Пример #1
0
        public void Test(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "style", out string style))
            {
                httpMessage.result = "command error! \nexample: test 1 Address C:\\Address.csv";
                return;
            }

            httpMessage.result = "";
            if (style == "1")
            {
                if (!GetParam(httpMessage, "2", "Address", out string Address))
                {
                    httpMessage.result = "command error! \nexample: test 1 Address C:\\Address.csv";
                    return;
                }
                if (!GetParam(httpMessage, "3", "file", out string file))
                {
                    httpMessage.result = "command error! \nexample: test 1 Address C:\\Address.csv";
                    return;
                }

                LevelDBStore.Export2CSV_Transfer($"{file}", Address);
            }
            else
            if (style == "2")
            {
                OneThreadSynchronizationContext.Instance.Post(this.Test2Async, null);
            }
            else
            if (style == "3")
            {
                OneThreadSynchronizationContext.Instance.Post(this.Test3Async, null);
            }
            else
            if (style == "4")
            {
                LevelDBStore.Export2CSV_Accounts($"C:\\Accounts_test4.csv");
            }
            else
            if (style == "5")
            {
                if (!GetParam(httpMessage, "2", "Address", out string Address))
                {
                    httpMessage.result = "command error! \nexample: test 5 Address C:\\Address.csv";
                    return;
                }
                if (!GetParam(httpMessage, "3", "file", out string file))
                {
                    httpMessage.result = "command error! \nexample: test 5 Address C:\\Address.csv";
                    return;
                }
                LevelDBStore.Export2CSV_Account($"{file}", Address);
            }
            else
            if (style == "rule")
            {
                TestBeRule(httpMessage);
            }
        }
Пример #2
0
        public static void test_put(string[] args)
        {
            //
            //DBTests tests = new DBTests();
            //tests.SetUp();
            //tests.Snapshot();
            var          tempPath     = System.IO.Directory.GetCurrentDirectory();
            var          randName     = "LevelDB";
            var          DatabasePath = System.IO.Path.Combine(tempPath, randName);
            LevelDBStore dbstore      = new LevelDBStore().Init(DatabasePath);

            //Êý¾ÝдÈë²âÊÔ
            System.Diagnostics.Stopwatch sp = new System.Diagnostics.Stopwatch();
            sp.Reset();
            sp.Start();
            int mCount = 0;

            while (true)
            {
                dbstore.Put(mCount.ToString(), "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaeraaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
                if (System.Threading.Interlocked.Increment(ref mCount) % 10000 == 0)
                {
                    System.Console.WriteLine($"{mCount} has inserted. time use {sp.ElapsedMilliseconds}ms.");
                }
            }
        }
Пример #3
0
        public async Task <bool> Sync(Block otherMcBlk, string ipEndPoint)
        {
            nodeManager  = nodeManager ?? Entity.Root.GetComponent <NodeManager>();
            blockMgr     = blockMgr ?? Entity.Root.GetComponent <BlockMgr>();
            cons         = cons ?? Entity.Root.GetComponent <Consensus>();
            levelDBStore = levelDBStore ?? Entity.Root.GetComponent <LevelDBStore>();

            if (cons.transferHeight >= otherMcBlk.height)
            {
                return(false);
            }

            // 接收广播过来的主块
            // 检查链是否一致,不一致表示前一高度有数据缺失
            // 获取对方此高度主块linksblk列表,对方非主块的linksblk列表忽略不用拉取
            // 没有的块逐个拉取,校验数据是否正确,添加到数据库
            // 拉取到的块重复此过程
            // UndoTransfers到拉去到的块高度 , 有新块添加需要重新判断主块把漏掉的账本应用
            // GetMcBlock 重新去主块 ,  ApplyTransfers 应用账本
            long syncHeight = otherMcBlk.height;
            long currHeight = (int)(cons.transferHeight / 10) * 10;

            var nodes = nodeManager.GetNode(NodeManager.EnumState.openSyncFast);

            if (nodes.Length != 0)
            {
                long spacing = 10;

                int ii     = 0;
                int random = RandomHelper.Random() % nodes.Length;
                while (GetFunCount <= nodes.Length)
                {
                    long h = currHeight + ii * spacing;
                    if (h > cons.transferHeight + 300)
                    {
                        break;
                    }

                    if (record.IndexOf(h) == -1)
                    {
                        Get(h, spacing, nodes[(ii + random) % nodes.Length].ipEndPoint);
                    }
                    ii++;
                }
            }

            record.RemoveAll(x => x < currHeight);

            return(await cons.SyncHeightNear(otherMcBlk, nodeManager.GetRandomNode(NodeManager.EnumState.openSyncFast), 1f));
        }
Пример #4
0
        public static bool Test(string[] args)
        {
            //
            //DBTests tests = new DBTests();
            //tests.SetUp();
            //tests.Snapshot();
            var          tempPath     = System.IO.Directory.GetCurrentDirectory();
            var          randName     = "LevelDB";
            var          DatabasePath = System.IO.Path.Combine(tempPath, randName);
            LevelDBStore dbstore      = new LevelDBStore().Init(DatabasePath);

            using (DbSnapshot snapshot = dbstore.GetSnapshot(1))
            {
                snapshot.Blocks.Add("11", new Block()
                {
                    Address = "11"
                });
                snapshot.Blocks.Add("22", new Block()
                {
                    Address = "22"
                });
                var value1 = dbstore.Blocks.Get("11");
                var value2 = dbstore.Blocks.Get("22");
                snapshot.Commit();
                var result1 = dbstore.Blocks.Get("11");
                var result2 = dbstore.Blocks.Get("22");
            }

            using (DbSnapshot snapshot = dbstore.GetSnapshot(1))
            {
                snapshot.Blocks.Add("11", new Block()
                {
                    Address = "11"
                });
                snapshot.Blocks.Add("22", new Block()
                {
                    Address = "22"
                });
                var value1 = dbstore.Blocks.Get("11");
                var value2 = dbstore.Blocks.Get("22");
                snapshot.Commit();
                var result1 = dbstore.Blocks.Get("11");
                var result2 = dbstore.Blocks.Get("22");
            }

            return(true);
        }
Пример #5
0
        static public void test_ergodic(string[] args)
        {
            //
            //DBTests tests = new DBTests();
            //tests.SetUp();
            //tests.Snapshot();
            var          tempPath     = System.IO.Directory.GetCurrentDirectory();
            var          randName     = "Data\\LevelDB4";
            var          DatabasePath = System.IO.Path.Combine(tempPath, randName);
            LevelDBStore dbstore      = new LevelDBStore().Init(DatabasePath);

            // Create new iterator
            using (var it = dbstore.db.CreateIterator())
            {
                // Iterate in reverse to print the values as strings
                for (it.SeekToFirst(); it.IsValid(); it.Next())
                {
                    Log.Info($"Value as string: {it.KeyAsString()}");
                }
            }
        }
Пример #6
0
        public static void test_delete(string[] args)
        {
            var          tempPath     = System.IO.Directory.GetCurrentDirectory();
            var          randName     = "LevelDB";
            var          DatabasePath = System.IO.Path.Combine(tempPath, randName);
            LevelDBStore dbstore      = new LevelDBStore().Init(DatabasePath);

            using (DbSnapshot snapshot = dbstore.GetSnapshot(1))
            {
                snapshot.Blocks.Add("11", new Block()
                {
                    Address = "11"
                });
                snapshot.Blocks.Add("22", new Block()
                {
                    Address = "22"
                });
                var value1 = dbstore.Blocks.Get("11");
                var value2 = dbstore.Blocks.Get("22");
                System.Console.WriteLine($"dbstore.test_delete value1: {value1}");
                snapshot.Commit();
                var result1 = dbstore.Blocks.Get("11");
                var result2 = dbstore.Blocks.Get("22");
                System.Console.WriteLine($"dbstore.test_delete value1: {result1}");
            }

            using (DbSnapshot snapshot = dbstore.GetSnapshot(1))
            {
                snapshot.Blocks.Delete("11");
                snapshot.Blocks.Delete("22");
                snapshot.Commit();
                var result1 = dbstore.Blocks.Get("11");
                var result2 = dbstore.Blocks.Get("22");
                System.Console.WriteLine($"dbstore.test_delete value1: {result1}");
            }
        }
Пример #7
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>();

            HttpMessage httpMessage = new HttpMessage();
            string      address     = Wallet.GetWallet().GetCurWallet().ToAddress();

            //string consAddress = "";

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

                if (DateTime.Now.Hour >= 12)
                {
                    var      dayAccount = "account" + DateTime.Now.ToString("yyyyMMdd");
                    FileInfo fi         = new FileInfo("./" + dayAccount + ".csv");
                    bool     exists     = fi.Exists;
                    if (exists == false)
                    {
                        var height = consensus.transferHeight;
                        LevelDBStore.test_ergodic2(height, dayAccount);
                        Console.WriteLine("导出完成");
                    }
                }
            }
        }
Пример #8
0
        private void OutLeveldb(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "passwords", out string password))
            {
                httpMessage.result = "command error! \nexample: wallet password";
                return;
            }

            if (Wallet.GetWallet().IsPassword(password))
            {
                if (!GetParam(httpMessage, "2", "height", out string height))
                {
                    httpMessage.result = "command error! \nexample: outleveldb password height filename";
                    return;
                }
                if (!GetParam(httpMessage, "3", "filename", out string filename))
                {
                    httpMessage.result = "command error! \nexample: outleveldb password height filename";
                    return;
                }
                LevelDBStore.test_ergodic2(long.Parse(height), filename);
                httpMessage.result = "导出完成";
            }
        }
Пример #9
0
        public static void test_undo(string[] args)
        {
            System.Console.WriteLine($"test_undo ...");

            //
            //DBTests tests = new DBTests();
            //tests.SetUp();
            //tests.Snapshot();
            var          tempPath     = System.IO.Directory.GetCurrentDirectory();
            var          randName     = "LevelDB";
            var          DatabasePath = System.IO.Path.Combine(tempPath, randName);
            LevelDBStore dbstore      = new LevelDBStore().Init(DatabasePath);

            for (int rr = 1; rr <= 30; rr++)
            {
                long.TryParse(dbstore.Get("UndoHeight"), out long UndoHeight);
                int random1 = 1000 + RandomHelper.Random() % 1000;

                if (UndoHeight < random1)
                {
                    for (long i = UndoHeight + 1; i <= random1; i++)
                    {
                        using (DbSnapshot snapshot = dbstore.GetSnapshot(i))
                        {
                            snapshot.Transfers.Add("undos_test", new BlockSub()
                            {
                                hash = $"Address_{i}"
                            });
                            snapshot.Commit();
                        }
                    }
                }

                {
                    using (DbSnapshot snapshot = dbstore.GetSnapshot(0))
                    {
                        var result1 = snapshot.Transfers.Get("undos_test");

                        long.TryParse(dbstore.Get("UndoHeight"), out long UndoHeight2);
                        if (result1.hash != $"Address_{UndoHeight2.ToString()}")
                        {
                            System.Console.WriteLine($"dbstore.Undo {random1} error1: {result1.hash}");
                        }
                        //System.Console.WriteLine($"dbstore.Undo {random1} error1: {result1.txid}");
                    }
                }

                if (UndoHeight > random1)
                {
                    dbstore.UndoTransfers(random1);
                }

                using (DbSnapshot snapshot = dbstore.GetSnapshot(0))
                {
                    var result2 = snapshot.Transfers.Get("undos_test");

                    long.TryParse(dbstore.Get("UndoHeight"), out long UndoHeight2);
                    if (result2.hash != $"Address_{UndoHeight2.ToString()}")
                    {
                        System.Console.WriteLine($"dbstore.Undo {random1} error2: {result2.hash}");
                    }
                    //System.Console.WriteLine($"dbstore.Undo {random1} error2: {result2.txid}");
                }
            }
        }
Пример #10
0
        public static void Export2CSV_Block(string[] args)
        {
            var randName = "LevelDB";

            if (args[2] != null)
            {
                randName = args[2];
            }
            var          tempPath     = System.IO.Directory.GetCurrentDirectory();
            var          DatabasePath = System.IO.Path.Combine(tempPath, randName);
            LevelDBStore dbstore      = new LevelDBStore().Init(DatabasePath);

            // file open
            string   fullPath = "C:\\blocks.csv";
            FileInfo fi       = new FileInfo(args[0]);

            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            FileStream   fs   = new FileStream(fullPath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter sw   = new StreamWriter(fs, System.Text.Encoding.UTF8);
            string       data = $"height;hash;diff;prehash;prehashmkl;Address;timestamp;random;sign;linksblk;linkstran";

            sw.WriteLine(data);

            long.TryParse(dbstore.Get("UndoHeight"), out long curHeight);
            for (long ii = 1; ii < curHeight + 10000; ii++)
            {
                List <string> list = dbstore.Heights.Get(ii.ToString());
                if (list != null)
                {
                    foreach (string hash in list)
                    {
                        Block blk = dbstore.Blocks.Get(hash);
                        if (blk != null)
                        {
                            string str_linksblk  = "";
                            string str_linkstran = "";

                            foreach (string value in blk.linksblk.Values)
                            {
                                str_linksblk = $"{str_linksblk}#{value}";
                            }

                            foreach (Transfer value in blk.linkstran.Values)
                            {
                                str_linkstran = $"{str_linkstran}#{value.ToString()}";
                            }

                            string temp = $"{blk.height};{blk.hash};#{blk.GetDiff()};{blk.prehash};{blk.prehashmkl};{blk.Address};{blk.timestamp};{blk.random};{blk.sign};{str_linksblk};{str_linkstran}";
                            sw.WriteLine(temp);
                        }
                    }
                }
                else
                {
                    //break;
                }
            }
            sw.Close();
            fs.Close();
            dbstore.Dispose();
        }
Пример #11
0
        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);
            }
        }
Пример #12
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("导出完成");
                }
            }
        }
Пример #13
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();
        }
Пример #14
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)
            {
                dbstore.UndoTransfers(height);
                using (var it = dbstore.db.CreateIterator())
                {
                    File.Delete("./" + filename + ".csv");
                    var NodeData = new NodeManager.NodeData();
                    File.AppendAllText("./" + filename + ".csv", "height:" + height + "版本:" + NodeData.version + "\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");
                                }
                                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 = StortJson(kv["obj"]["jsonData"].ToStr());

                                Console.WriteLine(it.KeyAsString() + ":" + json);

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