Exemple #1
0
        void P2P_NewBlock_Handle(Session session, int opcode, object msg)
        {
            P2P_NewBlock p2p_Block = msg as P2P_NewBlock;
            Block        blk       = JsonHelper.FromJson <Block>(p2p_Block.block);

            if (!NodeManager.CheckNetworkID(p2p_Block.networkID))
            {
                Log.Warning($"NewBlk:{blk.Address} H:{blk.height} ipEndPoint:{p2p_Block.ipEndPoint} RemoteAddress:{session.RemoteAddress}");
                return;
            }

            //Log.Debug($"NewBlock IP:{session.RemoteAddress.ToString()} {blk.Address} hash:{blk.hash} ");
            Log.Debug($"NewBlk:{blk.Address} H:{blk.height} Pre:{blk.prehash} T:{blk.linkstran.Count}");

            newBlockHeight = blk.height;
            // 有高度差的直接忽略
            long.TryParse(levelDBStore.Get("UndoHeight"), out long transferHeight);
            if (transferHeight - 1 < blk.height)
            {
                AddBlock(blk);
            }

            //// 如果收到的是桶外的数据 , 向K桶内进行一次广播
            //if (nodeManager.IsNeedBroadcast2Kad(p2p_Block.ipEndPoint))
            //{
            //    p2p_Block.ipEndPoint = Entity.Root.GetComponent<ComponentNetworkInner>().ipEndPoint.ToString();
            //    nodeManager.Broadcast2Kad(p2p_Block);
            //}
        }
Exemple #2
0
        void P2P_NewBlock_Handle(Session session, int opcode, object msg)
        {
            P2P_NewBlock p2p_Block = msg as P2P_NewBlock;
            Block        blk       = JsonHelper.FromJson <Block>(p2p_Block.block);

            Log.Debug($"NewBlock IP:{session.RemoteAddress.ToString()} hash:{blk.hash} ");

            // 有高度差的直接忽略
            long.TryParse(levelDBStore.Get("UndoHeight"), out long transferHeight);
            if (transferHeight - 1 < blk.height)
            {
                AddBlock(blk);
            }

            // 如果收到的是桶外的数据 , 向K桶内进行一次广播
            if (nodeManager.IsNeedBroadcast2Kad(session.RemoteAddress))
            {
                nodeManager.Broadcast2Kad(p2p_Block);
            }
        }
Exemple #3
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}");
                }
            }
        }
Exemple #4
0
        public override void Awake(JToken jd = null)
        {
            try
            {
                transferShow = jd["transferShow"] != null;
                Log.Info($"Consensus.transferShow = {transferShow}");

                if (jd["Run"] != null)
                {
                    bool.TryParse(jd["Run"].ToString(), out bRun);
                }

                if (jd["height"] != null)
                {
                    long height = long.Parse(jd["height"].ToString());
                    long.TryParse(levelDBStore.Get("UndoHeight"), out long height_total);
                    while (height_total > height)
                    {
                        height_total = Math.Max(height_total - 100, height);
                        levelDBStore.UndoTransfers(height_total);
                        Log.Debug($"UndoTransfers height = {height_total}");
                    }
                }

                string aa = BigInt.Div("1000,1000", "1000");
            }
            catch (Exception)
            {
            }
        }
Exemple #5
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();
        }
Exemple #6
0
        public async void Run()
        {
            //Entity.Root.GetComponent<LevelDBStore>().Undo(100);
            await Task.Delay(3000);

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

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

            Wallet       wallet       = Wallet.GetWallet();
            P2P_NewBlock p2p_NewBlock = new P2P_NewBlock()
            {
                networkID = NodeManager.networkIDBase
            };
            Block    blk        = null;
            Block    preblk     = null;
            TimePass timePass   = new TimePass(1);
            bool     bBlkMining = true;

            if (httpRule == null)
            {
                broadcasttime = pooltime * 5 / 15; // 不挖矿就提前广播块
            }
            state = 0xff;
            while (true)
            {
                try
                {
                    if (state < 0xff)
                    {
                        await Task.Delay(1000);
                    }

                    long time = (nodeManager.GetNodeTime() / 1000) % pooltime;
                    if (blk == null && time < broadcasttime && timePass.IsPassSet())
                    {
                        preblk = GetLastMcBlock();
                        if (consensus.IsRule(preblk.height + 1, wallet.GetCurWallet().ToAddress()))
                        {
                            blk = CreateBlock(preblk, ref bBlkMining);
                            if (blk != null && bBlkMining)
                            {
                                diff_max   = 0;
                                hashmining = blk.ToHashMining();
                                httpRule?.SetMinging(blk.height, hashmining, consensus.calculatePower.GetPower());
                            }
                        }
                        else
                        {
                            long.TryParse(levelDBStore.Get("UndoHeight"), out height);
                            await Task.Delay(1000);
                        }
                    }

                    if (blk != null && httpRule == null)
                    {
                        // 挖矿
                        if (httpRule == null && bBlkMining)
                        {
                            Mining(blk, hashmining);
                        }
                    }

                    // 广播块
                    if (blk != null && time >= broadcasttime)
                    {
                        if (bBlkMining)
                        {
                            if (httpRule != null)
                            {
                                Dictionary <string, MinerTask> miners = httpRule.GetMiner(blk.height);
                                if (miners != null)
                                {
                                    double diff  = miners.Values.Max(t => t.diff);
                                    var    miner = miners.Values.FirstOrDefault(c => c.diff == diff);
                                    if (miner != null && miner.random != null && miner.random.Count > 0)
                                    {
                                        blk.random = miner.random[miner.random.Count - 1];
                                    }
                                    httpRule.SetMinging(blk.height, "", consensus.calculatePower.GetPower());
                                }
                            }
                            height   = blk.height;
                            blk.hash = blk.ToHash();
                            blk.sign = blk.ToSign(Wallet.GetWallet().GetCurWallet());
                            blockMgr.AddBlock(blk);
                        }

                        p2p_NewBlock.block      = JsonHelper.ToJson(blk);
                        p2p_NewBlock.ipEndPoint = networkInner.ipEndPoint.ToString();
                        nodeManager.Broadcast(p2p_NewBlock, blk);
                        relayNetwork?.Broadcast(p2p_NewBlock);

                        Log.Debug($"Rule.Broadcast H:{blk.height} Mining:{bBlkMining} hash:{blk.hash} T:{blk.linkstran.Count}");

                        calculatePower.Insert(blk);
                        hashmining = "";
                        diff_max   = 0;
                        blk        = null;
                    }

                    await Task.Delay(10);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }
        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);
            }
        }
Exemple #8
0
        public async void Run()
        {
            //Entity.Root.GetComponent<LevelDBStore>().Undo(100);
            await Task.Delay(3000);

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

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

            Wallet       wallet       = Wallet.GetWallet();
            P2P_NewBlock p2p_NewBlock = new P2P_NewBlock();
            Block        blk          = null;
            Block        preblk       = null;
            TimePass     timePass     = new TimePass(1);
            var          httpRule     = Entity.Root.GetComponent <HttpPool>();

            state = 0xff;
            while (true)
            {
                try
                {
                    if (state < 0xff)
                    {
                        await Task.Delay(1000);
                    }

                    long time = (nodeManager.GetNodeTime() / 1000) % pooltime;
                    if (blk == null && time < broadcasttime && timePass.IsPassSet())
                    {
                        // 找到最新的Mc块
                        preblk = GetLastMcBlock();
                        // 是否在裁决节点列表中
                        if (consensus.IsRule(preblk.height + 1, wallet.GetCurWallet().ToAddress()))
                        {
                            // 生成主块
                            blk        = CreateBlock(preblk);
                            diff_max   = 0;
                            hashmining = blk.ToHashMining();
                            httpRule?.SetMinging(blk.height, hashmining, consensus.calculatePower.GetPower());
                        }
                        else
                        {
                            long.TryParse(levelDBStore.Get("UndoHeight"), out height);
                            await Task.Delay(1000);
                        }
                    }

                    if (blk != null && httpRule == null)
                    {
                        // 挖矿 这里是提交算力 by sxh
                        Mining(blk, hashmining);
                    }

                    // 广播块
                    if (blk != null && time >= broadcasttime)
                    {
                        if (httpRule != null)
                        {
                            Dictionary <string, MinerTask> miners = httpRule.GetMiner(blk.height);
                            if (miners != null)
                            {
                                double diff  = miners.Values.Max(t => t.diff);
                                var    miner = miners.Values.First(c => c.diff == diff);
                                blk.random = miner.random;
                                httpRule?.SetMinging(blk.height, "", consensus.calculatePower.GetPower());
                            }
                        }

                        height   = blk.height;
                        blk.hash = blk.ToHash();
                        blk.sign = blk.ToSign(Wallet.GetWallet().GetCurWallet());
                        blockMgr.AddBlock(blk);
                        p2p_NewBlock.block      = JsonHelper.ToJson(blk);
                        p2p_NewBlock.ipEndPoint = networkInner.ipEndPoint.ToString();
                        nodeManager.Broadcast(p2p_NewBlock);
                        diff_max = 0;

                        Log.Debug($"Rule.Broadcast {blk.height} {blk.hash}");
                        calculatePower.Insert(blk);
                        blk        = null;
                        hashmining = "";
                    }

                    await Task.Delay(10);
                }
                catch (Exception)
                {
                    await Task.Delay(1000);
                }
            }
        }