public static void OnGetMcBlock(HttpMessage httpMessage)
        {
            Dictionary <string, string> map = new Dictionary <string, string>();
            // 版本检查
            string version = httpMessage.map["version"];

            if (version != Miner.version)
            {
                map.Remove("report");
                map.Add("report", "error");
                map.Add("tips", $"Miner.version: {Miner.version}");
                return;
            }

            // 矿池登记检查
            if (Pool.registerPool && poolIpAddress.IndexOf(httpMessage.request.RemoteEndPoint.Address.ToString()) == -1)
            {
                map.Add("tips", "need register Pool");
                return;
            }

            long ___height = long.Parse(httpMessage.map["height"]);

            var mcblk = BlockChainHelper.GetMcBlock(___height);

            if (mcblk != null)
            {
                var poolBlock = new PoolBlock();
                poolBlock.hash     = mcblk.hash;
                poolBlock.Address  = mcblk.Address;
                poolBlock.random   = mcblk.random;
                httpMessage.result = JsonHelper.ToJson(poolBlock);
            }
        }
Example #2
0
        private void OnLatest_block(HttpMessage httpMessage)
        {
            var consensus = Entity.Root.GetComponent <Consensus>();
            var showCount = 10;

            var height = consensus.transferHeight;

            if (!GetParam(httpMessage, "Index", "index", out string index))
            {
                index = "0";
            }

            List <Block> BlockList = new List <Block>();

            for (long ii = height - showCount * int.Parse(index); ii > height - showCount * (int.Parse(index) + 1) && ii > 0; ii--)
            {
                Block myblk = BlockChainHelper.GetMcBlock(ii);

                if (myblk != null)
                {
                    BlockList.Add(myblk);
                }
            }
            httpMessage.result = JsonHelper.ToJson(BlockList);
        }
Example #3
0
        public void MinerReward()
        {
            if (httpPool != null)
            {
                Dictionary <string, MinerTask> miners = httpPool.GetMinerReward(out long miningHeight);
                if (miners != null && miningHeight + 3 < height)
                {
                    string ownerAddress = Wallet.GetWallet().GetCurWallet().ToAddress();

                    var mcblk = BlockChainHelper.GetMcBlock(miningHeight);
                    if (mcblk != null && mcblk.Address == ownerAddress)
                    {
                        var       miner     = miners.Values.First(c => c.random == mcblk.random);
                        WalletKey walletKey = Wallet.GetWallet().GetCurWallet();

                        // 出块奖励
                        if (miner != null)
                        {
                            Transfer transfer = new Transfer();
                            transfer.addressIn  = ownerAddress;
                            transfer.addressOut = miner.address;
                            transfer.amount     = Consensus.GetReward(miningHeight).ToString();
                            transfer.nonce      = TimeHelper.NowSeconds();
                            transfer.type       = "tranfer";
                            transfer.hash       = transfer.ToHash();
                            transfer.sign       = transfer.ToSign(walletKey);
                            minerTransfer.Add(mcblk.hash, transfer);
                        }

                        // 参与奖励
                    }
                    httpPool.DelMiner(miningHeight);
                }
            }
        }
Example #4
0
        public Dictionary <string, BlockSub> MinerReward_SOLO()
        {
            if (httpPool != null)
            {
                Dictionary <string, BlockSub>  minerTransfer = new Dictionary <string, BlockSub>();
                Dictionary <string, MinerTask> miners        = httpPool.GetMinerReward(out long miningHeight);
                if (miners != null && miningHeight + 5 < httpPool.height)
                {
                    string ownerAddress = Wallet.GetWallet().GetCurWallet().ToAddress();

                    var mcblk = BlockChainHelper.GetMcBlock(miningHeight);
                    if (mcblk != null && mcblk.Address == ownerAddress)
                    {
                        var miner = miners.Values.FirstOrDefault(c => c.random == mcblk.random);
                        if (miner != null)
                        {
                            var transfer = new BlockSub();
                            transfer.addressIn  = ownerAddress;
                            transfer.addressOut = miner.address;
                            transfer.type       = "transfer";
                            transfer.amount     = Consensus.GetReward(miningHeight).ToString();
                            transfer.data       = CryptoHelper.Sha256($"{mcblk.hash}_{ownerAddress}_{miner.address}_{transfer.amount}_Reward_SOLO");
                            minerTransfer.Add(transfer.addressOut, transfer);

                            transferProcess.AddTransferHandle(ownerAddress, miner.address, transfer.amount, transfer.data);
                            transferProcess.SaveTransferToDB();
                        }
                    }
                    httpPool.DelMiner(miningHeight);
                    return(minerTransfer);
                }
            }
            return(null);
        }
Example #5
0
        public static void Q2P_McBlockHash_Handle(Session session, int opcode, object msg)
        {
            Q2P_McBlockHash q2q_McBlockHash = msg as Q2P_McBlockHash;
            Block           mcbkl           = BlockChainHelper.GetMcBlock(q2q_McBlockHash.height);
            var             cons            = Entity.Root.GetComponent <Consensus>();

            if (mcbkl == null && cons.transferHeight + 3 >= q2q_McBlockHash.height)
            {
                // 取最新高度
                var chain1 = BlockChainHelper.GetBlockChain(cons.transferHeight);
                while (chain1 != null)
                {
                    if (q2q_McBlockHash.height == chain1.height)
                    {
                        mcbkl = chain1.GetMcBlock();
                        break;
                    }
                    chain1 = chain1.GetMcBlockNext();
                }
            }

            R2P_McBlockHash r2p_McBlockHash = new R2P_McBlockHash()
            {
                hash = mcbkl != null ? mcbkl.hash : ""
            };

            if (r2p_McBlockHash.hash == "")
            {
                r2p_McBlockHash.hash = "";
            }

            session.Reply(q2q_McBlockHash, r2p_McBlockHash);
        }
Example #6
0
        private void OnInfo(HttpMessage httpMessage)
        {
            //Infomsg infomsg = new Infomsg();
            Dictionary <string, object> infomsg = new Dictionary <string, object>();

            infomsg.Add("success", true);
            infomsg.Add("message", "successful operation");
            Dictionary <string, object> result = new Dictionary <string, object>();

            var   consensus = Entity.Root.GetComponent <Consensus>();
            var   height    = consensus.transferHeight;
            Block myblk     = BlockChainHelper.GetMcBlock(height);

            result.Add("network ", "testnet");
            string[] capabilities = { "SMARTX", "FAST_SYNC" };
            result.Add("capabilities", capabilities);
            result.Add("clientId", "Smartx/v1.0.0-Windows/amd64");
            result.Add("coinbase", "0xcc1ca38eda5dd60d243633e95b893a14c44b8df8");
            result.Add("activePeers", 2);
            result.Add("pendingTransactions", 10);
            result.Add("latestBlockNumber", height.ToString());
            result.Add("latestBlockHash", myblk.hash);
            infomsg.Add("result", result);
            httpMessage.result = JsonHelper.ToJson(infomsg);
        }
Example #7
0
        private void OnBlocktranHash(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "hash", out string hash))
            {
                httpMessage.result = "please input hash";
                return;
            }
            using (var dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                var transfer = dbSnapshot.Transfers.Get(hash);
                if (transfer != null)
                {
                    Block myblk = BlockChainHelper.GetMcBlock(transfer.height);
                    if (transfer.addressIn == "" && transfer.addressOut == "" || transfer.addressIn == null && transfer.addressOut == null)
                    {
                        transfer.addressIn  = "00000000000000000000000000000000";
                        transfer.addressOut = myblk.Address;
                    }
                    if (transfer.timestamp == 0)
                    {
                        transfer.timestamp = myblk.timestamp;
                    }
                }

                if (transfer == null || transfer.timestamp == 0)
                {
                    httpMessage.result = "false";
                }
                else
                {
                    httpMessage.result = JsonHelper.ToJson(transfer);
                }
            }
        }
Example #8
0
        public void GetNearBlock(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "browserIndex", out string browserIndexStr))
            {
                httpMessage.result = "command error! \nexample: GetNearBlock browserIndex";
                return;
            }
            long.TryParse(browserIndexStr, out long browserIndex);

            List <Block> list = new List <Block>();
            // 高度差太大的块直接忽略
            var consensus = Entity.Root.GetComponent <Consensus>();
            var blockMgr  = Entity.Root.GetComponent <BlockMgr>();
            var rule      = Entity.Root.GetComponent <Rule>();
            var showCount = 19;

            var height = browserIndex != 0 ? browserIndex : consensus.transferHeight;

            for (long ii = height; ii > height - showCount && ii > 0; ii--)
            {
                Block myblk = BlockChainHelper.GetMcBlock(ii);
                if (myblk != null)
                {
                    list.Add(myblk);
                }
            }

            if (consensus.transferHeight <= height && rule.state != 0)
            {
                var last = rule.GetLastMcBlock();
                if (last != null)
                {
                    var pre = blockMgr.GetBlock(last.prehash);
                    if (pre.height != consensus.transferHeight)
                    {
                        list.Insert(0, pre);
                        if (list.Count > showCount)
                        {
                            list.RemoveAt(list.Count - 1);
                        }
                    }
                    list.Insert(0, last);
                    if (list.Count > showCount)
                    {
                        list.RemoveAt(list.Count - 1);
                    }
                }
            }

            List <Block> list2 = new List <Block>();

            for (int ii = 0; ii < list.Count; ii++)
            {
                Block blk = list[ii].GetHeader();
                list2.Add(blk);
            }

            httpMessage.result = JsonHelper.ToJson(list2);
        }
Example #9
0
        public Block GetMcBlock(long rewardheight)
        {
            var httpPoolRelay = Entity.Root.GetComponent <HttpPoolRelay>();

            if (httpPoolRelay != null)
            {
                return(httpPoolRelay.GetMcBlock(rewardheight));
            }
            return(BlockChainHelper.GetMcBlock(rewardheight));
        }
Example #10
0
        public static void Q2P_Prehashmkl_Handle(Session session, int opcode, object msg)
        {
            Q2P_Prehashmkl q2p_Prehashmkl = msg as Q2P_Prehashmkl;
            Block          mcbkl          = BlockChainHelper.GetMcBlock(q2p_Prehashmkl.height);
            R2P_Prehashmkl r2p_Prehashmkl = new R2P_Prehashmkl()
            {
                prehashmkl = mcbkl != null ? mcbkl.prehashmkl : ""
            };

            session.Reply(q2p_Prehashmkl, r2p_Prehashmkl);
        }
Example #11
0
        public static void Q2P_McBlock_Handle(Session session, int opcode, object msg)
        {
            Q2P_McBlock q2p_McBlock = msg as Q2P_McBlock;
            Block       mcbkl       = BlockChainHelper.GetMcBlock(q2p_McBlock.height);
            R2P_McBlock r2p_McBlock = null;

            r2p_McBlock = new R2P_McBlock()
            {
                block = mcbkl != null?JsonHelper.ToJson(mcbkl) : ""
            };
            session.Reply(q2p_McBlock, r2p_McBlock);
        }
Example #12
0
        private void OnBlocktranHash(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "hash", out string hash))
            {
                httpMessage.result = "please input hash";
                return;
            }
            using (var dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                var transfer = dbSnapshot.Transfers.Get(hash);
                if (transfer != null)
                {
                    Block myblk = BlockChainHelper.GetMcBlock(transfer.height);
                    if (transfer.addressIn == "" && transfer.addressOut == "" || transfer.addressIn == null && transfer.addressOut == null)
                    {
                        transfer.addressIn  = "00000000000000000000000000000000";
                        transfer.addressOut = "00000000000000000000000000000000";
                    }

                    if (transfer.type == "contract")
                    {
                        string[] arr = transfer.data.Replace("\"", "").Replace("\\", "").Replace("transfer(", "").Replace(")", "").Split(",");
                        transfer.amount = arr[arr.Length - 1];
                        if (transfer.data.Contains("transfer("))
                        {
                            httpMessage.map.Clear();
                            httpMessage.map.Add("address", transfer.addressIn);
                            OnProperty(httpMessage);
                            var res = JsonHelper.FromJson <Dictionary <string, string> >(httpMessage.result);
                            foreach (KeyValuePair <string, string> kv in res)
                            {
                                if (kv.Value.Contains(transfer.addressOut))
                                {
                                    transfer.temp = new List <string>();
                                    transfer.temp.Add(kv.Value.Split(":")[0]);
                                    break;
                                }
                            }
                        }
                    }
                }

                if (transfer == null || transfer.timestamp == 0)
                {
                    httpMessage.result = "false";
                }
                else
                {
                    httpMessage.result = JsonHelper.ToJson(transfer);
                }
            }
        }
Example #13
0
        public void OnGlobal_info(HttpMessage httpMessage)
        {
            long.TryParse(Entity.Root.GetComponent <LevelDBStore>().Get("UndoHeight"), out long UndoHeight);
            var blk = BlockChainHelper.GetMcBlock(UndoHeight);

            Dictionary <string, object> globalInfo = new Dictionary <string, object>();

            globalInfo.Add("success", true);
            globalInfo.Add("message", "successful operation");
            globalInfo.Add("currentBlockHeight", UndoHeight.ToString());
            globalInfo.Add("globalDifficulty", blk.GetDiff().ToString());
            globalInfo.Add("globalHashRate", Entity.Root.GetComponent <Consensus>().calculatePower.GetPower());
            httpMessage.result = JsonHelper.ToJson(globalInfo);
        }
Example #14
0
        private void OnTransactions(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "Index", "index", out string index))
            {
                index = "0";
            }
            int             Index           = int.Parse(index);
            List <BlockSub> transactionList = new List <BlockSub>();

            using (var dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                if (!GetParam(httpMessage, "1", "address", out string address))
                {
                    httpMessage.result = "please input address";
                }
                var account = dbSnapshot.Accounts.Get(address);

                if (account != null)
                {
                    int TFA_Count = dbSnapshot.List.GetCount($"TFA__{address}");
                    Index = TFA_Count - Index * 12;

                    for (int ii = Index; ii > Index - 12 && ii > 0; ii--)
                    {
                        string hasht = dbSnapshot.List.Get($"TFA__{address}", ii - 1);
                        if (hasht != null)
                        {
                            var transfer = dbSnapshot.Transfers.Get(hasht);
                            if (transfer != null)
                            {
                                if (transfer.addressIn == "" && transfer.addressOut == "" || transfer.addressIn == null && transfer.addressOut == null)
                                {
                                    transfer.addressIn  = "00000000000000000000000000000000";
                                    transfer.addressOut = address;
                                }
                                Block myblk = BlockChainHelper.GetMcBlock(transfer.height);
                                if (transfer.timestamp == 0)
                                {
                                    transfer.timestamp = myblk.timestamp;
                                }
                                transactionList.Add(transfer);
                            }
                        }
                    }
                }
                httpMessage.result = JsonHelper.ToJson(transactionList);
            }
        }
Example #15
0
        private void OnBlocktranHash(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "hash", out string hash))
            {
                httpMessage.result = "please input hash";
                return;
            }
            using (var dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                var transfer = dbSnapshot.Transfers.Get(hash);
                if (transfer != null)
                {
                    Block myblk = BlockChainHelper.GetMcBlock(transfer.height);
                    if (transfer.addressIn == "" && transfer.addressOut == "" || transfer.addressIn == null && transfer.addressOut == null)
                    {
                        transfer.addressIn  = "00000000000000000000000000000000";
                        transfer.addressOut = "00000000000000000000000000000000";
                    }

                    if (transfer.type == "contract")
                    {
                        string[] arr = transfer.data.Replace("\"", "").Replace("\\", "").Replace("transfer(", "").Replace(")", "").Split(",");
                        transfer.amount = arr[arr.Length - 1];
                        if (transfer.data.Contains("transfer("))
                        {
                            var symbol = LuaContract.GetSymbol(transfer.addressOut);
                            transfer.temp = new List <string>();
                            transfer.temp.Add(symbol);
                        }
                    }
                }

                if (transfer == null)
                {
                    httpMessage.result = "false";
                }
                else
                {
                    httpMessage.result = JsonHelper.ToJson(transfer);
                }
            }
        }
Example #16
0
        static public bool IsRuleOnline(long height, string address)
        {
            var mcblk = BlockChainHelper.GetMcBlock(height - 1);

            if (mcblk != null)
            {
                var blockMgr = Entity.Root.GetComponent <BlockMgr>();
                for (int i = 0; i < mcblk.linksblk.Count; i++)
                {
                    Block blk = blockMgr.GetBlock(mcblk.linksblk[i]);
                    if (blk != null)
                    {
                        if (blk.Address == address)
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Example #17
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);
                }
            }
        }
Example #18
0
        public bool ApplyHeight(BlockChain blockChain)
        {
            if (blockChain == null)
            {
                return(false);
            }

            // 应用高度不是下一高度
            long.TryParse(levelDBStore.Get("UndoHeight"), out transferHeight);
            if (blockChain.height - 1 != transferHeight)
            {
                return(false);
            }

            Block mcblk = blockChain.GetMcBlock();

            if (mcblk == null)
            {
                return(false);
            }

            Block preblk = BlockChainHelper.GetMcBlock(transferHeight);

            if (mcblk.prehash != preblk.hash)
            {
                return(false);
            }

            LuaVMEnv luaVMEnv = Entity.Root.GetComponent <LuaVMEnv>();

            ruleInfos = luaVMEnv.GetRules(consAddress, transferHeight);

            // --------------------------------------------------
            calculatePower.Insert(mcblk);
            //Log.Debug($"ApplyHeight={blockChain.height}, {calculatePower.GetPower()}, {mcblk.GetDiff()}");

            using (DbSnapshot dbSnapshot = levelDBStore.GetSnapshotUndo(blockChain.height))
            {
                blockChain.Apply(dbSnapshot);
                ApplyReward(dbSnapshot, mcblk);

                if (GetRuleCount(mcblk.height - 1, 2) >= 2 && BlockChainHelper.IsIrreversible(this, mcblk))
                {
                    dbSnapshot.Add("2F1Height", mcblk.height.ToString());
                }

                // 连接块交易
                for (int ii = 0; ii < mcblk.linksblk.Count; ii++)
                {
                    Block linkblk = blockMgr.GetBlock(mcblk.linksblk[ii]);
                    if (linkblk == null)
                    {
                        return(false);
                    }
                    if (linkblk.height != 1)
                    {
                        for (int jj = 0; jj < linkblk.linkstran.Count; jj++)
                        {
                            if (!ApplyTransfer(dbSnapshot, linkblk.linkstran[jj], linkblk.height))
                            {
                                return(false);
                            }
                            if (!ApplyContract(dbSnapshot, linkblk.linkstran[jj], linkblk.height))
                            {
                                return(false);
                            }
                        }
                    }
                }

                dbSnapshot.Commit();
            }

            ruleInfos = luaVMEnv.GetRules(consAddress, mcblk.height, true);
            return(true);
        }
Example #19
0
        // Miner reward, only after confirming that it cannot be rolled back
        public Dictionary <string, BlockSub> MinerReward_PPLNS(string today, long minHeight, long maxHeight)
        {
            Dictionary <string, BlockSub> minerTransfer = new Dictionary <string, BlockSub>();

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

                    //var miners = httpPool.GetMiner(rewardheight);
                    if (miners != null)
                    {
                        string ownerAddress = Wallet.GetWallet().GetCurWallet().ToAddress();

                        var mcblk = BlockChainHelper.GetMcBlock(rewardheight);
                        if (mcblk != null && mcblk.Address == ownerAddress)
                        {
                            BigFloat reward = new BigFloat(Consensus.GetReward(rewardheight));
                            reward = reward * (1.0f - serviceFee);

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

                            // Total power
                            BigFloat diffsum = new BigFloat(0);
                            foreach (var dic in miners.Values)
                            {
                                if (string.IsNullOrEmpty(dic.address))
                                {
                                    continue;
                                }
                                if (dic.diff < 0.99999f)
                                {
                                    continue;
                                }
                                diffsum += new BigFloat(dic.diff);
                            }

                            // Reward for participation
                            foreach (var dic in miners.Values)
                            {
                                if (string.IsNullOrEmpty(dic.address))
                                {
                                    continue;
                                }
                                if (dic.diff < 0.99999f)
                                {
                                    continue;
                                }

                                var    v   = new BigFloat(dic.diff);
                                string pay = BigHelper.Round8((v * reward / diffsum).ToString());

                                if (minerTransfer.TryGetValue(dic.address, out BlockSub transfer))
                                {
                                    transfer.amount = BigHelper.Add(transfer.amount, pay);
                                }
                                else
                                if (BigHelper.Greater(pay, "0.002", false))
                                {
                                    transfer            = new BlockSub();
                                    transfer.addressIn  = ownerAddress;
                                    transfer.addressOut = dic.address;
                                    transfer.amount     = BigHelper.Sub(pay, "0.002"); // 扣除交易手续费
                                    transfer.type       = "transfer";
                                    transfer.data       = CryptoHelper.Sha256($"{today}_{maxHeight}_{ownerAddress}_{dic.address}_MinerReward");
                                    minerTransfer.Add(transfer.addressOut, transfer);
                                }
                            }
                        }
                    }
                }
            }
            return(minerTransfer);
        }
Example #20
0
        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("导出完成");
                }
            }
        }
Example #21
0
 static public Block GetMcBlock(long height)
 {
     return(BlockChainHelper.GetMcBlock(height));
 }