Example #1
0
        public void CompareBlockInfo2()
        {
            string url1 = "http://192.168.197.34:8000";
            string url2 = "http://192.168.197.29:8000";

            //Get Block Height
            string method    = "get_block_height";
            string parameter = "{}";
            string code      = string.Empty;

            var    request  = new RpcRequestManager(url1);
            string response = request.PostRequest(method, parameter, out code);
            var    result   = JObject.Parse(response);

            Assert.AreEqual("OK", code);
            Console.WriteLine(result["result"]["result"]);
            int height = Int32.Parse(result["result"]["result"]["block_height"].ToString());

            for (int i = 0; i < height; i++)
            {
                method    = "get_block_info";
                parameter = "{\"block_height\":\"" + i + "\"}";
                string code1    = string.Empty;
                string code2    = string.Empty;
                var    request1 = new RpcRequestManager(url1);
                var    request2 = new RpcRequestManager(url2);

                string response1 = request.PostRequest(method, parameter, out code1);
                string response2 = request.PostRequest(method, parameter, out code2);
                Assert.AreEqual("OK", code1);
                Assert.AreEqual("OK", code2);
                Assert.AreEqual(response1, response2);
            }
        }
        public void RpcBroadcastWithRawTx(CommandInfo ci)
        {
            var rawtx = new JObject
            {
                ["rawtx"] = ci.Parameter
            };
            var    req        = RpcRequestManager.CreateRequest(rawtx, "broadcast_tx", 1);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }

            JObject rObj = JObject.Parse(resp);
            var     rj   = rObj["result"];
            string  hash = rj["hash"] == null ? rj["error"].ToString() :rj["hash"].ToString();
            string  res  = rj["hash"] == null ? "error" : "txId";
            var     jobj = new JObject
            {
                [res] = hash
            };

            ci.InfoMsg.Add(jobj.ToString());

            ci.Result = true;
        }
        public void RpcConnectChain(CommandInfo ci)
        {
            var    req        = RpcRequestManager.CreateRequest(new JObject(), "connect_chain", 1);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }

            JObject jObj = JObject.Parse(resp);

            var j = jObj["result"];

            if (j["error"] != null)
            {
                ci.ErrorMsg.Add(j["error"].ToString());
                return;
            }

            if (j["result"]["BasicContractZero"] != null)
            {
                _genesisAddress = j["result"]["BasicContractZero"].ToString();
            }
            string message = JObject.FromObject(j["result"]).ToString();

            ci.InfoMsg.Add(message);
            ci.Result = true;
        }
Example #4
0
        public void TestRedisKeyInfo()
        {
            var rh   = new RedisHelper("192.168.197.13");
            var list = rh.GetAllKeys();

            Console.WriteLine("Total key counts: {0}", list.Count);

            TypeSummarySet tss   = new TypeSummarySet();
            int            count = 0;

            foreach (var item in list)
            {
                if (item == "ping")
                {
                    continue;
                }
                count++;
                var    byteArray = rh.GetT <byte[]>(item);
                string hexValue  = BitConverter.ToString(byteArray, 0).Replace("-", string.Empty).ToLower();

                var inputByteArray = new byte[hexValue.Length / 2];
                for (var x = 0; x < inputByteArray.Length; x++)
                {
                    var i = Convert.ToInt32(hexValue.Substring(x * 2, 2), 16);
                    inputByteArray[x] = (byte)i;
                }

                //Rpc Call
                string url       = "http://192.168.197.13:8000";
                string method    = "get_deserialized_info";
                string parameter = "{\"key\":\"" + item + "\",\"value\":\"" + hexValue + "\"}";
                string code      = string.Empty;

                try
                {
                    var    request  = new RpcRequestManager(url);
                    string response = request.PostRequest(method, parameter, out code);
                    Console.WriteLine($"Key {count} : {item}");
                    Console.WriteLine(response);
                    var    result = JObject.Parse(response);
                    string type   = result["result"]["TypeName"].ToString();
                    string value  = result["result"]["Value"].ToString();

                    var data = new DataResult(item, type, value);
                    tss.AddDataResult(data);
                    tss.AddTypeSummary(data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Analyze {0} key got exception: {1}", item, ex.Message);
                }
            }

            foreach (var item in tss.SummaryInfo)
            {
                Console.WriteLine($"{item.TypeName} : {item.Count}");
            }
            Assert.IsTrue(true);
        }
Example #5
0
        public CliHelper(string rpcUrl)
        {
            _keyStore           = new AElfKeyStore(ApplicationHelpers.GetDefaultDataDir());
            _accountManager     = new AccountManager(_keyStore);
            _transactionManager = new TransactionManager(_keyStore);
            _requestManager     = new RpcRequestManager(rpcUrl);
            _loadedModules      = new Dictionary <string, Module>();

            CommandList = new List <CommandInfo>();
        }
        public CliHelper(string rpcUrl, string keyPath = "")
        {
            _rpcAddress         = rpcUrl;
            _keyStore           = new AElfKeyStore(keyPath == ""? ApplicationHelper.GetDefaultDataDir() : keyPath);
            _accountManager     = new AccountManager(_keyStore);
            _transactionManager = new TransactionManager(_keyStore);
            _requestManager     = new RpcRequestManager(rpcUrl);
            _loadedModules      = new Dictionary <string, Module>();

            CommandList = new List <CommandInfo>();
        }
Example #7
0
        public void Invoke <T>(Func <Expression <Action <T> > > func, ResponseCallback responseCallback)
        {
            var methodTuple = RpcRequestManager.CreateMethodTuple(func);
            var methodId    = methodTuple.RpcMethod.GetId();

            if (!Connections.TryGetValue(methodId, out var peer))
            {
                Logger.Warn($"服务器端没有注册{methodId}方法!");
                return;
            }

            Ssci.Invoke(func, peer, responseCallback);
        }
Example #8
0
        public void GetBlockHeight()
        {
            string url       = "http://192.168.197.34:8000";
            string method    = "get_block_height";
            string parameter = "{}";
            string code      = string.Empty;

            var    request  = new RpcRequestManager(url);
            string response = request.PostRequest(method, parameter, out code);

            Console.WriteLine(response);
            Assert.AreEqual("OK", code);
            Assert.IsTrue(response.Contains("block_height"));
        }
        public void RpcGetBlockHeight(CommandInfo ci)
        {
            var    req        = RpcRequestManager.CreateRequest(new JObject(), ci.Category, 0);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }
            ci.InfoMsg.Add(resp);
            ci.Result = true;
        }
        public void RpcGetContractAbi(CommandInfo ci)
        {
            if (ci.Parameter == "")
            {
                if (_genesisAddress == null)
                {
                    ci.ErrorMsg.Add("Please connect_chain first.");
                    return;
                }
                ci.Parameter = _genesisAddress;
            }

            var req = RpcRequestManager.CreateRequest(new JObject
            {
                ["address"] = ci.Parameter
            }, ci.Category, 1);

            Module m = null;

            if (!_loadedModules.TryGetValue(ci.Parameter, out m))
            {
                string returnCode = string.Empty;
                long   timeSpan   = 0;
                string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);
                ci.TimeSpan = timeSpan;
                if (!CheckResponse(ci, returnCode, resp))
                {
                    return;
                }

                JObject jObj = JObject.Parse(resp);
                var     res  = JObject.FromObject(jObj["result"]);

                JToken ss = res["abi"];
                byte[] aa = ByteArrayHelpers.FromHexString(ss.ToString());

                MemoryStream ms = new MemoryStream(aa);
                m = Serializer.Deserialize <Module>(ms);
                _loadedModules.Add(ci.Parameter, m);
                ci.InfoMsg.Add(resp);
            }

            var obj = JObject.FromObject(m);

            ci.InfoMsg.Add(obj.ToString());
            ci.Result = true;
        }
        public void RpcGetCommands(CommandInfo ci)
        {
            var    req        = RpcRequestManager.CreateRequest(new JObject(), ci.Category, 0);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }

            JObject jObj = JObject.Parse(resp);
            var     j    = jObj["result"];

            ci.InfoMsg.Add(j["result"]["commands"].ToString());
            ci.Result = true;
        }
Example #12
0
        private static void Invoke<T>(Func<Expression<T>> func, IPeer peer, ResponseCallback responseCallback) {
            
            var methodTuple = RpcRequestManager.Get(func);
            var method = func?.Invoke().Body as MethodCallExpression;
            var array = new object[method.Arguments.Count];

            for (var i = 0; i < array.Length; i++) {
                var arg = method.Arguments;
                if (arg[i] is ConstantExpression v1) {
                    array[i] = v1.Value;
                }

                if (arg[i] is MemberExpression v2) {
                    var container = ((ConstantExpression)v2.Expression).Value;
                    var propertyInfo = v2.Member as FieldInfo;
                    array[i] = propertyInfo.GetValue(container);
                }
            }

            methodTuple.Action.Invoke(methodTuple.RpcMethod.GetId(), peer, responseCallback, array);
        }
Example #13
0
        public void GetInTimeBlockInfo(string rpcUrl)
        {
            int value = 0;

            for (int i = 1; i > 0; i++)
            {
                string method    = "get_block_height";
                string parameter = "{}";
                string code      = string.Empty;

                var    request  = new RpcRequestManager(rpcUrl);
                string response = request.PostRequest(method, parameter, out code);
                Console.WriteLine(response);
                Assert.AreEqual("OK", code);
                var    result   = JObject.Parse(response);
                string countStr = result["result"]["result"]["block_height"].ToString();
                if (value == Int32.Parse(countStr))
                {
                    continue;
                }

                value = Int32.Parse(countStr);
                string count = (Int32.Parse(countStr) - 1).ToString();
                method = "get_block_info";

                parameter = "{\"block_height\":\"" + count + "\"}";
                code      = string.Empty;

                request  = new RpcRequestManager(rpcUrl);
                response = request.PostRequest(method, parameter, out code);
                Console.WriteLine(response);
                Assert.AreEqual("OK", code);
                result = JObject.Parse(response);
                string txcount    = result["result"]["result"]["Body"]["TransactionsCount"].ToString();
                string txPoolSize = result["result"]["result"]["CurrentTransactionPoolSize"].ToString();
                System.Diagnostics.Debug.WriteLine("Height: {0},  TxCount: {1}, TxPoolSize: {2}, Time: {3}", count, txcount, txPoolSize, DateTime.Now.ToString());
                Thread.Sleep(1000);
            }
        }
Example #14
0
        public void ExecuteOneRpcTask()
        {
            string rpcMsg  = string.Empty;
            var    request = new RpcRequestManager(RpcUrl);

            while (true)
            {
                if (!ContractRpcList.TryDequeue(out rpcMsg))
                {
                    break;
                }
                Logger.WriteInfo("Contracts execution left: {0}", ContractRpcList.Count);
                var ci = new CommandInfo("broadcast_tx");
                ci.Parameter = rpcMsg;
                CH.ExecuteCommand(ci);
                if (!ci.Result)
                {
                    ContractRpcList.Enqueue(rpcMsg);
                }
                Thread.Sleep(20);
            }
        }
        public void RpcGetMerklePath(CommandInfo ci)
        {
            if (!ci.CheckParameterValid(1))
            {
                return;
            }

            var req = RpcRequestManager.CreateRequest(new JObject
            {
                ["txid"] = ci.Parameter
            }, ci.Category, 1);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }
            ci.InfoMsg.Add(resp);
            ci.Result = true;
        }
        public void RpcBroadcastTxs(CommandInfo ci)
        {
            var paramObject = new JObject
            {
                ["rawtxs"] = ci.Parameter
            };
            var    req        = RpcRequestManager.CreateRequest(paramObject, ci.Category, 0);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }

            JObject jObj = JObject.Parse(resp);
            var     j    = jObj["result"];

            ci.InfoMsg.Add(j["result"].ToString());
            ci.Result = true;
        }
        public void RpcSetBlockVolume(CommandInfo ci)
        {
            if (!ci.CheckParameterValid(2))
            {
                return;
            }

            var req = RpcRequestManager.CreateRequest(new JObject
            {
                ["minimal"] = ci.Parameter.Split(" ")?[0],
                ["maximal"] = ci.Parameter.Split(" ")?[1]
            }, ci.Category, 1);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }
            ci.InfoMsg.Add(resp);
            ci.Result = true;
        }
Example #18
0
        public void TestMultiNodesDbData()
        {
            var rh1 = new RedisHelper("192.168.197.34");
            var rh2 = new RedisHelper("192.168.197.13");
            var rh3 = new RedisHelper("192.168.197.29");

            var list1 = rh1.GetAllKeys();
            var list2 = rh2.GetAllKeys();
            var list3 = rh2.GetAllKeys();

            Console.WriteLine("Node1 total keys: {0}", list1.Count);
            Console.WriteLine("Node2 total keys :{0}", list2.Count);
            Console.WriteLine("Node3 total keys :{0}", list3.Count);

            var same12 = RedisHelper.GetIntersection(list1, list2);
            var same13 = RedisHelper.GetIntersection(list1, list3);
            var same23 = RedisHelper.GetIntersection(list2, list3);

            var same123 = RedisHelper.GetIntersection(same12, same13);

            Console.WriteLine("Node12 same keys count: {0}", same12.Count);
            Console.WriteLine("Node13 same keys count: {0}", same13.Count);
            Console.WriteLine("Node23 same keys count: {0}", same23.Count);

            var diff12 = RedisHelper.GetExceptList(list1, list2);
            var diff21 = RedisHelper.GetExceptList(list2, list1);

            Console.WriteLine("Diff12 info(length): {0}", diff12.Count);
            foreach (var item in diff12)
            {
                Console.WriteLine("Diff12: {0}", item);
            }

            Console.WriteLine("Diff21 info(length): {0}", diff21.Count);
            foreach (var item in diff21)
            {
                Console.WriteLine("Diff21: {0}", item);
            }

            var diff13 = RedisHelper.GetExceptList(list1, list3);
            var diff31 = RedisHelper.GetExceptList(list3, list1);

            Console.WriteLine("Diff13 info(length): {0}", diff13.Count);
            foreach (var item in diff13)
            {
                Console.WriteLine("Diff13: {0}", item);
            }

            Console.WriteLine("Diff31 info(length): {0}", diff31.Count);
            foreach (var item in diff31)
            {
                Console.WriteLine("Diff31: {0}", item);
            }

            var diff23 = RedisHelper.GetExceptList(list2, list3);
            var diff32 = RedisHelper.GetExceptList(list3, list2);

            Console.WriteLine("Diff23 info(length): {0}", diff23.Count);
            foreach (var item in diff23)
            {
                Console.WriteLine("Diff23: {0}", item);
            }

            Console.WriteLine("Diff23 info(length): {0}", diff32.Count);
            foreach (var item in diff32)
            {
                Console.WriteLine("Diff32: {0}", item);
            }

            TypeSummarySet tss1 = new TypeSummarySet();
            TypeSummarySet tss2 = new TypeSummarySet();
            TypeSummarySet tss3 = new TypeSummarySet();

            Console.WriteLine("Compare same key with diff data scenario:");
            foreach (var item in same123)
            {
                if (item == "ping")
                {
                    continue;
                }

                //Redis Value
                var    byteArray1 = rh1.GetT <byte[]>(item);
                string hexValue1  = BitConverter.ToString(byteArray1, 0).Replace("-", string.Empty).ToLower();

                var    byteArray2 = rh2.GetT <byte[]>(item);
                string hexValue2  = BitConverter.ToString(byteArray2, 0).Replace("-", string.Empty).ToLower();

                var    byteArray3 = rh3.GetT <byte[]>(item);
                string hexValue3  = BitConverter.ToString(byteArray3, 0).Replace("-", string.Empty).ToLower();

                //Rpc Call
                string method = "get_deserialized_info";
                string url1   = "http://192.168.197.34:8000";
                string url2   = "http://192.168.197.13:8000";
                string url3   = "http://192.168.197.29:8000";

                if (hexValue1 != hexValue2)
                {
                    Console.WriteLine("Vaule1 Value2 diff: {0}", item);

                    string parameter1 = "{\"key\":\"" + item + "\",\"value\":\"" + hexValue1 + "\"}";
                    string code1      = string.Empty;

                    var    request1  = new RpcRequestManager(url1);
                    string response1 = request1.PostRequest(method, parameter1, out code1);
                    Console.WriteLine("Db1 rpc data:\r\n" + response1);
                    var    result1 = JObject.Parse(response1);
                    string type1   = result1["result"]["TypeName"].ToString();
                    string value1  = result1["result"]["Value"].ToString();

                    var data1 = new DataResult(item, type1, value1);
                    tss1.AddDataResult(data1);
                    tss1.AddTypeSummary(data1);

                    string parameter2 = "{\"key\":\"" + item + "\",\"value\":\"" + hexValue2 + "\"}";
                    string code2      = string.Empty;

                    var    request2  = new RpcRequestManager(url2);
                    string response2 = request2.PostRequest(method, parameter2, out code2);
                    Console.WriteLine("Db2 rpc data:\r\n" + response2);
                    var    result2 = JObject.Parse(response2);
                    string type2   = result2["result"]["TypeName"].ToString();
                    string value2  = result2["result"]["Value"].ToString();

                    var data2 = new DataResult(item, type2, value2);
                    tss2.AddDataResult(data2);
                    tss2.AddTypeSummary(data2);
                }

                if (hexValue1 != hexValue3)
                {
                    Console.WriteLine("Vaule1 Value3 diff: {0}", item);
                    string parameter3 = "{\"key\":\"" + item + "\",\"value\":\"" + hexValue3 + "\"}";
                    string code3      = string.Empty;

                    var    request3  = new RpcRequestManager(url3);
                    string response3 = request3.PostRequest(method, parameter3, out code3);
                    Console.WriteLine("Db3 rpc data:\r\n" + response3);
                    var    result3 = JObject.Parse(response3);
                    string type3   = result3["result"]["TypeName"].ToString();
                    string value3  = result3["result"]["Value"].ToString();

                    var data3 = new DataResult(item, type3, value3);
                    tss3.AddDataResult(data3);
                    tss3.AddTypeSummary(data3);
                }
                Assert.IsTrue(true);
            }
        }
        public void RpcDeployContract(CommandInfo ci)
        {
            if (!ci.CheckParameterValid(3))
            {
                return;
            }
            string filename = ci.Parameter.Split(" ")[0];
            // Read sc bytes
            SmartContractReader screader = new SmartContractReader();

            byte[] sc  = screader.Read(filename);
            string hex = sc.ToHex();

            if (!_loadedModules.TryGetValue(_genesisAddress, out var m))
            {
                ci.ErrorMsg.Add("ABI not loaded.");
                return;
            }

            Method meth = m.Methods.FirstOrDefault(mt => mt.Name.Equals("DeploySmartContract"));

            if (meth == null)
            {
                ci.ErrorMsg.Add("Method not Found.");
                return;
            }
            byte[] serializedParams = meth.SerializeParams(new List <string> {
                "1", hex
            });
            _transactionManager.SetCmdInfo(ci);
            Transaction tx = _transactionManager.CreateTransaction(ci.Parameter.Split(" ")[2], _genesisAddress,
                                                                   ci.Parameter.Split(" ")[1],
                                                                   "DeploySmartContract", serializedParams, TransactionType.ContractTransaction);

            tx = tx.AddBlockReference(_rpcAddress);
            if (tx == null)
            {
                return;
            }
            tx = _transactionManager.SignTransaction(tx);
            if (tx == null)
            {
                return;
            }
            var    rawtx      = _transactionManager.ConvertTransactionRawTx(tx);
            var    req        = RpcRequestManager.CreateRequest(rawtx, "broadcast_tx", 1);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }

            JObject jObj = JObject.Parse(resp);
            var     j    = jObj["result"];

            if (j["error"] != null)
            {
                ci.ErrorMsg.Add(j["error"].ToString());
                ci.Result = false;
                return;
            }
            string hash = j["hash"] == null ? j["error"].ToString() :j["hash"].ToString();
            string res  = j["hash"] == null ? "error" : "txId";
            var    jobj = new JObject
            {
                [res] = hash
            };

            ci.InfoMsg.Add(jobj.ToString());

            ci.Result = true;
        }
        public void RpcBroadcastTx(CommandInfo ci)
        {
            if (!ci.Parameter.Contains("{"))
            {
                RpcBroadcastWithRawTx(ci);
                return;
            }
            JObject     j  = JObject.Parse(ci.Parameter);
            Transaction tr = _transactionManager.ConvertFromJson(j);

            if (tr == null)
            {
                return;
            }
            string hex = tr.To.Value.ToHex();
            Module m   = null;

            if (!_loadedModules.TryGetValue(hex.Replace("0x", ""), out m))
            {
                if (!_loadedModules.TryGetValue("0x" + hex.Replace("0x", ""), out m))
                {
                    ci.ErrorMsg.Add("Abi Not Loaded.");
                    return;
                }
            }

            Method method = m.Methods?.FirstOrDefault(mt => mt.Name.Equals(tr.MethodName));

            if (method == null)
            {
                ci.ErrorMsg.Add("Method not found.");
                return;
            }

            JArray p = j["params"] == null ? null : JArray.Parse(j["params"].ToString());

            tr.Params = j["params"] == null ? null : method.SerializeParams(p.ToObject <string[]>());
            tr.type   = TransactionType.ContractTransaction;
            tr        = tr.AddBlockReference(_rpcAddress);

            _transactionManager.SignTransaction(tr);
            var    rawtx      = _transactionManager.ConvertTransactionRawTx(tr);
            var    req        = RpcRequestManager.CreateRequest(rawtx, ci.Category, 1);
            string returnCode = string.Empty;
            long   timeSpan   = 0;
            string resp       = _requestManager.PostRequest(req.ToString(), out returnCode, out timeSpan);

            ci.TimeSpan = timeSpan;
            if (!CheckResponse(ci, returnCode, resp))
            {
                return;
            }

            JObject rObj = JObject.Parse(resp);
            var     rj   = rObj["result"];
            string  hash = rj["hash"] == null ? rj["error"].ToString() :rj["hash"].ToString();
            string  res  = rj["hash"] == null ? "error" : "txId";
            var     jobj = new JObject
            {
                [res] = hash
            };

            ci.InfoMsg.Add(jobj.ToString());

            ci.Result = true;
        }