Exemple #1
0
    //市场合约余额测试
    void test_getAuctionSgas()
    {
        MyJson.JsonNode_Object paparms = new MyJson.JsonNode_Object();
        var array = new MyJson.JsonNode_Array();

        array.AddArrayValue("(addr)AYTcTTB8jpWtGgs8ukoUrQPm1zmEFxZHNk");
        paparms["sbParamJson"]  = array;
        paparms["sbPushString"] = new MyJson.JsonNode_ValueString("balanceOf");
        paparms["nnc"]          = new MyJson.JsonNode_ValueString("0x7753e79cfb98e63e2b7aa00a819e0cb86fdb1930");

        NeoGameSDK_CS.invokescrept((bool timeout, WWW www) => {
            var json = MyJson.Parse(www.text);
            if (!json.AsDict().ContainsKey("result"))
            {
                Debug.Log("无余额");
            }
            else
            {
                var resultv = json.AsDict()["result"].AsList()[0].AsDict()["stack"].AsList()[0].AsDict();
                var rtype   = resultv["type"].AsString();
                var rvalue  = resultv["value"].AsString();
                if (rvalue != "")
                {
                    var n = new BigMath.Numerics.BigInteger(ThinNeo.Helper.HexString2Bytes(rvalue));
                    Debug.Log("余额:" + decimal.Parse((float.Parse(n.ToString()) / 100000000).ToString()));
                }
                else
                {
                    Debug.Log("无余额");
                }
            }
        }, paparms);
    }
Exemple #2
0
 public static void LoadRecord()
 {
     try
     {
         TxHistory.Clear();
         UtxoHistory.Clear();
         var str    = System.IO.File.ReadAllText("records.json", System.Text.Encoding.UTF8);
         var record = MyJson.Parse(str).AsDict();
         foreach (var item in record["trans"].AsList())
         {
             var newitem = new TranInfo();
             TxHistory.Add(newitem);
             newitem.txid = item.AsDict()["txid"].AsString();
             newitem.type = (ThinNeo.TransactionType)Enum.Parse(typeof(ThinNeo.TransactionType), item.AsDict()["type"].AsString());
             newitem.time = DateTime.FromFileTimeUtc(long.Parse(item.AsDict()["time"].AsString().Substring(4)));
         }
         foreach (var item in record["uxtos"].AsList())
         {
             UtxoHistory.Add(item.AsString());
         }
     }
     catch
     {
     }
 }
Exemple #3
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            utxos.Clear();
            comboUtxo.Items.Clear();
            System.Net.WebClient wc = new System.Net.WebClient();
            listUTXO.Items.Clear();
            Dictionary <string, decimal> count = new Dictionary <string, decimal>();

            var str    = MakeRpcUrl(this.texturl.Text, "getutxo", new MyJson.JsonNode_ValueString(textaddress.Text));
            var result = await wc.DownloadStringTaskAsync(str);

            var json1 = MyJson.Parse(result).AsDict();

            if (json1.ContainsKey("error"))
            {
                return;
            }
            var json = json1["result"].AsList();

            foreach (var item in json)
            {
                UTXO txio = new UTXO();
                //var use = item.GetDictItem("vinTx").AsString();
                var hextxid = item.GetDictItem("txid").AsString();
                txio.txid = ThinNeo.Helper.HexString2Bytes(hextxid).Reverse().ToArray();

                txio.n = item.GetDictItem("n").AsInt();

                var hexasset = item.GetDictItem("asset").AsString();
                txio.asset = ThinNeo.Helper.HexString2Bytes(hexasset).Reverse().ToArray();
                var coolasset = ThinNeo.Helper.Bytes2HexString(txio.asset);
                var value     = decimal.Parse(item.GetDictItem("value").AsString());
                txio.value = value;
                //if (use == "")
                {
                    if (count.ContainsKey(coolasset) == false)
                    {
                        count[coolasset] = 0;
                    }
                    count[coolasset] += value;

                    listUTXO.Items.Add(txio.txid + "[" + txio.n + "] " + value + ":" + ThinNeo.Helper.Bytes2HexString(txio.asset));
                    comboUtxo.Items.Add(txio);
                }
                utxos.Add(txio);
                //else
                //{
                //    listUTXO.Items.Add("[已花费]" + value + ":" + asset);
                //}
            }
            listMoney.Items.Clear();
            foreach (var m in count)
            {
                listMoney.Items.Add("资产:" + m.Value + "  " + m.Key);
            }
            if (comboUtxo.Items.Count > 0)
            {
                comboUtxo.SelectedIndex = 0;
            }
        }
Exemple #4
0
        private void Button_Click_8(object sender, RoutedEventArgs e)
        {
            listTestScript.Items.Clear();

            try
            {
                var symbol    = ThinNeo.Helper.Bytes2HexString(lastScript);
                var str       = WWW.MakeRpcUrl(labelRPC.Text, "invokescript", new MyJson.JsonNode_ValueString(symbol));
                var resultstr = WWW.GetWithDialog(this, str);
                var json      = MyJson.Parse(resultstr).AsDict();
                var gas       = json["result"].AsDict()["gas_consumed"].ToString();
                lastFee       = decimal.Parse(gas);
                labelFee.Text = "Fee:" + lastFee;
                StringBuilder sb = new StringBuilder();
                json["result"].AsDict().ConvertToStringWithFormat(sb, 4);
                var lines = sb.ToString().Split('\n');
                foreach (var l in lines)
                {
                    listTestScript.Items.Add(l);
                }
            }
            catch (Exception err)
            {
                listTestScript.Items.Add("error:" + err.Message);
            }
        }
Exemple #5
0
        public static MyJson.JsonNode_Array GetData(string mongodbConnStr, string mongodbDatabase, string coll, string findFliter)
        {
            var client     = new MongoClient(mongodbConnStr);
            var database   = client.GetDatabase(mongodbDatabase);
            var collection = database.GetCollection <BsonDocument>(coll);

            List <BsonDocument> query = collection.Find(BsonDocument.Parse(findFliter)).ToList();

            client = null;

            if (query.Count > 0)
            {
                var jsonWriterSettings = new JsonWriterSettings {
                    OutputMode = JsonOutputMode.Strict
                };
                MyJson.JsonNode_Array JA = MyJson.Parse(query.ToJson(jsonWriterSettings)) as MyJson.JsonNode_Array;
                foreach (MyJson.JsonNode_Object j in JA)
                {
                    j.Remove("_id");
                }
                return(JA);
            }
            else
            {
                return(new MyJson.JsonNode_Array());
            }
        }
Exemple #6
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string rootPath = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location);
            string pathLog  = System.IO.Path.Combine(rootPath, "tempLog");

            if (System.IO.Directory.Exists(pathLog) == false)
            {
                System.IO.Directory.CreateDirectory(pathLog);
            }
            var transid = this.textTid.Text;

            byte[] info = ThinNeo.Helper.HexString2Bytes(transid.ToLower());
            transid = "0x" + ThinNeo.Helper.Bytes2HexString(info);
            if (transid != "0x00")
            {//download and write debugfile
                var filename = System.IO.Path.Combine(pathLog, transid + ".llvmhex.txt");
                var url      = textAPITran.Text + "?jsonrpc=2.0&id=1&method=getfulllog&params=[%22" + transid + "%22]";
                var rtnstr   = wc.DownloadString(url);
                var json     = MyJson.Parse(rtnstr).AsDict();
                if (json.ContainsKey("result") == false)
                {
                    MessageBox.Show("找不到此交易的智能合约log。Can not find fullloginfo for this transaction.");
                    return;
                }
                var txt = json["result"].AsList()[0].AsDict()["fulllog7z"].AsString();
                System.IO.File.WriteAllText(filename, txt);
            }
            LoadTxLog(transid);
        }
Exemple #7
0
        //更新固件
        public async void InstallFramework()
        {
            await Dispatcher.InvokeAsync(async() =>
            {
                ForbidAllBtnClick();

                //安装按钮隐藏  等待按钮显示
                gif_Framework_loading.Visibility = Visibility.Visible;
                Btn_Framework_update.Visibility  = Visibility.Hidden;

                var pluginType = this.label_FrameworkVersion.Content.ToString().Split(' ')[0];
                var version    = servicePackageInfo[pluginType].ToString();
                var language   = Mgr_Language.Ins.curEnumLanguage.ToString();

                byte[] postdata;
                //从服务器获取固件和插件的版本信息
                var url        = HttpHelper.MakeRpcUrlPost("https://apiaggr.nel.group/api/testnet", "downloadplugin", out postdata, new MyJson.JsonNode_ValueString(pluginType + "_" + version + "_" + language));
                var res        = await HttpHelper.HttpPost(url, postdata);
                var str_plugin = MyJson.Parse(res).AsDict()["result"].AsList()[0].AsDict()["plugin"].ToString();
                byte[] data    = ThinNeo.Helper.HexString2Bytes(str_plugin);


                EnumInstallType type   = EnumInstallType.Framework;
                EnumPluginType content = EnumPluginType.Unknow;

                Result result = await ManagerControl.Ins.ToDo(EnumControl.InstallFramework, data, type, content, version);
                gif_Framework_loading.Visibility = Visibility.Hidden;
                Btn_Framework_update.Visibility  = Visibility.Visible;

                AllowAllBtnClick();
            });
        }
Exemple #8
0
        private async Task test_getRefundTarget()
        {
            subPrintLine("Input txid:");
            string txid = Console.ReadLine();

            byte[] script = null;
            using (var sb = new ThinNeo.ScriptBuilder())
            {
                var array = new MyJson.JsonNode_Array();
                array.AddArrayValue("(hex256)" + txid);
                sb.EmitParamJson(array);                                                   //参数倒序入
                sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)getRefundTarget")); //参数倒序入
                var shash = Config.dapp_sgas;
                sb.EmitAppCall(shash);                                                     //nep5脚本
                script = sb.ToArray();
            }

            var    urlCheckUTXO    = Helper.MakeRpcUrl(Config.api, "invokescript", new MyJson.JsonNode_ValueString(ThinNeo.Helper.Bytes2HexString(script)));
            string resultCheckUTXO = await Helper.HttpGet(urlCheckUTXO);

            var jsonCU = MyJson.Parse(resultCheckUTXO);
            var stack  = jsonCU.AsDict()["result"].AsList()[0].AsDict()["stack"].AsList()[0].AsDict();
            var value  = ThinNeo.Helper.HexString2Bytes(stack["value"].ToString());

            subPrintLine("addr:" + ThinNeo.Helper.GetAddressFromScriptHash(value));
        }
Exemple #9
0
 public static MyJson.JsonNode_Object downloadScript(string api, string savepath, string scripthash)
 {
     System.Net.WebClient wc = new MyWebClient();
     try
     {
         var str  = wc.DownloadString(api + "?rpccall=2.0&id=1&method=getcontractscript&params=[\"" + scripthash + "\"]");
         var json = MyJson.Parse(str).AsDict()["result"].AsList()[0].AsDict();
         if (json.ContainsKey("cs"))
         {
             var srcResult = json["cs"].AsString();
             srcResult = Uri.UnescapeDataString(srcResult);
             var outfile = System.IO.Path.Combine(savepath, scripthash + ".cs");
             System.IO.File.WriteAllText(outfile, srcResult);
         }
         if (json.ContainsKey("avm"))
         {
             var avmResult = json["avm"].AsString();
             var bts       = ThinNeo.Helper.HexString2Bytes(avmResult);
             var outfile   = System.IO.Path.Combine(savepath, scripthash + ".avm");
             System.IO.File.WriteAllBytes(outfile, bts);
         }
         if (json.ContainsKey("map"))
         {
             var mapResult = json["map"].ToString();
             var outfile   = System.IO.Path.Combine(savepath, scripthash + ".map.json");
             System.IO.File.WriteAllText(outfile, mapResult);
         }
         return(json);
     }
     catch (Exception err)
     {
         return(null);
     }
 }
Exemple #10
0
        public void LoadJson(string jsonstr)
        {
            this.Title = "";
            this.funcs = null;

            MyJson.JsonNode_Object json = MyJson.Parse(jsonstr).AsDict();
            if (json.ContainsKey("title"))
            {
                this.Title = json["title"].AsString();
            }
            var funcs = json["funcs"].AsList();

            this.funcs = new DApp_Func[funcs.Count];
            for (var i = 0; i < funcs.Count; i++)
            {
                this.funcs[i] = new DApp_Func();

                this.funcs[i].Load(funcs[i].AsDict());
            }
            if (json.ContainsKey("consts"))
            {
                foreach (var citem in json["consts"].AsDict())
                {
                    this.consts[citem.Key] = citem.Value.ToString();
                }
            }
        }
        public static async Task <Result> api_InvokeScript(Hash160 scripthash, string methodname, params string[] subparam)
        {
            byte[] data = null;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
                for (var i = 0; i < subparam.Length; i++)
                {
                    array.AddArrayValue(subparam[i]);
                }
                sb.EmitParamJson(array);
                sb.EmitPushString(methodname);
                sb.EmitAppCall(scripthash);
                data = sb.ToArray();
            }
            string script = ThinNeo.Helper.Bytes2HexString(data);

            byte[] postdata;
            var    url  = Helper.MakeRpcUrlPost(api, "invokescript", out postdata, new MyJson.JsonNode_ValueString(script));
            var    text = await Helper.HttpPost(url, postdata);

            MyJson.JsonNode_Object json = MyJson.Parse(text) as MyJson.JsonNode_Object;

            Result rest = new Result();

            rest.textInfo = text;
            if (json.ContainsKey("result"))
            {
                var result = json["result"].AsList()[0].AsDict()["stack"].AsList();
                rest.value = ResultItem.FromJson("Array", result);
            }
            return(rest);// subPrintLine("得到的结果是:" + result);
        }
    /// <summary>
    /// 解析服务端返回数据
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    private bool ParseJson(string s)
    {
        try
        {
            var json = MyJson.Parse(s);
            srdata.http_code                 = json.asDict()["http_code"].AsString();
            srdata.name                      = json.asDict()["data"].asDict()["name"].AsString();
            srdata.version_latest            = json.asDict()["data"].asDict()["version_latest"].AsString();
            srdata.ver_res_latest            = json.asDict()["data"].asDict()["ver_res_latest"].AsString();
            srdata.server_resource_online    = json.asDict()["data"].asDict()["server_resource_online"].AsString();
            srdata.server_resource_online_ip = json.asDict()["data"].asDict()["server_resource_online_ip"].AsString();
            srdata.server_resource_local_ip  = json.asDict()["data"].asDict()["server_resource_local_ip"].AsString();

            foreach (var _j in json.asDict()["data"].asDict()["resource"].AsList())
            {
                ResData res = new ResData();
                res.version_res_current = _j.asDict()["version_res_current"].AsString();
                res.version_res_next    = _j.asDict()["version_res_next"].AsString();
                res.path_resource       = _j.asDict()["path_resource"].AsString();
                res.force_update        = _j.asDict()["force_update"].AsString();
                res.status = _j.asDict()["status"].AsString();

                srdata.resource.Add(res);
            }
            return(true);
        }
        catch
        {
            return(false);
        }
    }
Exemple #13
0
        //async public static Task<MyJson.JsonNode_Object> callcontractfortest(string url,string method)
        //{
        //    var gstr = MakeRpcUrlPost("getfullloginfo", txid);
        //    try
        //    {
        //        var str = await postData(url, gstr);
        //        var json = MyJson.Parse(str);
        //        var result = json.AsDict().GetDictItem("result") as MyJson.JsonNode_Object;
        //        return result;
        //    }
        //    catch (Exception err)
        //    {
        //        var errorMsg = "failed to call contract for test.Info:" + err.ToString();
        //        Console.WriteLine(errorMsg);
        //        Log.WriteLog(errorMsg);
        //        return null;
        //    }
        //}
        async public static Task <MyJson.JsonNode_Object> invokescript(string url, string scripthash, string method)
        {
            var sb = new ThinNeo.ScriptBuilder();

            ThinNeo.Hash160 shash = new ThinNeo.Hash160(scripthash);
            sb.EmitParamJson(new MyJson.JsonNode_Array());
            sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)" + method)); //调用的方法
            sb.EmitAppCall(shash);                                               //nep5脚本

            var data   = sb.ToArray();
            var script = ThinNeo.Helper.Bytes2HexString(data);

            var urldata = MakeRpcUrlPost("invokescript", script);

            try
            {
                var str = await postData(url, urldata);

                var json = MyJson.Parse(str);
                if (json.AsDict().ContainsKey("error"))
                {
                    return(json.AsDict()["error"] as MyJson.JsonNode_Object);
                }
                var result = json.AsDict().GetDictItem("result") as MyJson.JsonNode_Object;
                return(result);
            }
            catch (Exception err)
            {
                var errorMsg = "failed to invokescript method:" + method + ".Info:" + err.ToString();
                Console.WriteLine(errorMsg);
                return(null);
            }
        }
Exemple #14
0
        static async void invokescript(string avmPath, string rpcurl)
        {
            //从文件中读取合约脚本
            byte[] script = System.IO.File.ReadAllBytes(avmPath); //这里填你的合约所在地址

            byte[] parameter__list = new byte[0];
            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                //倒叙插入数据
                //sb.EmitParamJson(new MyJson.JsonNode_Array());
                sb.EmitParamJson(new MyJson.JsonNode_Array());
                sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)totalSupply"));
                var nnc           = ThinNeo.Helper.GetScriptHashFromScript(script);
                var scriptaddress = new ThinNeo.Hash160(nnc);
                sb.EmitAppCall(scriptaddress);
                //sb.EmitPushBytes(script);
                //ThinNeo.Hash160 shash = new ThinNeo.Hash160(scripthash.Replace("0x", ""));
                //sb.EmitAppCall(script);//nep5脚本

                string scriptPublish = ThinNeo.Helper.Bytes2HexString(sb.ToArray());
                //用ivokescript试运行并得到消耗

                byte[] postdata;
                var    url    = Helper.MakeRpcUrlPost(rpcurl, "invokescript", out postdata, new MyJson.JsonNode_ValueString(scriptPublish));
                var    result = await Helper.HttpPost(url, postdata);

                Console.WriteLine("得到的结果是:" + result);
                var json = MyJson.Parse(result).AsDict()["result"].AsDict();
                printByteArray(json);
            }
        }
Exemple #15
0
        public JObject callContractForTestMulti(string neoCliJsonRPCUrl, List <string> scripthashs, JArray paramsJA)
        {
            JObject res       = new JObject();
            JArray  stackList = new JArray();
            int     n         = 0;

            foreach (var scripthash in scripthashs)
            {
                ThinNeo.ScriptBuilder tmpSb = new ThinNeo.ScriptBuilder();
                httpHelper            hh    = new httpHelper();
                var json = MyJson.Parse(JsonConvert.SerializeObject(paramsJA[n])).AsList();
                var list = json.AsList();
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    tmpSb.EmitParamJson(list[i]);
                }

                var scripthashReverse = ThinNeo.Helper.HexString2Bytes(scripthash).Reverse().ToArray();
                tmpSb.EmitAppCall(scripthashReverse);
                string  invokeSc = ThinNeo.Helper.Bytes2HexString(tmpSb.ToArray());
                JObject invokeRs = invokeScript(neoCliJsonRPCUrl, invokeSc);

                /**
                 * JObject 不能存放相同字段,为将其与其他接口调用区分开来,现单端改名为-Multi结尾的方法
                 */
                /*
                 * res.Add("script", invokeRs["script"]);
                 * res.Add("state", invokeRs["state"]);
                 * res.Add("gas_consumed", invokeRs["gas_consumed"]);
                 */

                JObject stack1 = null;
                if (invokeRs == null)
                {
                    stack1 = new JObject();
                    stack1.Add("type", "FAULT");
                    stack1.Add("value", "");
                    stackList.Add(stack1);
                    continue;
                }
                string state = invokeRs["state"].ToString();
                JArray stack = (JArray)invokeRs["stack"];
                if (state.StartsWith("FAULT"))
                {
                    // 调用合约出错,填充占位
                    stack1 = new JObject();
                    stack1.Add("type", "FAULT");
                    stack1.Add("value", "");
                }
                else
                {
                    stack1 = (JObject)stack[0];
                }
                stack1["hash"] = scripthash;
                stackList.Add(stack1);
            }

            res.Add("stack", stackList);
            return(res);
        }
        public async Task InvokeNep5Async(string chainHash, string WIF, string ContractHash)
        {
            UInt160 scriptHash = ZoroHelper.Parse(ContractHash);

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitAppCall(scriptHash, "name");
                sb.EmitAppCall(scriptHash, "totalSupply");
                sb.EmitAppCall(scriptHash, "symbol");
                sb.EmitAppCall(scriptHash, "decimals");

                var result = await ZoroHelper.InvokeScript(sb.ToArray(), chainHash);

                //Console.WriteLine(result);

                MyJson.JsonNode_Object json_result_array = MyJson.Parse(result) as MyJson.JsonNode_Object;
                MyJson.JsonNode_Object json_result_obj   = json_result_array["result"] as MyJson.JsonNode_Object;
                MyJson.JsonNode_Array  stack             = json_result_obj["stack"].AsList();

                if (stack.Count == 4)
                {
                    Console.WriteLine("name:" + Helper.GetJsonString(stack[0] as MyJson.JsonNode_Object));
                    Console.WriteLine("totalSupply:" + Helper.GetJsonBigInteger(stack[1] as MyJson.JsonNode_Object));
                    Console.WriteLine("symbol:" + Helper.GetJsonString(stack[2] as MyJson.JsonNode_Object));
                    Console.WriteLine("decimals:" + Helper.GetJsonInteger(stack[3] as MyJson.JsonNode_Object));
                }
            }
        }
Exemple #17
0
 void downloadScript(string api, string savepath, string scripthash)
 {
     try
     {
         var str  = wc.DownloadString(api + "get?hash=" + scripthash);
         var json = MyJson.Parse(str).AsDict();
         if (json.ContainsKey("cs"))
         {
             var srcResult = json["cs"].AsString();
             srcResult = Uri.UnescapeDataString(srcResult);
             var outfile = System.IO.Path.Combine(savepath, scripthash + ".cs");
             System.IO.File.WriteAllText(outfile, srcResult);
         }
         if (json.ContainsKey("avm"))
         {
             var avmResult = json["avm"].AsString();
             var bts       = ThinNeo.Helper.HexString2Bytes(avmResult);
             var outfile   = System.IO.Path.Combine(savepath, scripthash + ".avm");
             System.IO.File.WriteAllBytes(outfile, bts);
         }
         if (json.ContainsKey("map"))
         {
             var mapResult = json["map"].AsString();
             mapResult = Uri.UnescapeDataString(mapResult);
             var outfile = System.IO.Path.Combine(savepath, scripthash + ".debug.json");
             System.IO.File.WriteAllText(outfile, mapResult);
         }
     }
     catch (Exception err)
     {
     }
 }
        public void Load(string _pathlog, string _pathscript, string transid)
        {
            this.pathScript = _pathscript;
            if (transid.ToLower().IndexOf("0x") == 0)
            {
                transid = transid.Substring(2);
            }
            byte[] info     = HexString2Bytes(transid);
            var    filename = "0x" + ToHexString(info);

            var tranfile = System.IO.Path.Combine(_pathlog, filename + ".fulllog.7z");


            if (System.IO.File.Exists(tranfile) == false)
            {
                throw new Exception("你的数据源里没有log信息,他可能还没有同步,或者这不是一个智能合约交易");
            }
            using (var ms = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(tranfile)))
            {
                SevenZip.SevenZipExtractor e7z = new SevenZip.SevenZipExtractor(ms);
                var outms = new System.IO.MemoryStream();
                e7z.ExtractFile(0, outms);
                var text = System.Text.Encoding.UTF8.GetString(outms.ToArray());
                var json = MyJson.Parse(text) as MyJson.JsonNode_Object;
                fullLog = SmartContract.Debug.FullLog.FromJson(json);
            }
            //循环所有的
            simvm.Execute(fullLog);
        }
Exemple #19
0
        public MatParser GetMatParser(string shaderName)
        {
            //if (debug)
            Debug.Log("getmatParser:" + shaderName);
            foreach (var m in matParsers.Keys)
            {
                Debug.Log(m);
            }
            if (matParsers.ContainsKey(shaderName) == false)
            {
#if UNITY_EDITOR
                Debug.LogWarning("try load shader:" + shaderName);
                string path = Application.dataPath + "/resources/shaderparser";
                if (System.IO.Directory.Exists(path) == false)
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                //string shadername = mat.shader.name;
                //shadername = shadername.Replace("/", "%2f");
                var    shaderfileName        = shaderName.Replace("/", "%2f");
                string file                  = path + "/" + shaderfileName + ".shaderparser.txt";
                byte[] jsonbyte              = System.IO.File.ReadAllBytes(file);
                string jsontxt               = System.Text.Encoding.UTF8.GetString(jsonbyte);
                MyJson.JsonNode_Object _json = MyJson.Parse(jsontxt) as MyJson.JsonNode_Object;
                InitMatParser(shaderfileName, _json);
                return(GetMatParser(shaderName));
#endif
                return(null);
            }

            return(matParsers[shaderName]);
        }
Exemple #20
0
        string GetBalanceFromJson(string info)
        {
            string result = "";

            MyJson.JsonNode_Object json = MyJson.Parse(info) as MyJson.JsonNode_Object;

            if (json.ContainsKey("result"))
            {
                MyJson.JsonNode_Object json_result = json["result"] as MyJson.JsonNode_Object;
                MyJson.JsonNode_Array  stack       = json_result["stack"] as MyJson.JsonNode_Array;

                if (stack != null && stack.Count >= 2)
                {
                    string balance  = ZoroHelper.GetJsonValue(stack[0] as MyJson.JsonNode_Object);
                    string decimals = ZoroHelper.GetJsonValue(stack[1] as MyJson.JsonNode_Object);

                    Decimal value = Decimal.Parse(balance) / new Decimal(Math.Pow(10, int.Parse(decimals)));
                    string  fmt   = "{0:N" + decimals + "}";
                    result = string.Format(fmt, value);
                }
            }
            else if (json.ContainsKey("error"))
            {
                MyJson.JsonNode_Object json_error_obj = json["error"] as MyJson.JsonNode_Object;
                result = json_error_obj.ToString();
            }

            return(result);
        }
Exemple #21
0
        //點擊安裝插件
        private async void Click_Install(object sender, RoutedEventArgs e)
        {
            Button btn        = (sender as Button);
            var    pluginType = ((btn.Parent as StackPanel).Children[1] as Label).Content.ToString().Split(' ')[0];
            var    version    = servicePackageInfo[pluginType].ToString();

            ForbidAllBtnClick();

            //安装按钮隐藏  等待按钮显示
            Image img = this.FindName(pluginType + "_gif_loading") as Image;

            img.Visibility = Visibility.Visible;
            btn.Visibility = Visibility.Hidden;

            EnumInstallType type    = EnumInstallType.Plugin;
            EnumPluginType  content = (EnumPluginType)Enum.Parse(typeof(EnumPluginType), pluginType);

            byte[] postdata;
            //从服务器获取固件或插件
            var url = HttpHelper.MakeRpcUrlPost("https://apiaggr.nel.group/api/testnet", "downloadplugin", out postdata, new MyJson.JsonNode_ValueString(pluginType + "_" + version));
            var res = await HttpHelper.HttpPost(url, postdata);

            var str_plugin = MyJson.Parse(res).AsDict()["result"].AsList()[0].AsDict()["plugin"].ToString();

            byte[] data = ThinNeo.Helper.HexString2Bytes(str_plugin);

            Result result = await ManagerControl.Ins.ToDo(EnumControl.InstallPlugin, data, type, content, version);

            GetPackageInfo();
            img.Visibility = Visibility.Hidden;
            btn.Visibility = Visibility.Visible;
            AllowAllBtnClick();
        }
Exemple #22
0
        async public static Task Demo()
        {
            string privateKey = "7c5a23ddb24c5eacb200874a32a64585bea7f1dd8efa23745e2b2a7753004c81";
            string targetAddr = "AZr9EpWFwx9dJZd7nncx5eGAB5zaW9iW1Y";

            byte[] prikey  = ThinNeo.Helper.HexString2Bytes(privateKey);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            Console.WriteLine("确认我执行到了这里");
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(api, address);

            //拼装交易体
            string[] targetAddrs = new string[1] {
                targetAddr
            };
            Transaction tran = makeTran(dir, targetAddrs, new Hash256(id_GAS), (decimal)1);

            tran.version = 0;
            tran.type    = TransactionType.ContractTransaction;
            byte[] msg      = tran.GetMessage();
            byte[] signdata = ThinNeo.Helper.Sign(msg, prikey);
            tran.AddWitness(signdata, pubkey, address);
            string txid = tran.GetHash().ToString();

            byte[] data    = tran.GetRawData();
            string rawdata = ThinNeo.Helper.Bytes2HexString(data);

            byte[] postdata;
            var    url    = Helper.MakeRpcUrlPost(api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
            var    result = await Helper.HttpPost(url, postdata);

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
            Console.WriteLine(resJO.ToString());
        }
Exemple #23
0
    private void OnPhpServer(string serverStr)
    {
        if (!string.IsNullOrEmpty(serverStr))
        {
            MyJson.JsonNode_Object jsonNode = MyJson.Parse(serverStr) as MyJson.JsonNode_Object;
            if (jsonNode == null)
            {
                Utils.LogError(serverStr);
            }
            else
            {
                //URLFactory.ServerGameResPath = jsonNode["ServerGameResPath"].AsString() + NetManager.PackageStyle + "/";
                //if (jsonNode.ContainsKey("AnyAmount")) URLFactory.AnyAmount = jsonNode["AnyAmount"].AsInt();
                //根据web服务器Php返回, 修正各链接地址
                URLFactory.NewAppVersion = jsonNode["version"].AsString();
                URLFactory.NewApkWebUrl  = jsonNode["apkUrl"].AsString();//ApkUrl

                if (!AppVersionCompare(Application.version, URLFactory.NewAppVersion))
                {
                    StartCoroutine(StartInit());
                }
                else // 更新大版本
                {
                    string msg = "游戏版本过低,请下载最新安装包进行游戏";
                    Utils.MessagePopup(msg, UpdateIphonePackage, 1, true, "前往");
                }
            }
        }
        else
        {
            Timers.inst.Add(3, 1, OnWaitToGetWebPath);
        }
    }
        async public static Task <MyJson.JsonNode_Object> handle(int height)
        {
            var queryArr = Mongo.Find(Collection, "index", height);

            if (queryArr.Count == 0)
            {
                var blockData = await Rpc.getblock(Config.NeoCliJsonRPCUrl, height);

                blockData.Remove("confirmations");
                blockData.Remove("nextblockhash");

                Collection.InsertOne(BsonDocument.Parse(blockData.ToString()));
                //Mongo.SetSystemCounter(collectionType, height);
                return(blockData);
            }
            else
            {
                BsonDocument queryB             = queryArr[0].AsBsonDocument;
                var          jsonWriterSettings = new JsonWriterSettings {
                    OutputMode = JsonOutputMode.Strict
                };
                MyJson.JsonNode_Object block = MyJson.Parse(queryB.ToJson(jsonWriterSettings)) as MyJson.JsonNode_Object;
                return(block);
            }
        }
Exemple #25
0
        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var str    = MakeRpcUrl("getassets");
            var result = await wc.DownloadStringTaskAsync(str);

            var json = MyJson.Parse(result).asDict()["result"].asDict();

            listAssets.Items.Clear();
            Dictionary <string, string> mapName = new Dictionary <string, string>();

            foreach (var item in json)
            {
                var    names   = item.Value.asDict()["name"].AsList();
                string outname = "";
                foreach (var n in names)
                {
                    if (n.asDict()["lang"].AsString() == "en")
                    {
                        outname           = n.asDict()["name"].AsString();
                        mapName[item.Key] = outname;
                    }
                }
                listAssets.Items.Add(item.Key + ":[" + outname + "]");
            }
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                this.asmList.Items.Clear();

                var json = MyJson.Parse(jsonParam.Text).AsList();
                jsonParam.Foreground = new SolidColorBrush(Color.FromRgb(0, 0, 0));
                ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
                var list = json.AsList();
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    sb.EmitParamJson(list[i]);
                }
                var scripthash = ThinNeo.Helper.HexString2Bytes(textScriptHash.Text).Reverse().ToArray();
                sb.EmitAppCall(scripthash);
                this.script = sb.ToArray();
                var ops = ThinNeo.Compiler.Avm2Asm.Trans(this.script);
                for (int i = 0; i < ops.Length; i++)
                {
                    this.asmList.Items.Add(ops[i]);
                }
                this.asmBinText.Text = ThinNeo.Helper.Bytes2HexString(sb.ToArray());
            }
            catch
            {
                jsonParam.Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0));
            }
        }
Exemple #27
0
        public static void uploadScript(string api, string path, string hash)
        {
            System.Net.WebClient wc = new MyWebClient();
            try
            {
                System.Collections.Specialized.NameValueCollection vs = new System.Collections.Specialized.NameValueCollection();
                vs["jsonrpc"] = "2.0";
                vs["id"]      = "1";
                vs["method"]  = "setcontractscript";
                MyJson.JsonNode_Array  array   = new MyJson.JsonNode_Array();
                MyJson.JsonNode_Object jsonmap = new MyJson.JsonNode_Object();
                jsonmap["hash"] = new MyJson.JsonNode_ValueString(hash);
                var avm = System.IO.File.ReadAllBytes(System.IO.Path.Combine(path, hash + ".avm"));
                var cs  = System.IO.File.ReadAllText(System.IO.Path.Combine(path, hash + ".cs"));
                var map = System.IO.File.ReadAllText(System.IO.Path.Combine(path, hash + ".map.json"));
                var abi = System.IO.File.ReadAllText(System.IO.Path.Combine(path, hash + ".abi.json"));

                jsonmap["avm"] = new MyJson.JsonNode_ValueString(ThinNeo.Helper.Bytes2HexString(avm));
                jsonmap["cs"]  = new MyJson.JsonNode_ValueString(Uri.EscapeDataString(cs));
                jsonmap["map"] = MyJson.Parse(map);
                jsonmap["abi"] = MyJson.Parse(abi);
                array.Add(new MyJson.JsonNode_ValueString(jsonmap.ToString()));
                vs["params"] = array.ToString();

                var ret = wc.UploadValues(api, vs);
                var txt = System.Text.Encoding.UTF8.GetString(ret);
                MessageBox.Show(txt);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Exemple #28
0
        public JObject callContractForTest(string neoCliJsonRPCUrl, List <string> scripthashs, JArray paramsJA)
        {
            //string script = (string)getContractState(neoCliJsonRPCUrl, scripthash)["script"];
            int n = 0;

            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
            foreach (var scripthash in scripthashs)
            {
                var json = MyJson.Parse(JsonConvert.SerializeObject(paramsJA[n])).AsList();

                var list = json.AsList();
                for (int i = list.Count - 1; i >= 0; i--)
                {
                    sb.EmitParamJson(list[i]);
                }

                var scripthashReverse = ThinNeo.Helper.HexString2Bytes(scripthash).Reverse().ToArray();
                sb.EmitAppCall(scripthashReverse);

                n++;
            }

            string scriptPlusParams = ThinNeo.Helper.Bytes2HexString(sb.ToArray());

            return(invokeScript(neoCliJsonRPCUrl, scriptPlusParams));
        }
Exemple #29
0
        public static async Task <Result> api_GetBalance(Hash160 scripthash, string addr)
        {
            byte[] postdata;
            var    url  = Helper.MakeRpcUrlPost(Config.api, "getbalance", out postdata, new MyJson.JsonNode_ValueString(addr));
            var    text = await Helper.HttpPost(url, postdata);


            Result rest = new Result();

            rest.textInfo = text;
            //if (json.ContainsKey("result"))
            //{
            //    var result = json["result"].AsList()[0].AsDict()["stack"].AsList();
            //    rest.value = ResultItem.FromJson("Array", result);
            //}
            //return rest;// subPrintLine("得到的结果是:" + result);

            var json = MyJson.Parse(text).AsDict()["result"].AsList();

            foreach (var item in json)
            {
                if (item.AsDict()["asset"].AsString() == Config.id_GAS)
                {
                    Console.WriteLine("gas=" + item.AsDict()["balance"].ToString());
                }
                if (item.AsDict()["asset"].AsString() == Config.id_NEO)
                {
                    Console.WriteLine("neo=" + item.AsDict()["balance"].ToString());
                    rest.textInfo = item.AsDict()["balance"].ToString();
                }
            }
            return(rest);
        }
Exemple #30
0
        async public Task Demo()
        {
            string wif1       = "KwwJMvfFPcRx2HSgQRPviLv4wPrxRaLk7kfQntkH8kCXzTgAts8t";
            string targetAddr = "AdsNmzKPPG7HfmQpacZ4ixbv9XJHJs2ACz";

            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif1);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(api, address);

            //拼装交易体
            string[] targetAddrs = new string[1] {
                targetAddr
            };
            ThinNeo.Transaction tran = makeTran(dir, targetAddrs, new ThinNeo.Hash256(id_GAS), (decimal)1);
            tran.version = 0;
            tran.type    = ThinNeo.TransactionType.ContractTransaction;
            byte[] msg    = tran.GetMessage();
            string msgstr = ThinNeo.Helper.Bytes2HexString(msg);

            byte[] signdata = ThinNeo.Helper.Sign(msg, prikey);
            tran.AddWitness(signdata, pubkey, address);
            string txid = tran.GetHash().ToString();

            byte[] data    = tran.GetRawData();
            string rawdata = ThinNeo.Helper.Bytes2HexString(data);

            byte[] postdata;
            var    url    = Helper.MakeRpcUrlPost(api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
            var    result = await Helper.HttpPost(url, postdata);

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
            Console.WriteLine(resJO.ToString());
        }