Beispiel #1
0
        public async Task <List <string> > QueryBeLinkHash(string hash, string ipEndPoint = null)
        {
            Q2P_BeLinkHash q2p_BeLinkHash = new Q2P_BeLinkHash();

            q2p_BeLinkHash.ActorId = nodeManager.GetMyNodeId();
            q2p_BeLinkHash.hash    = hash;

            Session session = null;

            if (ipEndPoint != null && ipEndPoint != "")
            {
                session = await networkInner.Get(NetworkHelper.ToIPEndPoint(ipEndPoint));
            }
            if (session != null && !session.IsConnect())
            {
                session = null;
            }

            if (session == null)
            {
                NodeManager.NodeData node = nodeManager.GetRandomNode();
                if (node != null)
                {
                    session = await networkInner.Get(NetworkHelper.ToIPEndPoint(node.ipEndPoint));
                }
            }

            if (session != null)
            {
                R2P_BeLinkHash r2p_BeLinkHash = (R2P_BeLinkHash)await session.Query(q2p_BeLinkHash);

                if (r2p_BeLinkHash != null && r2p_BeLinkHash.hashs != null && r2p_BeLinkHash.hashs != "")
                {
                    return(JsonHelper.FromJson <List <string> >(r2p_BeLinkHash.hashs));
                }
            }

            return(null);
        }
Beispiel #2
0
        public TValue Get(string table, int index)
        {
            TValue currValue   = null;
            string table_index = $"{prefix}___{table}__{index}";

            if (currDic.TryGetValue(table_index, out currValue))
            {
                return(currValue);
            }

            string value = db.Get(table_index, options);

            if (value != null)
            {
                if (!isString)
                {
                    return(JsonHelper.FromJson <Slice>(value).obj);
                }
                return(value as TValue);
            }
            return(null);
        }
Beispiel #3
0
        public static void ExportAll(string exportDirectory, bool forceRegenerate = true)
        {
            if (!Directory.Exists(exportDirectory))
            {
                Directory.CreateDirectory(exportDirectory);
            }

            string md5File = Path.Combine(ExcelPath, "md5.txt");
            if (!File.Exists(md5File))
            {
                md5Info = new ExcelMD5Info();
            }
            else
            {
                md5Info = JsonHelper.FromJson<ExcelMD5Info>(File.ReadAllText(md5File));
            }

            string[] files = Directory.GetFiles(ExcelPath);
            foreach (string filePath in files)
            {
                if (filePath.Length < 12 || Path.GetFileName(filePath).StartsWith("~") || !filePath.EndsWith("Config.xlsx"))
                {
                    continue;
                }
                string fileName = Path.GetFileName(filePath);
                string oldMD5 = md5Info.Get(fileName);
                string md5 = MD5Helper.FileMD5(filePath);
                md5Info.Add(fileName, md5);
                if (md5 == oldMD5 && !forceRegenerate)
                {
                    continue;
                }

                Export(filePath, exportDirectory);
            }

            File.WriteAllText(md5File, JsonHelper.ToJson(md5Info));
        }
Beispiel #4
0
        public void TestOnSubmit(HttpMessage httpMessage)
        {
            if (httpMessage.map["cmd"].ToLower() != "submit")
            {
                return;
            }

            var resultMap = JsonHelper.FromJson <Dictionary <string, string> >(httpMessage.result);

            resultMap.TryGetValue("hashmining", out string hashmining);

            if (Pool.registerPool || string.IsNullOrEmpty(hashmining))
            {
                return;
            }

            string address = httpMessage.map["address"];
            string number  = httpMessage.map["number"];

            for (int i = 0; i < 20000; i++)
            {
                MinerTask minerTask = NewNextTakID(height, address, number);
                if (minerTask != null)
                {
                    string randomTemp;
                    randomTemp = minerTask.taskid + System.Guid.NewGuid().ToString("N").Substring(0, 13);

                    string hash  = BlockDag.ToHash(minerTask.height, hashmining, randomTemp);
                    double diff  = Helper.GetDiff(hash);
                    double power = CalculatePower.Power(diff);

                    minerTask.diff = diff;
                    minerTask.random.Add(randomTemp);
                    minerTask.power         = power;
                    minerTask.power_average = power.ToString();
                }
            }
        }
Beispiel #5
0
        int OpenWallet(string password)
        {
            passwords = password;
            try
            {
                string allText    = File.ReadAllText(walletFile, System.Text.Encoding.UTF8);
                var    walletJson = JsonHelper.FromJson <WalletJson>(allText);
                if (walletJson == null || walletJson.version < 101)
                {
                    return(-3);
                }
                var aes256 = new AesEverywhere.AES256();

                for (int i = 0; i < walletJson.accounts.Count; i++)
                {
                    WalletKey walletKey = new WalletKey();
                    string    base64    = aes256.Decrypt(walletJson.accounts[i].encrypted, passwords);
                    walletKey.random = base64.HexToBytes();

                    ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, walletKey.random);

                    if (walletKey.ToAddress() != walletJson.accounts[i].address)
                    {
                        return(-2);
                    }

                    keys.Add(walletKey);
                }

                curIndex = walletJson.curIndex;
            }
            catch (Exception)
            {
                return(-1);
            }
            return(1);
        }
        public static HttpMessage QuerySync(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()); //把服务端返回的信息转成字符串
                //var str = HttpClient.Post(url, jsonModel);
                HttpMessage response = new HttpMessage();
                response.map = JsonHelper.FromJson <Dictionary <string, string> >(str);
                return(response);
            }
        }
Beispiel #7
0
        /// <summary>
        /// 获取远程版本文件
        /// </summary>
        /// <returns></returns>
        public static async ETTask <VersionConfig> GetRemoteVersion()
        {
            VersionConfig remoteVersionConfig;

            string versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                }
            }
            catch (Exception e)
            {
                Log.Error($"download version.txt error:{e}");

                throw;
            }

            return(remoteVersionConfig);
        }
Beispiel #8
0
        public void GetAccounts(HttpMessage httpMessage)
        {
            var buffer = Base58.Decode(httpMessage.map["List"]).ToStr();
            var list   = JsonHelper.FromJson <List <string> >(buffer);

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                var accounts = new Dictionary <string, Account>();
                for (int i = 0; i < list.Count; i++)
                {
                    Account account = dbSnapshot.Accounts.Get(list[i]);
                    if (account == null)
                    {
                        account = new Account()
                        {
                            address = list[i], amount = "0", index = 0, notice = 0
                        };
                    }
                    accounts.Remove(account.address);
                    accounts.Add(account.address, account);
                }
                httpMessage.result = JsonHelper.ToJson(accounts);
            }
        }
Beispiel #9
0
        public virtual async ETTask LoadAsync()
        {
            this.dictionary = new Dictionary <long, IConfig>();

            UnityEngine.Debug.Log($"解析配置{ConfigType.Name}...");
            string configStr = "";

            if (UnityEngine.Application.isPlaying)
            {
                configStr = (await UnityEngine.AddressableAssets.Addressables.LoadAssetAsync <UnityEngine.TextAsset>(ConfigType.Name).Task).text;
            }
            else
            {
                configStr = File.ReadAllText($"Assets/AddressableAssets/Config/{ConfigType.Name}.txt");
            }
            foreach (string str in configStr.Split(new[] { "\n" }, StringSplitOptions.None))
            {
                try
                {
                    string str2 = str.Trim();
                    if (str2 == "" || str.StartsWith("//"))
                    {
                        continue;
                    }
                    T t = JsonHelper.FromJson <T>(str2);
                    this.dictionary.Add(t.Id, t);
                }
                catch (Exception e)
                {
                    string str2 = str.Trim();

                    UnityEngine.Debug.Log($"解析配置{str2}...");
                    throw new Exception($"parser json fail: {str}", e);
                }
            }
        }
Beispiel #10
0
        // Miner reward, only after confirming that it cannot be rolled back
        public Dictionary <string, BlockSub> GetMinerReward_PPLNS(long minHeight, long maxHeight)
        {
            Dictionary <string, BlockSub> minerTransfer = new Dictionary <string, BlockSub>();

            if (httpPool != null)
            {
                string addressIn = Wallet.GetWallet().GetCurWallet().ToAddress();

                for (long rewardheight = minHeight; rewardheight < maxHeight; rewardheight++)
                {
                    Dictionary <string, MinerTask> miners = null;
                    using (DbSnapshot snapshot = PoolDBStore.GetSnapshot())
                    {
                        string json = snapshot.Get("Pool_H2_" + rewardheight);
                        if (!string.IsNullOrEmpty(json))
                        {
                            miners = JsonHelper.FromJson <Dictionary <string, MinerTask> >(json);
                        }
                    }

                    if (miners != null)
                    {
                        var mcblk = GetMcBlock(rewardheight);
                        if (mcblk == null)
                        {
                            throw new Exception($"GetMcBlock({rewardheight}) return null");
                        }

                        if (mcblk != null && mcblk.Address == ownerAddress)
                        {
                            double reward = Consensus.GetReward(rewardheight);
                            reward = reward * (1.0f - GetServiceFee());

                            var miner = miners.Values.FirstOrDefault(c => c.random.IndexOf(mcblk.random) != -1);
                            if (miner == null)
                            {
                                continue;
                            }

                            // Total power
                            double powerSum = 0;
                            var    Values   = miners.Values.ToList();
                            for (var ii = 0; ii < Values.Count; ii++)
                            {
                                var dic = Values[ii];
                                if (string.IsNullOrEmpty(dic.address))
                                {
                                    continue;
                                }
                                double power = CalculatePower.Power(dic.diff);
                                if (power < HttpPool.ignorePower)
                                {
                                    continue;
                                }
                                powerSum += power;
                            }

                            // Reward for participation
                            BlockSub transfer = null;
                            for (var ii = 0; ii < Values.Count; ii++)
                            {
                                var dic = Values[ii];
                                if (string.IsNullOrEmpty(dic.address))
                                {
                                    continue;
                                }
                                double power = CalculatePower.Power(dic.diff);
                                double pay   = Math.Round(power * reward / powerSum, 8);

                                if (minerTransfer.TryGetValue(dic.address, out transfer))
                                {
                                    if (power < HttpPool.ignorePower)
                                    {
                                        transfer.height += 1; // 这里表示无效提交数
                                        continue;
                                    }

                                    transfer.nonce += 1; // 这里表示有效提交数
                                    transfer.amount = BigHelper.Add(transfer.amount, pay.ToString("N8"));
                                }
                                else
                                if (pay >= 0.002)
                                {
                                    transfer            = new BlockSub();
                                    transfer.nonce      = 1; // 这里表示有效提交数
                                    transfer.addressIn  = addressIn;
                                    transfer.addressOut = dic.address;
                                    transfer.amount     = BigHelper.Sub(pay.ToString("N8"), "0.002"); // 扣除交易手续费
                                    transfer.data       = CryptoHelper.Sha256($"{mcblk.hash}_{maxHeight}_{ownerAddress}_{dic.address}_MinerReward");
                                    if (power < HttpPool.ignorePower)
                                    {
                                        transfer.height += 1; // 这里表示无效提交数
                                        continue;
                                    }

                                    minerTransfer.Add(transfer.addressOut, transfer);
                                }
                            }
                        }
                    }
                }

                // 有效提交次数越多收益越高
                var totalAmount1 = "0"; // 总账1
                var totalAmount2 = "0"; // 总账2
                foreach (var transfer in minerTransfer.Values)
                {
                    try
                    {
                        totalAmount1 = BigHelper.Add(totalAmount1, transfer.amount);
                        var totalSubmit = transfer.nonce + transfer.height;
                        var share       = (float)transfer.nonce / (float)totalSubmit;
                        transfer.type    = $"{Math.Round(share * 100, 2)}%"; // 有效提交百分比
                        share           *= share;
                        transfer.remarks = BigHelper.Mul(share.ToString(), transfer.amount);
                        totalAmount2     = BigHelper.Add(totalAmount2, transfer.remarks);
                    }
                    catch (Exception)
                    {
                        transfer.type    = "0%";
                        transfer.remarks = "0";
                    }
                }

                var totalAmount3 = "0"; // 总账3
                foreach (var transfer in minerTransfer.Values)
                {
                    try
                    {
                        transfer.amount = BigHelper.Div(BigHelper.Mul(transfer.remarks, totalAmount1), totalAmount2);
                        totalAmount3    = BigHelper.Add(totalAmount3, transfer.amount);
                    }
                    catch (Exception)
                    {
                    }
                }

                //if (BigHelper.Greater(BigHelper.Abs(BigHelper.Sub(totalAmount1, totalAmount3)), "0.002", true))
                //{
                //    Log.Warning($"|totalAmount1 - totalAmount3| > 0.002 {BigHelper.Sub(totalAmount1, totalAmount3)}");
                //}
            }
            return(minerTransfer);
        }
Beispiel #11
0
        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);
        }
Beispiel #12
0
        public async void Run(bool bRun)
        {
            await Task.Delay(1 * 1000);

            List <string> list = JsonHelper.FromJson <List <string> >(Program.jdNode["NodeSessions"].ToString());

            // Get Internet IP
            try
            {
                Session session = await networkInner.Get(NetworkHelper.ToIPEndPoint(list[0]));

                Q2P_IP_INFO qIPNode = new Q2P_IP_INFO();
                R2P_IP_INFO rIPNode = (R2P_IP_INFO)await session.Query(qIPNode, 0.3f);

                networkInner.ipEndPoint = NetworkHelper.ToIPEndPoint(GetIpV4() + ":" + networkInner.ipEndPoint.Port);
                if (rIPNode != null)
                {
                    networkInner.ipEndPoint = NetworkHelper.ToIPEndPoint(rIPNode.address + ":" + networkInner.ipEndPoint.Port);
                }
            }
            catch (Exception)
            {
            }
            Log.Info($"NodeManager  {networkInner.ipEndPoint.ToString()}");
            Log.Info($"NodeSessions {list[0]}");

            //
            Q2P_New_Node new_Node = new Q2P_New_Node();

            new_Node.ActorId    = GetMyNodeId();
            new_Node.address    = Wallet.GetWallet().GetCurWallet().ToAddress();
            new_Node.ipEndPoint = networkInner.ipEndPoint.ToString();

            long state     = 0;
            var  consensus = Entity.Root.GetComponent <Consensus>();

            if (consensus != null)
            {
                state |= consensus.transferShow ? EnumState.transferShow : 0;
                state |= consensus.openSyncFast ? EnumState.openSyncFast : 0;
            }
            state           |= Entity.Root.GetComponentInChild <RelayNetwork>() != null ? EnumState.RelayNetwork : 0;
            new_Node.state   = state;
            new_Node.version = BlockMgr.networkID;

            while (bRun && list.Count > 0)
            {
                try
                {
                    for (int ii = 0; ii < list.Count; ii++)
                    {
                        bool bResponse = false;
                        new_Node.HashCode = StringHelper.HashCode(JsonHelper.ToJson(nodes));
                        Session session = await networkInner.Get(NetworkHelper.ToIPEndPoint(list[ii]));

                        if (session != null && session.IsConnect())
                        {
                            //Log.Debug($"NodeSessions connect " + r2P_New_Node.ActorId);
                            //session.Send(new_Node);

                            long         sendTime     = TimeHelper.Now();
                            R2P_New_Node r2P_New_Node = (R2P_New_Node)await session.Query(new_Node, 3f);

                            if (r2P_New_Node != null)
                            {
                                long timeNow = TimeHelper.Now();
                                nodeTimeOffset = (timeNow - sendTime) / 2 + r2P_New_Node.nodeTime - timeNow;
                                if (!string.IsNullOrEmpty(r2P_New_Node.Nodes))
                                {
                                    nodes = JsonHelper.FromJson <List <NodeData> >(r2P_New_Node.Nodes);
                                }
                                if (!string.IsNullOrEmpty(r2P_New_Node.Message))
                                {
                                    Log.Warning($"NodeSessions: {r2P_New_Node.Message}");
                                }
                                bResponse = true;
                            }
                        }
                        if (bResponse)
                        {
                            break;
                        }
                    }

                    // 等待5秒后关闭连接
                    await Task.Delay(5 * 1000);
                }
                catch (Exception)
                {
                    await Task.Delay(5 * 1000);
                }
            }
        }
Beispiel #13
0
        public async Task StartAsync()
        {
            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                string versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                Log.Debug(versionUrl);
                await request.DownloadAsync(versionUrl);

                this.VersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            Log.Debug("WebVersion:\n" + JsonHelper.ToJson(this.VersionConfig));

            // 对比本地的Version.txt
            string versionPath = Path.Combine(PathHelper.AppHotfixResPath, "Version.txt");

            if (!File.Exists(versionPath))
            {
                foreach (FileVersionInfo versionInfo in this.VersionConfig.FileInfoDict.Values)
                {
                    if (versionInfo.File == "Version.txt")
                    {
                        continue;
                    }
                    this.bundles.Enqueue(versionInfo.File);
                    this.TotalSize += versionInfo.Size;
                }
            }
            else
            {
                VersionConfig localVersionConfig = JsonHelper.FromJson <VersionConfig>(File.ReadAllText(versionPath));
                Log.Debug("LocalVersion:\n" + JsonHelper.ToJson(localVersionConfig));
                // 先删除服务器端没有的ab
                foreach (FileVersionInfo fileVersionInfo in localVersionConfig.FileInfoDict.Values)
                {
                    if (this.VersionConfig.FileInfoDict.ContainsKey(fileVersionInfo.File))
                    {
                        continue;
                    }
                    string abPath = Path.Combine(PathHelper.AppHotfixResPath, fileVersionInfo.File);
                    File.Delete(abPath);
                }

                // 再下载
                foreach (FileVersionInfo fileVersionInfo in this.VersionConfig.FileInfoDict.Values)
                {
                    FileVersionInfo localVersionInfo;
                    if (localVersionConfig.FileInfoDict.TryGetValue(fileVersionInfo.File, out localVersionInfo))
                    {
                        if (fileVersionInfo.MD5 == localVersionInfo.MD5)
                        {
                            continue;
                        }
                    }

                    if (fileVersionInfo.File == "Version.txt")
                    {
                        continue;
                    }

                    this.bundles.Enqueue(fileVersionInfo.File);
                    this.TotalSize += fileVersionInfo.Size;
                }
            }

            if (this.bundles.Count == 0)
            {
                return;
            }

            Log.Debug($"need download bundles: {this.bundles.ToList().ListToString()}");
            await this.WaitAsync();
        }
Beispiel #14
0
        public async void Run()
        {
            await Task.Delay(2000);

            long.TryParse(levelDBStore.Get("UndoHeight"), out transferHeight);

            Log.Debug($"Consensus.Run at height {transferHeight}");

            // 恢复到停机前的高度
            ApplyBlockChain();

            // 算力统计
            calculatePower.Clear();
            for (long ii = Math.Max(1, transferHeight - calculatePower.statistic); ii <= transferHeight; ii++)
            {
                calculatePower.Insert(BlockChainHelper.GetMcBlock(ii));
            }

            int blockIndex = 0;

            while (true)
            {
                try
                {
                    if (newBlocks.Count > 0)
                    {
                        for (blockIndex = blockIndex % newBlocks.Count; blockIndex < newBlocks.Count; blockIndex++)
                        {
                            if (newBlocks[blockIndex] == null)
                            {
                                continue;
                            }
                            var   ipEndPoint = newBlocks[blockIndex].ipEndPoint;
                            Block otherMcBlk = JsonHelper.FromJson <Block>(newBlocks[blockIndex].block);
                            if (Check(otherMcBlk))
                            {
                                if (await SyncHeight(otherMcBlk, newBlocks[blockIndex].ipEndPoint))
                                {
                                    newBlocks.RemoveAll((x) => { return(x.ipEndPoint == ipEndPoint); });
                                    break;
                                }
                                //if (await SyncHeight(otherMcBlk, newBlocks[ii].ipEndPoint))
                                ApplyBlockChain();
                            }
                            //break;
                        }
                    }

                    ApplyBlockChain();

                    lock (this)
                    {
                        runAction?.Invoke();
                        runAction = null;
                    }

                    if (bifurcatedReportTime.IsPassOnce() && bifurcatedReport != "")
                    {
                        Log.Info(bifurcatedReport);
                        bifurcatedReport = "";
                    }

                    await Task.Delay(1000);
                }
                catch (Exception e)
                {
                    newBlocks.Clear();
                    Log.Error(e);
                    await Task.Delay(1000);
                }
            }
        }
Beispiel #15
0
 public static T ToObject <T>(string str)
 {
     return(JsonHelper.FromJson <T>(str));
 }
Beispiel #16
0
 public T DeserializeFrom <T>(string str)
 {
     return(JsonHelper.FromJson <T>(str));
 }
Beispiel #17
0
        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);
        }
Beispiel #18
0
        public MinerView GetMinerView(string address, long transferIndex, long transferColumn, long minerIndex, long minerColumn)
        {
            transferColumn = Math.Min(transferColumn, 100);
            minerColumn    = Math.Min(minerColumn, 100);

            var minerView = new MinerView();

            minerView.address = address;

            var transfers_cur = MinerReward_PPLNS(false)?.Values.FirstOrDefault(c => c.addressOut == address);

            if (transfers_cur != null)
            {
                minerView.amount_cur = transfers_cur.amount;
            }

            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.GetMinerReward(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);

                    totalPower += power_average;
                }
                minerView.totalMiners = minerList.Count;
            }

            minerView.totalPower = CalculatePower.GetPowerCompany(totalPower);

            return(minerView);
        }
Beispiel #19
0
        //对比本地资源和服务器资源
        public async ETTask StartAsync(string fileFoldr = "", string versionName = "Version.txt")
        {
            downloadFoldr = fileFoldr;
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    versionUrl = Path.Combine(GlobalConfigComponent.Instance.GlobalProto.GetUrl(), "StreamingAssets", downloadFoldr, versionName);
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                }
            }
            catch (Exception e)
            {
                pLoserCall?.Invoke(e.ToString());
                throw new Exception($"url: {versionUrl}", e);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(PathHelper.AppHotfixResPath, downloadFoldr));

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }
                    if (fileInfo.Name == versionName)
                    {
                        continue;
                    }
                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }


            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                this.bundles.Enqueue(fileVersionInfo.File);
                this.TotalSize += fileVersionInfo.Size;
            }
            await DownloadAsync();
        }
        /// <summary>
        /// 开始下载远程Version文件进行本地对比 确认需要下载的AB包文件
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    //从Resources文件夹读取“VK”预制体上的TXT文档取得AB资源服务区地址 得到最新的Version.txt
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                    //Log.Debug(versionUrl);
                    await webRequestAsync.DownloadAsync(versionUrl);                     //下载资源

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    //Log.Debug(JsonHelper.ToJson(this.VersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;
            //得到本地Version文件地址
            string versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件 获取本地热更新文件夹
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)             //如果有这个文件夹
            {
                //得到文件夹内所有文件
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    //新的版本配置表中没有这个文件 就删除此文件
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }

                    fileInfo.Delete();
                }
            }
            else
            {
                //否则就创建新的热更新资源文件夹
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 本地
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                this.bundles.Enqueue(fileVersionInfo.File);                 //需要重新下载的AB包的名字
                this.TotalSize += fileVersionInfo.Size;                     //需要下载的资源的总大小
            }
        }
Beispiel #21
0
        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);
        }
Beispiel #22
0
        private static void Main(string[] args)
        {
            Dictionary <string, string> param = new Dictionary <string, string>();

            for (int i = 0; i < args.Length; i++)
            {
                int jj = args[i].IndexOf(':');
                if (jj != -1)
                {
                    param.TryAdd(args[i].Substring(0, jj).Replace("-", ""), args[i].Substring(jj + 1, args[i].Length - (jj + 1)));
                }
                else
                {
                    param.TryAdd(args[i].Replace("-", ""), "true");
                }
            }

            param.TryAdd("configure", "");
            param.TryAdd("node", "All");
            param.TryAdd("wallet", "./Data/wallet.json");
            param.TryAdd("db", "./Data/LevelDB");
            param.TryAdd("node", "All");

            if (param.TryGetValue("index", out string index))
            {
                param["wallet"] = param["wallet"].Replace(".json", $"{index}.json");
                param["db"]     = param["db"] + index;
            }

            if (param.ContainsKey("miner"))
            {
                RandomXSharp.RandomX.randomx_init(param.ContainsKey("fullmem"));
                Entity.Root.AddComponent <Miner>().Init(param);
                Update();
                return;
            }
            RandomXSharp.RandomX.randomx_init(false);

            //RandomXSharp.RandomX.Test1(args);
            //return;

            //Wallet.Import("");
            //return;

            //BigHelper.Test();
            //return;

            //CalculatePower.Test();
            //return;

            //Wallet.Test2();
            //return;

            //Wallet.Test3();
            //return;

            // 测试代码
            //LuaVMEnv.TestRapidjson(args);
            //LuaVMEnv.TestLib(args);
            //LuaVMEnv.TestCoroutine(args);
            //LuaVMEnv.Test_number(args);
            //LevelDBStore.test_delete(args);
            //LevelDBStore.test_undo(args);
            //LevelDBStore.Export2CSV_Block(args);
            //LevelDBStore.test_ergodic(args);
            //return;
            //Log.Info(Environment.CurrentDirectory);

            if (param.TryGetValue("makeSnapshot", out string _))
            {
                LevelDBStore.MakeSnapshot(param);
                return;
            }

            string walletFile = param["wallet"];
            Wallet wallet     = Wallet.GetWallet(walletFile);

            if (wallet == null)
            {
                return;
            }

            if (param.TryGetValue("makeGenesis", out string _))
            {
                Consensus.MakeGenesis();
                return;
            }

            //DisbleQuickEditMode();
            Console.Clear();
            Console.CursorVisible = false;
#if !RELEASE
            Console.Title = $"SmartX 配置: {param["configure"]} {index} Address: {wallet.GetCurWallet().ToAddress()} Debug";
#else
            Console.Title = $"SmartX 配置: {param["configure"]} {index} Address: {wallet.GetCurWallet().ToAddress()} Release";
#endif
            Log.Debug($"address: {wallet.GetCurWallet().ToAddress()}");

            string NodeKey = param["node"];
            // 异步方法全部会回调到主线程
            SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance);
            AssemblyHelper.AddAssembly("Base", typeof(AssemblyHelper).Assembly);
            AssemblyHelper.AddAssembly("App", typeof(Program).Assembly);

            // check contract
            var contractHash = FileHelper.HashDirectory("Data/Contract", CryptoHelper.Sha256);
            if (contractHash != "da4d968db3d8a7360873221cb917c9fcb073600968c2e88a22640b90c529d0f1")
            {
                Log.Debug($"contractHash error: {contractHash}");
#if RELEASE
                return;
#endif
            }

            // 读取配置文件
            try
            {
                StreamReader sr     = new StreamReader(new FileStream(param["configure"], FileMode.Open, FileAccess.Read, FileShare.ReadWrite), System.Text.Encoding.UTF8);
                string       strTxt = sr.ReadToEnd();
                strTxt = strTxt.Replace("0.0.0.0", NodeManager.GetIpV4());
                sr.Close(); sr.Dispose();
                JToken jd = JToken.Parse(strTxt);
                jdNode = jd[NodeKey];
            }
            catch (Exception e)
            {
                Log.Info(e.ToString());
                Log.Error($"configure file: {param["configure"]} on exists ro json foramt error.");
                Console.ReadKey();
                return;
            }

            if (jdNode != null)
            {
                Log.Debug("启动: " + jdNode["appType"]);

                // DNS
                List <string> list = JsonHelper.FromJson <List <string> >(jdNode["NodeSessions"].ToString());
                for (int ii = 0; ii < list.Count; ii++)
                {
                    list[ii] = NetworkHelper.DnsToIPEndPoint(list[ii]);
                }
                jdNode["NodeSessions"] = JsonHelper.ToJson(list);

                if (!string.IsNullOrEmpty(index))
                {
                    if (jdNode["HttpRpc"] != null)
                    {
                        jdNode["HttpRpc"]["ComponentNetworkHttp"]["address"] = ((string)jdNode["HttpRpc"]["ComponentNetworkHttp"]["address"]).Replace("8101", (8100 + int.Parse(index)).ToString());
                    }
                    if (jdNode["HttpPool"] != null)
                    {
                        jdNode["HttpPool"]["ComponentNetworkHttp"]["address"] = ((string)jdNode["HttpPool"]["ComponentNetworkHttp"]["address"]).Replace("9101", (9100 + int.Parse(index)).ToString());
                    }
                    if (jdNode["SmartxRpc"] != null)
                    {
                        jdNode["SmartxRpc"]["ComponentNetworkHttp"]["address"] = ((string)jdNode["SmartxRpc"]["ComponentNetworkHttp"]["address"]).Replace("5000", ((5000 - 1) + int.Parse(index)).ToString());
                    }
                    if (jdNode["ComponentNetworkInner"] != null)
                    {
                        jdNode["ComponentNetworkInner"]["address"] = ((string)jdNode["ComponentNetworkInner"]["address"]).Replace("58601", (58600 + int.Parse(index)).ToString());
                    }
                    if (jdNode["RelayNetwork"] != null)
                    {
                        jdNode["RelayNetwork"]["ComponentNetworkInner"]["address"] = ((string)jdNode["RelayNetwork"]["ComponentNetworkInner"]["address"]).Replace("57601", (57600 + int.Parse(index)).ToString());
                    }
                    if (jdNode["Pool"] != null)
                    {
                        jdNode["Pool"]["db_path"] = ((string)jdNode["Pool"]["db_path"]) + index;
                    }
                    if (jdNode["HttpPoolRelay"] != null)
                    {
                        jdNode["HttpPoolRelay"]["number"] = jdNode["HttpPoolRelay"]["number"].ToString().Replace("Pool1", "Pool" + index);
                    }
                }

                // 数据库路径
                if (jdNode["LevelDBStore"] != null && args.Length >= 3)
                {
                    jdNode["LevelDBStore"]["db_path"] = param["db"];
                }

                Entity.Root.AddComponent <ComponentStart>(jdNode);
            }

            //TransferProcess.Test();

            Update();
        }
Beispiel #23
0
 public object DeserializeFrom(Type type, string str)
 {
     return(JsonHelper.FromJson(type, str));
 }
Beispiel #24
0
        public async void Run()
        {
            await Task.Delay(2000);

            var httpRpc = Entity.Root.Find("HttpRpc")?.GetComponent <HttpRpc>();

            if (httpRpc == null)
            {
                return;
            }
            var consensus = Entity.Root.GetComponent <Consensus>();
            var luaVMEnv  = Entity.Root.GetComponent <LuaVMEnv>();

            var    httpMessage = new HttpMessage();
            string address     = Wallet.GetWallet().GetCurWallet().ToAddress();
            string consAddress = "";
            int    delayTime   = 60 * 1000 * 2;

            while (true)
            {
                await Task.Delay(delayTime);

                try
                {
                    if (consensus.IsRule(consensus.transferHeight, address))
                    {
                        continue;
                    }

                    if (string.IsNullOrEmpty(consAddress))
                    {
                        if (httpMessage.map == null)
                        {
                            httpMessage.map = new Dictionary <string, string>();
                            httpMessage.map.Add("1", consensus.PledgeFactory);
                            httpMessage.map.Add("2", $"getPair(\"{address}\")");
                        }
                        httpRpc.callFun(httpMessage);
                        if (!httpMessage.result.Contains("error"))
                        {
                            consAddress = JsonHelper.FromJson <string>(httpMessage.result);
                            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot())
                            {
                                if (!luaVMEnv.IsERC(dbSnapshot, consAddress, null))
                                {
                                    consAddress = "";
                                }
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(consAddress))
                    {
                        continue;
                    }

                    if (!Wallet.CheckAddress(consAddress))
                    {
                        continue;
                    }

                    Account account = null;
                    using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
                    {
                        account = dbSnapshot.Accounts.Get(consAddress);
                    }
                    if (account == null)
                    {
                        continue;
                    }

                    var rulers = consensus.GetRule(consensus.transferHeight);
                    if (rulers == null)
                    {
                        continue;
                    }

                    int    rulerCount     = 0;
                    string rulerAmountMin = "";
                    foreach (RuleInfo info in rulers.Values)
                    {
                        if (info.End == -1 || info.End > consensus.transferHeight)
                        {
                            rulerCount++;
                            rulerAmountMin = rulerAmountMin == "" ? info.Amount : BigHelper.Min(rulerAmountMin, info.Amount);
                        }
                    }

                    if ((rulerCount < 25 && BigHelper.Greater(account.amount, "3000000", true)) ||
                        BigHelper.Greater(account.amount, rulerAmountMin, false))
                    {
                        httpRpc.OnBeRulerReal(httpMessage);
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// 注入参数
        /// </summary>
        /// <param name="context"></param>
        /// <param name="methodInfo"></param>
        /// <param name="postbody"></param>
        /// <returns></returns>
        private static object[] InjectParameters(HttpListenerContext context, MethodInfo methodInfo, string postbody)
        {
            context.Response.StatusCode = 200;
            ParameterInfo[] parameterInfos = methodInfo.GetParameters();
            object[]        args           = new object[parameterInfos.Length];
            for (int i = 0; i < parameterInfos.Length; i++)
            {
                ParameterInfo item = parameterInfos[i];

                if (item.ParameterType == typeof(HttpListenerRequest))
                {
                    args[i] = context.Request;
                    continue;
                }

                if (item.ParameterType == typeof(HttpListenerResponse))
                {
                    args[i] = context.Response;
                    continue;
                }

                try
                {
                    switch (context.Request.HttpMethod)
                    {
                    case "POST":
                        if (item.Name == "postBody")                                 // 约定参数名称为postBody,只传string类型。本来是byte[],有需求可以改。
                        {
                            args[i] = postbody;
                        }
                        else if (item.ParameterType.IsClass && item.ParameterType != typeof(string) && !string.IsNullOrEmpty(postbody))
                        {
                            object entity = JsonHelper.FromJson(item.ParameterType, postbody);
                            args[i] = entity;
                        }

                        break;

                    case "GET":
                        string query = context.Request.QueryString[item.Name];
                        if (query != null)
                        {
                            object value = Convert.ChangeType(query, item.ParameterType);
                            args[i] = value;
                        }

                        break;

                    default:
                        args[i] = null;
                        break;
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    args[i] = null;
                }
            }

            return(args);
        }
Beispiel #26
0
        public async ETTask StartAsync()
        {
            alreadyDownloadBytes = 0;

            TotalSize = 0;

            CurrVersionBytes = 0;

            string versionUrl = "";

            versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";

            Log.Debug($"当前资源为AB模式,远程版本文件路径:" + versionUrl);

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    await webRequestAsync.DownloadAsync(versionUrl);

                    CurrVersionBytes += (long)webRequestAsync.Request.downloadedBytes;

                    // 获取远程的Version.txt
                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                }
            }
            catch (Exception e)
            {
                Log.Error($"download version.txt error: {e}");
                return;
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;

            string versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                Log.Debug("本地版本文件路径:" + versionPath);

                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }

                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }
            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                //如果MD5相同,且当前项目不含有这个文件
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }

                if (IsFilterRes(fileVersionInfo.File))
                {
                    continue;
                }

                this.bundles.Enqueue(fileVersionInfo.File);

                this.TotalSize += fileVersionInfo.Size;
            }
        }
Beispiel #27
0
        private static async System.Threading.Tasks.Task Main(string[] args)
        {
            Wallet wallet = new Wallet();

            try
            {
                Dictionary <string, string> setip = new Dictionary <string, string>();
                string       wordTemplateName     = "./ip.json";
                StreamReader sr       = File.OpenText(wordTemplateName);
                string       jsonWord = sr.ReadToEnd();
                setip = JsonHelper.FromJson <Dictionary <string, string> >(jsonWord);
                string ips = setip["ip"].Split(":")[0];
                if (System.Net.IPAddress.TryParse(ips, out IPAddress ip))
                {
                    ruleIP = "http://" + ip.ToString() + ":" + setip["ip"].Split(":")[1];
                }
                else
                {
                    IPHostEntry host = Dns.GetHostEntry(ips);
                    ip     = host.AddressList[0];
                    ruleIP = "http://" + ip.ToString() + ":" + setip["ip"].Split(":")[1];
                }
            }
            catch (Exception e)
            {
                try
                {
                    if (System.Net.IPAddress.TryParse(args[0], out IPAddress ip))
                    {
                        ruleIP = "http://" + ip.ToString() + ":" + args[1];
                    }
                    else
                    {
                        IPHostEntry host = Dns.GetHostEntry(args[0]);
                        ip     = host.AddressList[0];
                        ruleIP = "http://" + ip.ToString() + ":" + args[1];
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Please check the IP file and input IP port");
                    while (true)
                    {
                        ;
                    }
                }
            }

            //string web = "seednode.smartx.one";
            //IPHostEntry host = Dns.GetHostEntry(web);
            //IPAddress ip = host.AddressList[0];
            //ruleIP = "http://" + ip.ToString();
            //ruleIP += ":5000";
            ////ruleIP = "http://192.168.1.101:5000";

            while (true)
            {
                Console.Write("smartx>");

                HttpMessage httpMessage = new HttpMessage();
                httpMessage.map = new Dictionary <string, string>();

                string input = Console.ReadLine();
                Program.input = input;
                if (input == "")
                {
                    continue;
                }


                input = input.Replace("%20", " ");
                input = input.Replace("  ", " ");
                input = input.Replace("   ", " ");
                input = input.Replace("  ", " ");

                string[] array = input.Split(' ');

                for (int ii = 0; ii < array.Length; ii++)
                {
                    string arrayValue = array[ii];
                    httpMessage.map.Remove("" + ii);
                    httpMessage.map.Add("" + ii, arrayValue);
                }

                httpMessage.map.Add("cmd", array[0]);
                await Command.OrderAsync(httpMessage);

                if (httpMessage.result != null && httpMessage.map["cmd"] != "transfer")
                {
                    if (httpMessage.result.Contains("{"))
                    {
                        httpMessage.result = ConvertJsonString(httpMessage.result);
                    }
                }
                Console.WriteLine(httpMessage.result);
            }
        }
        static public void test_ergodic2(long height, string filename)
        {
            //
            //DBTests tests = new DBTests();
            //tests.SetUp();
            //tests.Snapshot();
            //var tempPath = System.IO.Directory.GetCurrentDirectory();
            //var randName = "Data\\LevelDB1";
            //var DatabasePath = System.IO.Path.Combine(tempPath, randName);
            //LevelDBStore dbstore = new LevelDBStore().Init(DatabasePath);
            LevelDBStore dbstore = Entity.Root.GetComponent <LevelDBStore>();

            // Create new iterator
            lock (dbstore.db)
            {
                string sum = "0";
                dbstore.UndoTransfers(height);
                using (var it = dbstore.db.CreateIterator())
                {
                    File.Delete("./" + filename + ".csv");
                    File.AppendAllText("./" + filename + ".csv", "height:" + height + "版本:" + NodeManager.networkIDCur + "\n");
                    // Iterate in reverse to print the values as strings
                    for (it.SeekToFirst(); it.IsValid(); it.Next())
                    {
                        //Log.Info($"Value as string: {it.KeyAsString()}");
                        if ((!it.KeyAsString().Contains("undo")) && (!it.KeyAsString().Contains("Undo")))
                        {
                            if (it.KeyAsString().IndexOf("Accounts___") == 0)
                            {
                                try
                                {
                                    Console.WriteLine($"Value as string: {it.ValueAsString()}");
                                    Dictionary <string, Dictionary <string, object> > kv = JsonHelper.FromJson <Dictionary <string, Dictionary <string, object> > >(it.ValueAsString());
                                    //all += long.Parse(kv["obj"]["amount"].ToString());
                                    File.AppendAllText("./" + filename + ".csv", kv["obj"]["address"].ToString() + "," + kv["obj"]["amount"].ToString() + "\n");
                                    BigHelper.Add(kv["obj"]["amount"].ToString(), sum);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(it.KeyAsString());
                                    Console.WriteLine($"出错了: {it.ValueAsString()}");
                                    Console.WriteLine(e.Message);
                                    break;
                                }
                            }
                            else
                            if (it.KeyAsString().Contains("Storages"))
                            {
                                var kv   = JsonHelper.FromJson <Dictionary <string, Dictionary <string, byte[]> > >(it.ValueAsString());
                                var json = SortJson(JToken.Parse(kv["obj"]["jsonData"].ToStr()), null);

                                File.AppendAllText("./" + filename + ".csv", it.KeyAsString().Replace("Storages___", "") + "," + json + "\n");
                            }
                            else
                            if (it.KeyAsString().Contains("StgMap"))
                            {
                                Console.WriteLine($"Value as string: {it.ValueAsString()}");
                                File.AppendAllText("./" + filename + ".csv", $"{it.KeyAsString()},{it.ValueAsString()}\n");
                            }
                        }
                    }
                    File.AppendAllText("./" + filename + ".csv", "All" + "," + sum + "\n");

                    long posProduct    = 0;
                    long powProduct    = 0;
                    long posOriginally = 0;
                    long powOriginally = 0;
                    for (long i = 1; i <= height; i++)
                    {
                        Block block        = BlockChainHelper.GetMcBlock(i);
                        long  posNodeCount = block.linksblk.Count;
                        posProduct    += posNodeCount * Consensus.GetRewardRule(i);
                        powProduct    += Consensus.GetReward(i);
                        posOriginally += 25 * Consensus.GetRewardRule(i);
                        powOriginally += Consensus.GetReward(i);
                    }

                    long All_Product = posProduct + powProduct;
                    File.AppendAllText("./" + filename + ".csv", "All_Product" + "," + All_Product + "\n");
                    File.AppendAllText("./" + filename + ".csv", "posProduct" + "," + posProduct + "\n");
                    File.AppendAllText("./" + filename + ".csv", "posOriginally" + "," + posOriginally + "\n");
                    File.AppendAllText("./" + filename + ".csv", "powOriginally" + "," + powOriginally + "\n");

                    Console.WriteLine("导出完成");
                }
            }
        }
Beispiel #29
0
        public async ETTask StartAsync()
        {
            // 获取远程的Version.txt
            string versionUrl = "";

            try
            {
                using (UnityWebRequestAsync webRequestAsync = ComponentFactory.Create <UnityWebRequestAsync>())
                {
                    versionUrl = GlobalConfigComponent.Instance.GlobalProto.GetUrl() + "StreamingAssets/" + "Version.txt";
                    //Log.Debug(versionUrl);
                    await webRequestAsync.DownloadAsync(versionUrl);

                    remoteVersionConfig = JsonHelper.FromJson <VersionConfig>(webRequestAsync.Request.downloadHandler.text);
                    //Log.Debug(JsonHelper.ToJson(this.VersionConfig));
                }
            }
            catch (Exception e)
            {
                throw new Exception($"url: {versionUrl}", e);
            }

            // 获取streaming目录的Version.txt
            VersionConfig streamingVersionConfig;
            string        versionPath = Path.Combine(PathHelper.AppResPath4Web, "Version.txt");

            using (UnityWebRequestAsync request = ComponentFactory.Create <UnityWebRequestAsync>())
            {
                await request.DownloadAsync(versionPath);

                streamingVersionConfig = JsonHelper.FromJson <VersionConfig>(request.Request.downloadHandler.text);
            }

            // 删掉远程不存在的文件
            DirectoryInfo directoryInfo = new DirectoryInfo(PathHelper.AppHotfixResPath);

            if (directoryInfo.Exists)
            {
                FileInfo[] fileInfos = directoryInfo.GetFiles();
                foreach (FileInfo fileInfo in fileInfos)
                {
                    if (remoteVersionConfig.FileInfoDict.ContainsKey(fileInfo.Name))
                    {
                        continue;
                    }

                    if (fileInfo.Name == "Version.txt")
                    {
                        continue;
                    }

                    fileInfo.Delete();
                }
            }
            else
            {
                directoryInfo.Create();
            }

            // 对比MD5
            foreach (FileVersionInfo fileVersionInfo in remoteVersionConfig.FileInfoDict.Values)
            {
                // 对比md5
                string localFileMD5 = BundleHelper.GetBundleMD5(streamingVersionConfig, fileVersionInfo.File);
                if (fileVersionInfo.MD5 == localFileMD5)
                {
                    continue;
                }
                this.bundles.Enqueue(fileVersionInfo.File);
                this.TotalSize += fileVersionInfo.Size;
            }
        }
        static public void MakeSnapshot(Dictionary <string, string> param)
        {
            Console.WriteLine($"levelDB.Init {param["db"]}");
            LevelDBStore levelDB = new LevelDBStore();

            levelDB.Init(param["db"]);

            if (param.ContainsKey("height") && long.TryParse(param["height"], out long height))
            {
                levelDB.UndoTransfers(height);
            }
            long.TryParse(levelDB.Get("UndoHeight"), out long transferHeight);
            Console.WriteLine($"transferHeight: {transferHeight}");

            var DatabasePath = $"./Data/LevelDB_Snapshot_{transferHeight}";

            if (Directory.Exists(DatabasePath))
            {
                Console.WriteLine($"Directory LevelDB_Snapshot Exists");
                return;
            }
            LevelDBStore snapshotDB = new LevelDBStore();

            snapshotDB.Init(DatabasePath);

            int count = 0;

            using (var it = levelDB.db.CreateIterator())
            {
                for (it.SeekToFirst(); it.IsValid(); it.Next(), count++)
                {
                    //Log.Info($"Value as string: {it.KeyAsString()}");
                    if (it.KeyAsString().IndexOf("_undo_") == -1 &&
                        it.KeyAsString().IndexOf("Blocks") != 0 &&
                        it.KeyAsString().IndexOf("BlockChain") != 0 &&
                        it.KeyAsString().IndexOf("Queue") != 0 &&
                        it.KeyAsString().IndexOf("List") != 0 &&
                        it.KeyAsString().IndexOf("Heights") != 0 &&
                        it.KeyAsString().IndexOf("Undos___") != 0)
                    {
                        if (it.KeyAsString().IndexOf("Trans___") == 0)
                        {
                            var slice = JsonHelper.FromJson <DbCache <BlockSub> .Slice>(it.ValueAsString());
                            if (slice != null && slice.obj.height != 0)
                            {
                                snapshotDB.Put(it.KeyAsString(), $"{{\"obj\":{{\"height\":{slice.obj.height}}}}}");
                                Console.WriteLine($"Processed tran: {it.KeyAsString()}");
                            }
                        }
                        else
                        if (it.KeyAsString().IndexOf("Snap___") == 0)
                        {
                            if (it.KeyAsString().IndexOf("Snap___Rule_") == 0)
                            {
                                var key         = it.KeyAsString();
                                var pos1        = "Snap___Rule_".Length;
                                var pos2        = key.Length;
                                var hegihtTemp1 = key.Substring(pos1, pos2 - pos1);
                                var hegihtTemp2 = long.Parse(hegihtTemp1);
                                if (hegihtTemp2 > transferHeight - 5 && hegihtTemp2 < transferHeight + 5)
                                {
                                    snapshotDB.Put(it.KeyAsString(), it.ValueAsString());
                                    Console.WriteLine($"Processed  key: {it.KeyAsString()}");
                                }
                            }
                            else
                            if (it.KeyAsString().IndexOf("_Reward") != -1)
                            {
                                var key  = it.KeyAsString();
                                var pos1 = "Snap___".Length;
                                var pos2 = key.IndexOf("_Reward");

                                var hegihtTemp1 = key.Substring(pos1, pos2 - pos1);
                                var hegihtTemp2 = long.Parse(hegihtTemp1);
                                if (hegihtTemp2 > transferHeight - 5 && hegihtTemp2 < transferHeight + 5)
                                {
                                    snapshotDB.Put(it.KeyAsString(), it.ValueAsString());
                                    Console.WriteLine($"Processed  key: {it.KeyAsString()}");
                                }
                            }
                            else
                            {
                                snapshotDB.Put(it.KeyAsString(), it.ValueAsString());
                                Console.WriteLine($"Processed  key: {it.KeyAsString()}");
                            }
                        }
                        else
                        {
                            snapshotDB.Put(it.KeyAsString(), it.ValueAsString());
                            Console.WriteLine($"Processed  key: {it.KeyAsString()}");
                        }
                    }

                    if (count % 1000000 == 0)
                    {
                        Console.WriteLine($"Processed Count:{count}");
                    }
                }
            }

            using (DbSnapshot dbNew = snapshotDB.GetSnapshot(0, true))
                using (DbSnapshot dbOld = levelDB.GetSnapshot())
                {
                    for (long ii = transferHeight - 3; ii <= transferHeight + 2; ii++)
                    {
                        Console.WriteLine($"Processed height: {ii}");
                        var heights = dbOld.Heights.Get(ii.ToString());
                        for (int jj = 0; jj < heights.Count; jj++)
                        {
                            dbNew.Blocks.Add(heights[jj], dbOld.Blocks.Get(heights[jj]));
                        }

                        dbNew.Heights.Add(ii.ToString(), heights);
                        dbNew.BlockChains.Add(ii.ToString(), dbOld.BlockChains.Get(ii.ToString()));
                    }

                    dbNew.Commit();
                }

            Console.WriteLine($"MakeSnapshot Complete");

            while (true)
            {
                System.Threading.Thread.Sleep(1000);
            }
        }