Esempio n. 1
0
        public long GetAccountNotice(string address, bool reset = true)
        {
            long notice = 0;

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                Account account = dbSnapshot.Accounts.Get(address);
                if (!AccountNotice.TryGetValue(address, out notice))
                {
                    if (account != null)
                    {
                        notice = account.notice;
                    }
                }

                // 中间有交易被丢弃了
                if (reset && account != null && account.notice < notice - 20)
                {
                    notice = account.notice;
                }

                notice += 1;

                AccountNotice.Remove(address);
                AccountNotice.Add(address, notice);
            }
            return(notice);
        }
Esempio n. 2
0
        public bool AddBlock(Block blk, bool replace = false)
        {
            if (blk != null && (replace || GetBlock(blk.hash) == null))
            {
                if (!Entity.Root.GetComponent <Consensus>().Check(blk))
                {
                    Log.Warning($"Block Check Error: {blk.ToStringEx()}");
                    return(false);
                }
                using (DbSnapshot snapshot = levelDBStore.GetSnapshot(0, true))
                {
                    List <string> list = snapshot.Heights.Get(blk.height.ToString());
                    if (list == null)
                    {
                        list = new List <string>();
                    }
                    list.Remove(blk.hash);
                    list.Add(blk.hash);

                    snapshot.Heights.Add(blk.height.ToString(), list);
                    snapshot.Blocks.Add(blk.hash, blk);
                    snapshot.Commit();
                }
            }
            return(true);
        }
Esempio n. 3
0
        public void DelBlockWithWeight(Consensus consensus, string prehash, long perheight)
        {
            using (DbSnapshot snapshot = levelDBStore.GetSnapshot())
            {
                List <Block> blks = GetBlock(perheight + 1);
                blks = BlockChainHelper.GetRuleBlk(consensus, blks, prehash);

                List <string> list = snapshot.Heights.Get((perheight + 1).ToString());
                if (list != null)
                {
                    for (int ii = list.Count - 1; ii >= 0; ii--)
                    {
                        if (blks.Find(x => x.hash == list[ii]) == null)
                        {
                            snapshot.Blocks.Delete(list[ii]);
                            cacheDict.Remove(list[ii]);
                            cacheList.Remove(list[ii]);
                            list.RemoveAt(ii);
                        }
                    }
                    snapshot.Heights.Add((perheight + 1).ToString(), list);
                    snapshot.Commit();
                }
            }
        }
Esempio n. 4
0
        private void OnGetNonce(HttpMessage httpMessage)
        {
            string        address = httpMessage.map["address"];
            List <string> addr    = new List <string>();

            addr.Add(address);
            List <string> list = new List <string>();

            list.Add(Base58.Encode(System.Text.Encoding.UTF8.GetBytes("" + JsonHelper.ToJson(addr))));
            httpMessage.map.Clear();
            httpMessage.map.Add("List", list[0]);//JsonHelper.ToJson(list);

            var buffer = Base58.Decode(httpMessage.map["List"]).ToStr();
            var list2  = JsonHelper.FromJson <List <string> >(buffer);

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                Account account = dbSnapshot.Accounts.Get(list2[0]);
                if (account != null)
                {
                    httpMessage.result = $"{{\"success\":true,\"message\":\"successful operation\",\"nonce\":{account.nonce}}}";
                }
                else
                {
                    httpMessage.result = $"{{\"success\":true,\"message\":\"successful operation\",\"nonce\":{0}}}";
                }
            }
        }
Esempio n. 5
0
 // 取某高度mc块
 static public BlockChain GetBlockChain(long height)
 {
     using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
     {
         return(dbSnapshot.BlockChains.Get("" + height));
     }
 }
Esempio n. 6
0
        public void OnAccount(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "Address", out string address))
            {
                httpMessage.result = "command error! \nexample: account address";
                return;
            }
            Dictionary <string, object> result = new Dictionary <string, object>();

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                Account account = dbSnapshot.Accounts.Get(address);

                if (account != null)
                {
                    result.Add("Account", account.address);
                    result.Add("amount", account.amount);
                    result.Add("nonce", account.nonce);
                    httpMessage.result = JsonHelper.ToJson(result);
                }
                else
                {
                    result.Add("Account", address);
                    result.Add("amount", 0);
                    result.Add("nonce", 0);
                    httpMessage.result = JsonHelper.ToJson(result);
                }
                // httpMessage.result = $"          Account: {address}, amount:0 , index:0";
            }
        }
Esempio n. 7
0
        private void OnBalance(HttpMessage httpMessage)
        {
            //Balance balance = new Balance();
            Dictionary <string, object> balance = new Dictionary <string, object>();

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

            if (!GetParam(httpMessage, "Address", "address", out string address))
            {
                httpMessage.result = "please input address.";
                return;
            }

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                Account account = dbSnapshot.Accounts.Get(address);
                if (account != null)
                {
                    result.Add("address", address);
                    result.Add("available", account.amount);
                    balance.Add("result", result);
                    httpMessage.result = JsonHelper.ToJson(balance);
                    return;
                }
                httpMessage.result = "false";
            }
            httpMessage.result = "false";
        }
Esempio n. 8
0
        public bool ApplyGenesis(Block mcblk)
        {
            Log.Debug("ApplyGenesis");

            using (DbSnapshot dbSnapshot = levelDBStore.GetSnapshotUndo(1))
            {
                Block linkblk = mcblk;
                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);
                    }
                }
                new BlockChain()
                {
                    hash = mcblk.hash, height = mcblk.height
                }.Apply(dbSnapshot);

                dbSnapshot.Commit();
            }
            return(true);
        }
Esempio n. 9
0
        public void MinerSave()
        {
            if (httpPool != null)
            {
                Dictionary <string, MinerTask> miners = httpPool.GetMinerRewardMin(out long miningHeight);
                if (miners != null && miningHeight + 3 < httpPool.height)
                {
                    using (DbSnapshot snapshot = PoolDBStore.GetSnapshot(0, true))
                    {
                        string json         = snapshot.Get("Pool_H_Miner");
                        long   height_miner = -1;
                        if (!string.IsNullOrEmpty(json))
                        {
                            long.TryParse(json, out height_miner);
                        }

                        if (height_miner == -1 || height_miner < miningHeight)
                        {
                            snapshot.Add("Pool_H_Miner", miningHeight.ToString());
                            snapshot.Add("Pool_H2_" + miningHeight, JsonHelper.ToJson(miners));
                            snapshot.Commit();
                            httpPool.DelMiner(miningHeight);
                        }
                    }
                }
            }
        }
Esempio n. 10
0
        public bool AddBlock(Block blk)
        {
            if (blk != null && GetBlock(blk.hash) == null)
            {
                if (!Entity.Root.GetComponent <Consensus>().Check(blk))
                {
                    return(false);
                }
                using (DbSnapshot snapshot = levelDBStore.GetSnapshot())
                {
                    List <string> list = snapshot.Heights.Get(blk.height.ToString());
                    if (list == null)
                    {
                        list = new List <string>();
                    }
                    list.Remove(blk.hash);
                    list.Add(blk.hash);
                    snapshot.Heights.Add(blk.height.ToString(), list);

                    snapshot.Blocks.Add(blk.hash, blk);
                    snapshot.Commit();
                }
            }
            return(true);
        }
Esempio n. 11
0
        static Account GetAccount(string url, string address)
        {
            try
            {
                if (httpPoolRelay == null)
                {
                    using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
                    {
                        return(dbSnapshot.Accounts.Get(address));
                    }
                }

                var list = new List <string>();
                list.Add(address);

                HttpMessage quest = new HttpMessage();
                quest.map = new Dictionary <string, string>();
                quest.map.Add("cmd", "getaccounts");
                quest.map.Add("List", Base58.Encode(JsonHelper.ToJson(list).ToByteArray()));

                var result   = ComponentNetworkHttp.QueryStringSync($"http://{url}", quest);
                var accounts = JsonHelper.FromJson <Dictionary <string, Account> >(result);
                accounts.TryGetValue(address, out Account acc);

                return(acc);
            }
            catch (Exception)
            {
            }
            return(null);
        }
Esempio n. 12
0
        public void OnLiquidityOf(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "Address", out string address))
            {
                httpMessage.result = "command error! \nexample: GetLiquidity address factory";
                return;
            }

            if (!GetParam(httpMessage, "2", "Factory", out string factory))
            {
                httpMessage.result = "command error! \nexample: GetLiquidity address factory";
                return;
            }

            if (!GetParam(httpMessage, "3", "Pair", out string pair))
            {
                httpMessage.result = "command error! \nexample: GetLiquidity address factory pair";
                return;
            }

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                var map = new Dictionary <string, string>();

                var abc      = dbSnapshot.ABC.Get(address);
                var blockSub = new BlockSub();
                var index    = 1;
                if (abc != null)
                {
                    var      consensus = Entity.Root.GetComponent <Consensus>();
                    var      luaVMEnv  = Entity.Root.GetComponent <LuaVMEnv>();
                    object[] result    = null;
                    bool     rel;
                    for (int ii = 0; ii < abc.Count; ii++)
                    {
                        blockSub.addressIn  = address;
                        blockSub.addressOut = abc[ii];
                        try
                        {
                            if (!luaVMEnv.IsERC(dbSnapshot, blockSub.addressOut, pair))
                            {
                                continue;
                            }

                            blockSub.data = $"liquidityOf(\"{address}\",\"{factory}\")";
                            rel           = luaVMEnv.Execute(dbSnapshot, blockSub, consensus.transferHeight, out result);
                            if (rel && result != null && result.Length >= 1)
                            {
                                map.Add(index++.ToString(), JsonHelper.ToJson(result));
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                httpMessage.result = JsonHelper.ToJson(map);
            }
        }
Esempio n. 13
0
        public Dictionary <string, RuleInfo> GetRules(string address, long height, bool bCommit = false)
        {
            Dictionary <string, RuleInfo> rules = new Dictionary <string, RuleInfo>();

            try
            {
                LuaEnv       luaenv       = GetLuaEnv(address);
                LuaVMCall    luaVMCall    = new LuaVMCall();
                LuaVMScript  luaVMScript  = null;
                LuaVMContext LuaVMContext = null;

                using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot())
                {
                    s_dbSnapshot = dbSnapshot;
                    LuaVMContext Storages = dbSnapshot?.Storages.Get(address);
                    // rapidjson待优化,改为直接在C#层调用
                    luaenv.DoString(initScript);
                    luaVMScript  = dbSnapshot.Contracts.Get(address);
                    LuaVMContext = dbSnapshot.Storages.Get(address);
                    luaenv.DoString(luaVMScript.script);
                    luaenv.DoString($"Storages = rapidjson.decode('{LuaVMContext.jsonData.ToStr()}')\n");
                    luaVMCall.fnName = "Update";
                    luaVMCall.args   = new FieldParam[0];

                    object[]    args   = luaVMCall.args.Select(a => a.GetValue()).ToArray();
                    LuaFunction luaFun = luaenv.Global.Get <LuaFunction>(luaVMCall.fnName);

                    luaenv.DoString($"curHeight    =  {height}\n");
                    luaFun.Call(args);

                    // 待优化,改为直接在C#层调用
                    luaenv.DoString("StoragesJson = rapidjson.encode(Storages)\n");
                    LuaVMContext.jsonData = luaenv.Global.Get <string>("StoragesJson").ToByteArray();
                    if (bCommit)
                    {
                        dbSnapshot.Storages.Add(address, LuaVMContext);
                        dbSnapshot.Commit();
                    }

                    JToken   jdStorages = JToken.Parse(LuaVMContext.jsonData.ToStr());
                    JToken[] jdRule     = jdStorages["Rules"].ToArray();
                    for (int ii = 0; ii < jdRule.Length; ii++)
                    {
                        RuleInfo rule = new RuleInfo();
                        rule.Address = jdRule[ii]["Address"].ToString();
                        rule.Start   = long.Parse(jdRule[ii]["Start"].ToString());
                        rule.End     = long.Parse(jdRule[ii]["End"].ToString());
                        rules.Remove(rule.Address);
                        rules.Add(rule.Address, rule);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Debug(e.ToString());
                Log.Info("GetRules Error!");
            }
            return(rules);
        }
Esempio n. 14
0
        public void OnProperty(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "Address", out string address))
            {
                httpMessage.result = "command error! \nexample: account address";
                return;
            }

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                var map = new Dictionary <string, string>();

                Account account = dbSnapshot.Accounts.Get(address);
                map.Add("1", "SAT:" + (account != null?account.amount:"0") + ":");

                var abc      = dbSnapshot.ABC.Get(address);
                var blockSub = new BlockSub();
                var index    = 2;
                if (abc != null)
                {
                    var      consensus = Entity.Root.GetComponent <Consensus>();
                    var      luaVMEnv  = Entity.Root.GetComponent <LuaVMEnv>();
                    var      amount    = "";
                    var      symbol    = "";
                    object[] result    = null;
                    bool     rel;
                    for (int ii = 0; ii < abc.Count; ii++)
                    {
                        blockSub.addressIn  = address;
                        blockSub.addressOut = abc[ii];
                        try
                        {
                            if (!luaVMEnv.IsERC(dbSnapshot, blockSub.addressOut, "ERC20"))
                            {
                                continue;
                            }
                            blockSub.data = "symbol()";
                            rel           = luaVMEnv.Execute(dbSnapshot, blockSub, consensus.transferHeight, out result);
                            if (rel && result != null && result.Length >= 1)
                            {
                                symbol = ((string)result[0]) ?? "unknown";
                            }

                            blockSub.data = $"balanceOf(\"{address}\")";
                            rel           = luaVMEnv.Execute(dbSnapshot, blockSub, consensus.transferHeight, out result);
                            if (rel && result != null && result.Length == 1)
                            {
                                amount = ((string)result[0]) ?? "0";
                                map.Add(index++.ToString(), $"{symbol}:{amount}:{blockSub.addressOut}");
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
                httpMessage.result = JsonHelper.ToJson(map);
            }
        }
Esempio n. 15
0
 public void SaveTransferToDB()
 {
     using (DbSnapshot snapshot = Entity.Root.GetComponent <Pool>().PoolDBStore.GetSnapshot())
     {
         snapshot.Add($"TransferProcess", JsonHelper.ToJson(transfers));
         snapshot.Commit();
     }
 }
Esempio n. 16
0
        public Dictionary <string, BlockSub> GetMinerReward_SOLO(long minHeight, long maxHeight)
        {
            Dictionary <string, BlockSub> minerTransfer = new Dictionary <string, BlockSub>();

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

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

                    if (miners != null)
                    {
                        var mcblk = GetMcBlock(rewardheight);
                        if (mcblk != null && mcblk.Address == ownerAddress)
                        {
                            var miner = miners.Values.FirstOrDefault(c => c.random.IndexOf(mcblk.random) != -1);
                            if (miner != null)
                            {
                                BigFloat reward = new BigFloat(Consensus.GetReward(rewardheight));
                                reward = reward * (1.0f - GetServiceFee());

                                var transfer = new BlockSub();
                                transfer.addressIn  = addressIn;
                                transfer.addressOut = miner.address;
                                string pay = BigHelper.Round8(reward.ToString());

                                if (minerTransfer.TryGetValue(miner.address, out transfer))
                                {
                                    transfer.amount = BigHelper.Add(transfer.amount, pay);
                                }
                                else
                                {
                                    transfer            = new BlockSub();
                                    transfer.addressIn  = addressIn;
                                    transfer.addressOut = miner.address;
                                    transfer.amount     = BigHelper.Sub(pay, "0.002"); // 扣除交易手续费
                                    transfer.type       = "100%";                      // 有效提交百分比
                                    transfer.data       = CryptoHelper.Sha256($"{mcblk.hash}_{maxHeight}_{ownerAddress}_{miner.address}_Reward_SOLO");
                                    minerTransfer.Add(transfer.addressOut, transfer);
                                }
                            }
                        }
                    }
                }
            }
            return(minerTransfer);
        }
Esempio n. 17
0
        public Block GetMcBlock(long ___height)
        {
            if (___height <= 1)
            {
                return(null);
            }

            try
            {
                PoolBlock poolBlock = null;
                using (DbSnapshot snapshot = pool.PoolDBStore.GetSnapshot())
                {
                    var str = snapshot.Get($"PoolBlock_{___height}");
                    if (!string.IsNullOrEmpty(str))
                    {
                        poolBlock = JsonHelper.FromJson <PoolBlock>(str);
                        if (poolBlock != null && Wallet.CheckAddress(poolBlock.Address))
                        {
                            return(new Block()
                            {
                                hash = poolBlock.hash, Address = poolBlock.Address, random = poolBlock.random
                            });
                        }
                    }
                }

                HttpMessage quest = new HttpMessage();
                quest.map = new Dictionary <string, string>();
                quest.map.Add("cmd", "GetMcBlock");
                quest.map.Add("version", version);
                quest.map.Add("height", ___height.ToString());
                var result = ComponentNetworkHttp.QueryStringSync($"http://{poolUrl}", quest, 5);
                if (string.IsNullOrEmpty(result))
                {
                    return(null);
                }
                poolBlock = JsonHelper.FromJson <PoolBlock>(result);
                if (poolBlock != null && Wallet.CheckAddress(poolBlock.Address))
                {
                    using (DbSnapshot snapshot = pool.PoolDBStore.GetSnapshot())
                    {
                        snapshot.Add($"PoolBlock_{___height}", JsonHelper.ToJson(poolBlock));
                        snapshot.Commit();
                    }
                    return(new Block()
                    {
                        hash = poolBlock.hash, Address = poolBlock.Address, random = poolBlock.random
                    });
                }
            }
            catch (Exception)
            {
            }
            return(null);
        }
Esempio n. 18
0
 void LoadTransferFromDB()
 {
     using (DbSnapshot snapshot = Entity.Root.GetComponent <Pool>().PoolDBStore.GetSnapshot())
     {
         string str = snapshot.Get($"TransferProcess");
         if (str != null)
         {
             transfers = JsonHelper.FromJson <List <TransferHandle> >(str);
         }
     }
 }
Esempio n. 19
0
        public void ClearOutTimeDB()
        {
            using (DbSnapshot snapshot = PoolDBStore.GetSnapshot(0, true))
            {
                string str_Counted = snapshot.Get("Pool_Counted");
                long   counted     = 0;
                long.TryParse(str_Counted, out counted);
                string        str_MR          = snapshot.Get($"Pool_MR_{counted-1}");
                MinerRewardDB minerRewardLast = null;
                if (!string.IsNullOrEmpty(str_MR))
                {
                    minerRewardLast = JsonHelper.FromJson <MinerRewardDB>(str_MR);
                }
                if (minerRewardLast != null)
                {
                    bool bCommit  = false;
                    int  delCount = 5760 * 3;
                    for (long ii = counted - 2; ii > counted - delCount; ii--)
                    {
                        string key = $"Pool_MR_{ii}";
                        if (!string.IsNullOrEmpty(snapshot.Get(key)))
                        {
                            bCommit = true;
                            snapshot.Delete(key);
                        }
                        else
                        {
                            break;
                        }
                    }

                    // Miner
                    for (long ii = minerRewardLast.minHeight; ii > minerRewardLast.minHeight - delCount; ii--)
                    {
                        string key = $"Pool_H2_{ii}";
                        if (!string.IsNullOrEmpty(snapshot.Get(key)))
                        {
                            bCommit = true;
                            snapshot.Delete(key);
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (bCommit)
                    {
                        snapshot.Commit();
                    }
                }
            }
        }
Esempio n. 20
0
        public void callFun(HttpMessage httpMessage)
        {
            httpMessage.result = "command error! \nexample: contract consAddress callFun";
            GetParam(httpMessage, "1", "consAddress", out string consAddress);
            if (!GetParam(httpMessage, "2", "data", out string data))
            {
                return;
            }
            data = System.Web.HttpUtility.UrlDecode(data);

            WalletKey key    = Wallet.GetWallet().GetCurWallet();
            var       sender = key.ToAddress();

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot())
            {
                var consensus = Entity.Root.GetComponent <Consensus>();
                var luaVMEnv  = Entity.Root.GetComponent <LuaVMEnv>();

                var blockSub = new BlockSub();
                blockSub.addressIn  = sender;
                blockSub.addressOut = consAddress;
                blockSub.data       = data;

                try
                {
                    if (luaVMEnv.IsERC(dbSnapshot, consAddress, ""))
                    {
                        bool rel = luaVMEnv.Execute(dbSnapshot, blockSub, consensus.transferHeight, out object[] result);
                        if (rel)
                        {
                            if (result != null)
                            {
                                if (result.Length == 1)
                                {
                                    httpMessage.result = JsonHelper.ToJson(result[0]);
                                }
                                else
                                {
                                    httpMessage.result = JsonHelper.ToJson(result);
                                }
                            }
                        }
                        else
                        {
                            httpMessage.result = "error";
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }
Esempio n. 21
0
        static public string GetAmount(string address)
        {
            DbSnapshot dbSnapshot = LuaVMEnv.s_dbSnapshot;

            string  amount  = "0";
            Account account = dbSnapshot.Accounts.Get(address);

            if (account != null)
            {
                amount = account.amount;
            }
            return(amount);
        }
Esempio n. 22
0
        public void OnStats(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "style", out string style))
            {
                style = "";
            }

            string  address = Wallet.GetWallet().GetCurWallet().ToAddress();
            Account account = null;

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                account = dbSnapshot.Accounts.Get(address);
            }

            var rule   = Entity.Root.GetComponent <Rule>();
            var pool   = Entity.Root.GetComponent <Pool>();
            var amount = account != null ? account.amount : "0";

            long.TryParse(Entity.Root.GetComponent <LevelDBStore>().Get("UndoHeight"), out long UndoHeight);
            long   PoolHeight = rule.height;
            string power1     = rule.calculatePower.GetPower();
            string power2     = Entity.Root.GetComponent <Consensus>().calculatePower.GetPower();

            int nodeCount = Entity.Root.GetComponent <NodeManager>().GetNodeCount();

            if (style == "")
            {
                httpMessage.result = $"      AlppyHeight: {UndoHeight}\n" +
                                     $"       PoolHeight: {PoolHeight}\n" +
                                     $"  Calculate Power: {power1} of {power2}\n" +
                                     $"          Account: {address}, {amount}\n" +
                                     $"             Node: {nodeCount}\n" +
                                     $"    Rule.Transfer: {rule?.GetTransfersCount()}\n" +
                                     $"    Pool.Transfer: {pool?.GetTransfersCount()}\n" +
                                     $"     NodeSessions: {Program.jdNode["NodeSessions"]}\n" +
                                     $"           IsRule: {Entity.Root.GetComponent<Consensus>().IsRule(PoolHeight, address)}";
            }
            else
            if (style == "1")
            {
                httpMessage.result = $"H:{UndoHeight} P:{power2}";
            }
            else
            if (style == "2")
            {
                var httpPool = Entity.Root.GetComponent <HttpPool>();
                var miners   = httpPool?.GetMinerReward(out long miningHeight);
                httpMessage.result = $"H:{UndoHeight} P:{power2} Miner:{miners?.Count} P1:{power1}";
            }
        }
Esempio n. 23
0
        public bool IsERC(DbSnapshot dbSnapshot, string consAddress, string scriptName)
        {
            var luaVMScript = LuaVMScript.Get(dbSnapshot, consAddress);

            if (luaVMScript != null)
            {
                if (string.IsNullOrEmpty(scriptName))
                {
                    return(true);
                }
                return(luaVMScript.tablName == scriptName);
            }
            return(false);
        }
Esempio n. 24
0
        public void OnTransfer(HttpMessage httpMessage)
        {
            BlockSub transfer = new BlockSub();

            transfer.hash       = httpMessage.map["hash"];
            transfer.type       = httpMessage.map["type"];
            transfer.nonce      = long.Parse(httpMessage.map["nonce"]);
            transfer.addressIn  = httpMessage.map["addressIn"];
            transfer.addressOut = httpMessage.map["addressOut"];
            transfer.amount     = httpMessage.map["amount"];
            transfer.data       = System.Web.HttpUtility.UrlDecode(httpMessage.map["data"]);
            transfer.timestamp  = long.Parse(httpMessage.map["timestamp"]);
            transfer.sign       = httpMessage.map["sign"].HexToBytes();
            if (httpMessage.map.ContainsKey("depend"))
            {
                transfer.depend = System.Web.HttpUtility.UrlDecode(httpMessage.map["depend"]);
            }
            if (httpMessage.map.ContainsKey("remarks"))
            {
                transfer.remarks = System.Web.HttpUtility.UrlDecode(httpMessage.map["remarks"]);
            }
            if (httpMessage.map.ContainsKey("extend"))
            {
                transfer.extend = JsonHelper.FromJson <List <string> >(System.Web.HttpUtility.UrlDecode(httpMessage.map["extend"]));
            }

            //string hash = transfer.ToHash();
            //string sign = transfer.ToSign(Wallet.GetWallet().GetCurWallet()).ToHexString();
            //Log.Info($"{sign} {hash}");

            var rel = Entity.Root.GetComponent <Rule>().AddTransfer(transfer);

            if (rel == -1)
            {
                OnTransferAsync(transfer);
            }

            if (rel == -1 || rel == 1)
            {
                using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
                {
                    long index = dbSnapshot.List.GetCount($"TFA__{transfer.addressIn}{""}");
                    httpMessage.result = "{\"success\":true,\"accindex\":" + index + "} ";
                }
            }
            else
            {
                httpMessage.result = "{\"success\":false,\"rel\":" + rel + "}";
            }
        }
Esempio n. 25
0
        static public LuaVMScript Get(DbSnapshot dbSnapshot, string consAddress)
        {
            var luaVMScript = dbSnapshot.Contracts.Get(consAddress);

            if (luaVMScript == null)
            {
                throw new Exception($"Smart Contract not exist: {consAddress}");
            }
            if (!string.IsNullOrEmpty(luaVMScript.tablName))
            {
                luaVMScript.script = FileHelper.GetFileData($"./Data/Contract/{luaVMScript.tablName}.lua").ToByteArray();
            }

            return(luaVMScript);
        }
Esempio n. 26
0
        public LuaVMDB(DbSnapshot _dbSnapshot)
        {
            dbSnapshot = _dbSnapshot;

            Snap        = new LuaVMDBCache <string>(dbSnapshot.Snap);
            Blocks      = new LuaVMDBCache <Block>(dbSnapshot.Blocks);
            Heights     = new LuaVMDBCache <List <string> >(dbSnapshot.Heights);
            Transfers   = new LuaVMDBCache <BlockSub>(dbSnapshot.Transfers);
            Accounts    = new LuaVMDBCache <Account>(dbSnapshot.Accounts);
            Contracts   = new LuaVMDBCache <LuaVMScript>(dbSnapshot.Contracts);
            Storages    = new LuaVMDBCache <LuaVMContext>(dbSnapshot.Storages);
            BlockChains = new LuaVMDBCache <BlockChain>(dbSnapshot.BlockChains);
            StoragesMap = new LuaVMDBCache <string>(dbSnapshot.StoragesMap);
            ABC         = new LuaVMDBCache <List <string> >(dbSnapshot.ABC);
            List        = new LuaVMDBList <string>(dbSnapshot.List);
        }
Esempio n. 27
0
        public bool ApplyContract(DbSnapshot dbSnapshot, Transfer transfer, long height)
        {
            if (transfer.type != "contract")
            {
                return(true);
            }
            if (transfer.addressIn == transfer.addressOut)
            {
                return(true);
            }
            if (transfer.data == null || transfer.data == "")
            {
                return(true);
            }
            //if (!transfer.CheckSign())
            //    return true;

            luaVMEnv.Execute(dbSnapshot, transfer, height);

            // 设置交易index
            Account accountIn = dbSnapshot.Accounts.Get(transfer.addressIn);

            if (accountIn == null)
            {
                accountIn = new Account()
                {
                    address = transfer.addressIn, amount = "0", index = 0, nonce = 0
                }
            }
            ;
            if (accountIn.nonce + 1 != transfer.nonce)
            {
                return(true);
            }
            accountIn.index += 1;
            accountIn.nonce += 1;
            dbSnapshot.Accounts.Add(accountIn.address, accountIn);

            if (transferShow)
            {
                dbSnapshot.BindTransfer2Account(transfer.addressIn, accountIn.index, transfer.hash);
                transfer.height = height;
                dbSnapshot.Transfers.Add(transfer.hash, transfer);
            }

            return(true);
        }
Esempio n. 28
0
        public void balanceOf(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "Address", out string address))
            {
                httpMessage.result = "command error! \nexample: account address";
                return;
            }
            GetParam(httpMessage, "2", "token", out string token);

            var map = new Dictionary <string, string>();

            using (DbSnapshot dbSnapshot = Entity.Root.GetComponent <LevelDBStore>().GetSnapshot(0))
            {
                Account account = dbSnapshot.Accounts.Get(address);
                map.Add("nonce", account == null?"0":account.nonce.ToString());

                if (string.IsNullOrEmpty(token))
                {
                    map.Add("amount", account == null?"0":account.amount);
                }
                else
                {
                    var      consensus = Entity.Root.GetComponent <Consensus>();
                    var      luaVMEnv  = Entity.Root.GetComponent <LuaVMEnv>();
                    var      amount    = "";
                    object[] result    = null;
                    bool     rel;
                    var      blockSub = new BlockSub();
                    blockSub.addressIn  = address;
                    blockSub.addressOut = token;
                    try
                    {
                        blockSub.data = $"balanceOf(\"{address}\")";
                        rel           = luaVMEnv.Execute(dbSnapshot, blockSub, consensus.transferHeight, out result);
                        if (rel && result != null && result.Length >= 1)
                        {
                            amount = ((string)result[0]) ?? "0";
                            map.Add("amount", amount);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            httpMessage.result = JsonHelper.ToJson(map);
        }
Esempio n. 29
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);
        }
Esempio n. 30
0
 public void DelBlock(long height)
 {
     using (DbSnapshot snapshot = levelDBStore.GetSnapshot(0, true))
     {
         List <string> list = snapshot.Heights.Get(height.ToString());
         if (list != null)
         {
             for (int ii = 0; ii < list.Count; ii++)
             {
                 snapshot.Blocks.Delete(list[ii]);
                 blockCache.Remove(list[ii]);
             }
             snapshot.Heights.Delete(height.ToString());
         }
         snapshot.Commit();
     }
 }