public void WriteToJson(IResMgr resmgr, GameObject node, Component component, MyJson.JsonNode_Object json)
        {
            SkinnedMeshRenderer ic = component as SkinnedMeshRenderer;
            //json["type"] = new MyJson.JsonNode_ValueString(this.comptype.Name.ToLower());//必须的一行
            //放到外面去了

            //材质
            MyJson.JsonNode_Array mats = new MyJson.JsonNode_Array();

            json["mats"] = mats;

            foreach (var m in ic.sharedMaterials)
            {
                string hash = resmgr.SaveMat(m);
                mats.Add(new MyJson.JsonNode_ValueString(hash));
            }

            //bounds
            json["center"] = new MyJson.JsonNode_ValueString(StringHelper.ToString(ic.localBounds.center));
            json["size"] = new MyJson.JsonNode_ValueString(StringHelper.ToString(ic.localBounds.size));

            //mesh
            json["mesh"] = new MyJson.JsonNode_ValueString(resmgr.SaveMesh(ic.sharedMesh));

            json["rootboneobj"] = new MyJson.JsonNode_ValueNumber(ic.rootBone.gameObject.GetInstanceID());
            MyJson.JsonNode_Array bones = new MyJson.JsonNode_Array();
            foreach (var b in ic.bones)
            {
                bones.Add(new MyJson.JsonNode_ValueNumber(b.gameObject.GetInstanceID()));
            }
            json["boneobjs"] = bones;
            ic.rootBone.GetInstanceID();
        }
예제 #2
0
    public MyJson.IJsonNode Parser(Component com, NeedList list)
    {
        MeshRenderer t = com as MeshRenderer;
        var json = new MyJson.JsonNode_Object();
        json["castShadows"] = new MyJson.JsonNode_ValueNumber(t.castShadows);
        json["receiveShadows"] = new MyJson.JsonNode_ValueNumber(t.receiveShadows);
        json["useLightProbes"] = new MyJson.JsonNode_ValueNumber(t.useLightProbes);
        int meshcount = t.sharedMaterials.Length;

        json["materials"] = new MyJson.JsonNode_Array();
        foreach (var m in t.sharedMaterials)
        {
            MyJson.JsonNode_Object matobj = new MyJson.JsonNode_Object();
            json["materials"].AddArrayValue(matobj);

            matobj.SetDictValue("name", m.name);
            matobj.SetDictValue("shader", m.shader.name);
            matobj.SetDictValue("shaderkeyword", new MyJson.JsonNode_Array());
            foreach (var shaderkey in m.shaderKeywords)
            {
                matobj["shaderkeyword"].AddArrayValue(shaderkey);
            }
            if (m.mainTexture != null)
            {
                string name = AssetMgr.SaveTexture(m.mainTexture, System.IO.Path.Combine(Application.streamingAssetsPath, "texture"));
                matobj.SetDictValue("maintex", name);
                list.AddDependTexture(name);
            }
        }
        return json;
    }
        public void WriteToJson(IResMgr resmgr, GameObject node, Component component, MyJson.JsonNode_Object json)
        {
            FB.PosePlus.AniPlayer ic = component as FB.PosePlus.AniPlayer;

            MyJson.JsonNode_Array anis = new MyJson.JsonNode_Array();

            json["clips"] = anis;
            foreach (var m in ic.clips)
            {
                string hash = resmgr.SaveAniClip(m);
                anis.Add(new MyJson.JsonNode_ValueString(hash));
            }


        }
예제 #4
0
    public static string SaveAtlas(UIAtlas atlas, string path,string pathtex)
    {
        if (System.IO.Directory.Exists(path) == false)
        {
            System.IO.Directory.CreateDirectory(path);
        }
        string tname = SaveTexture(atlas.texture, pathtex);

        MyJson.JsonNode_Object obj = new MyJson.JsonNode_Object();

        obj["pixelSize"] = new MyJson.JsonNode_ValueNumber(atlas.pixelSize);
        var jsonmat = new MyJson.JsonNode_Object();
        obj["mat"] = jsonmat;
        jsonmat["shader"] = new MyJson.JsonNode_ValueString(atlas.spriteMaterial.shader.name);
        MyJson.JsonNode_Array shaderparams = new MyJson.JsonNode_Array();
        jsonmat["shaderparam"] = shaderparams;
        foreach (var p in atlas.spriteMaterial.shaderKeywords)
        {
            shaderparams.Add(new MyJson.JsonNode_ValueString(p));
        }

        jsonmat["img"] = new MyJson.JsonNode_ValueString(tname);
        var jsonsparray = new MyJson.JsonNode_Object();
        obj["sprites"] = jsonsparray;
        foreach (var s in atlas.spriteList)
        {
            MyJson.JsonNode_Array sarray = new MyJson.JsonNode_Array();
            jsonsparray[s.name] = sarray;
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.x));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.y));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.width));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.height));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.borderLeft));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.borderRight));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.borderTop));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.borderBottom));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.paddingLeft));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.paddingRight));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.paddingTop));
            sarray.Add(new MyJson.JsonNode_ValueNumber(s.paddingBottom));
        }
        string atalsName = atlas.name.ToLower();
        System.IO.File.WriteAllText(System.IO.Path.Combine(path, atalsName + ".atlas.txt"), obj.ToString());

        return atalsName;
    }
예제 #5
0
    void check_list(MyJson.JsonNode_Array json)
    {
        b_list_need_refresh = false;
        foreach (var item in json)
        {
            if (item.AsDict()["state"].ToString() == "0")
            {
                b_list_need_refresh = true;
            }
            else if (item.AsDict()["type"].ToString() == "2" && item.AsDict()["state"].ToString() == "1")
            {
                if (item.AsDict()["client_notify"].ToString() == "0")
                {
                    b_list_need_refresh = true;
                }
            }
        }

        if (!b_list_need_refresh)
        {
            onClick_Refresh();
        }
    }
        public static async Task <string> api_SendTransaction(byte[] prikey, Hash160 schash, string methodname, params string[] subparam)
        {
            byte[] data = null;
            //MakeTran
            ThinNeo.Transaction tran = 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(schash);
                    data = sb.ToArray();
                    Console.WriteLine(ThinNeo.Helper.Bytes2HexString(data));
                }
            }

            return(await nns_common.api_SendTransaction(prikey, data));
        }
예제 #7
0
        public void ParseUTXO(MyJson.JsonNode_Array jsonarray)
        {
            Dictionary <string, CoinType> cointype = new Dictionary <string, CoinType>();

            foreach (var item in jsonarray)
            {
                var asset = item.AsDict()["asset"].AsString();
                if (cointype.ContainsKey(asset) == false)
                {
                    var ctype = new CoinType(asset);
                    cointype[asset] = ctype;
                    allcoins.Add(ctype);
                }
                var coins = cointype[asset];
                var coin  = new UTXOCoin();
                coin.assetID = asset;
                coin.fromID  = item.AsDict()["txid"].AsString();
                coin.fromN   = item.AsDict()["n"].AsInt();
                var value = decimal.Parse(item.AsDict()["value"].AsString());
                coin.value = value;
                coins.coins.Add(coin);
            }
        }
예제 #8
0
    public Dictionary <string, List <Utxo> > get_utxo(string txt)
    {
        MyJson.JsonNode_Object response = (MyJson.JsonNode_Object)MyJson.Parse(txt);

        MyJson.JsonNode_Array             resJA = (MyJson.JsonNode_Array)response["result"];
        Dictionary <string, List <Utxo> > _dir  = new Dictionary <string, List <Utxo> >();

        foreach (MyJson.JsonNode_Object j in resJA)
        {
            Utxo utxo = new Utxo(j["addr"].ToString(), new ThinNeo.Hash256(j["txid"].ToString()), j["asset"].ToString(), decimal.Parse(j["value"].ToString()), int.Parse(j["n"].ToString()));
            if (_dir.ContainsKey(j["asset"].ToString()))
            {
                _dir[j["asset"].ToString()].Add(utxo);
            }
            else
            {
                List <Utxo> l = new List <Utxo>();
                l.Add(utxo);
                _dir[j["asset"].ToString()] = l;
            }
        }
        return(_dir);
    }
예제 #9
0
        public static string InvokeScript(string url, string method, string schash, string scmethod, params string[] scparams)
        {
            byte[] data = null;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();

                for (var i = 0; i < scparams.Length; i++)
                {
                    array.AddArrayValue(scparams[i]);
                }
                sb.EmitParamJson(array);
                sb.EmitPushString(scmethod);
                sb.EmitAppCall(new Hash160(schash));
                data = sb.ToArray();
            }
            string script = ThinNeo.Helper.Bytes2HexString(data);
            var    res    = HttpHelper.Post(url, method, new JArray {
                new JValue(script)
            });

            return(res);
        }
예제 #10
0
        //public Dictionary<string, byte[]> codes = new Dictionary<string, byte[]>();
        //public byte[] GetScript(byte[] script_hash)
        //{
        //    string strhash = "";
        //    foreach (var b in script_hash)
        //    {
        //        strhash += b.ToString("X02");
        //    }
        //    return codes[strhash];
        //}
        public string GenJson()
        {
            MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
            json["__name__"] = new MyJson.JsonNode_ValueString("neomodule.");

            //code
            var jsoncode = new MyJson.JsonNode_Array();

            json["code"] = jsoncode;
            foreach (var c in this.total_Codes.Values)
            {
                jsoncode.Add(c.GenJson());
            }
            //code bytes
            var code    = this.Build();
            var codestr = "";

            foreach (var c in code)
            {
                codestr += c.ToString("X02");
            }
            json.SetDictValue("codebin", codestr);

            //calls
            MyJson.JsonNode_Object methodinfo = new MyJson.JsonNode_Object();
            json["call"] = methodinfo;
            foreach (var m in this.mapMethods)
            {
                methodinfo[m.Key] = m.Value.GenJson();
            }


            StringBuilder sb = new StringBuilder();

            json.ConvertToStringWithFormat(sb, 4);
            return(sb.ToString());
        }
예제 #11
0
        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();
                if (subparam != null && subparam.Length > 0)
                {
                    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(Config.api, "invokescript", out postdata, new MyJson.JsonNode_ValueString(script));
            var    text = await Helper.HttpPost(url, postdata);

            //Console.WriteLine(text);
            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);
        }
예제 #12
0
    //从市场里面提币
    void test_drawToken()
    {
        MyJson.JsonNode_Array paparms = new MyJson.JsonNode_Array();

        MyJson.JsonNode_Object paparms_1 = new MyJson.JsonNode_Object();
        var array = new MyJson.JsonNode_Array();

        array.AddArrayValue("(addr)AYTcTTB8jpWtGgs8ukoUrQPm1zmEFxZHNk");
        array.AddArrayValue("(int)" + 100000000);
        paparms_1["sbParamJson"]  = array;
        paparms_1["sbPushString"] = new MyJson.JsonNode_ValueString("drawToken");
        paparms_1["nnc"]          = new MyJson.JsonNode_ValueString("0x7753e79cfb98e63e2b7aa00a819e0cb86fdb1930");

        MyJson.JsonNode_Object paparms_extString = new MyJson.JsonNode_Object();
        paparms_extString["txType"] = new MyJson.JsonNode_ValueString("transferNepToAuc");
        paparms_extString["kind"]   = new MyJson.JsonNode_ValueString("0");
        paparms_extString["data"]   = new MyJson.JsonNode_ValueString("1");

        paparms_1["extString"] = paparms_extString;

        paparms.AddArrayValue(paparms_1);

        NeoGameSDK_CS.makeRawTransaction((bool timeout, WWW www) => { Debug.Log(www.text); }, paparms);
    }
예제 #13
0
 static public void friend_getlist()
 {
     try
     {
         String   URL = Config.ROOT_URL + "friend_getlist";
         PostData nvc = new PostData();
         Func.putPassWord(nvc);
         //nvc.Add("order", "addtime");
         //nvc.Add("desc", "DESC");
         nvc.Add("start", "0");
         nvc.Add("count", "0");
         nvc.Add("tag", "qq");
         nvc.Add("tagval", "251197161");
         if (nvc != null)
         {
             string sttuas = Func.HttpPostData(URL, 10000, nvc);
             if (sttuas.Length > 10)
             {
                 MyJson.JsonNode_Array jsons = MyJson.Parse(sttuas) as MyJson.JsonNode_Array;
                 for (int i = 0; i < jsons.GetListCount(); i++)
                 {
                     MyJson.JsonNode_Object json = jsons.GetArrayItem(i) as MyJson.JsonNode_Object;
                     QQFriend info = new QQFriend();
                     info.qq      = json["qq"].AsString();
                     info.qqfri   = json["qqfri"].AsString();
                     info.addtime = Func.MyUrlDeCode(json["addtime"].AsString());
                     info.state   = Func.MyUrlDeCode(json["state"].AsString());
                     lsQQFriend.Add(info);
                 }
             }
         }
     }
     catch (Exception)
     {
     }
 }
        public void WriteToJson(IResMgr resmgr, GameObject node, Component component, MyJson.JsonNode_Object json)
        {
            MeshRenderer ic = component as MeshRenderer;
            //json["type"] = new MyJson.JsonNode_ValueString(this.comptype.Name.ToLower());//必须的一行
            //放到外面去了

            MyJson.JsonNode_Array mats = new MyJson.JsonNode_Array();

            json["mats"] = mats;
#if UNITY_EDITOR
            foreach (var m in ic.sharedMaterials)
            {
                string hash = resmgr.SaveMat(m);
                mats.Add(new MyJson.JsonNode_ValueString(hash));
            }
#else
            foreach (var m in ic.materials)
            {
                string hash = resmgr.SaveMat(m);
                mats.Add(new MyJson.JsonNode_ValueString(hash));
            }
#endif

        }
예제 #15
0
        private static async Task <Dictionary <string, List <UTXO> > > GetUTXOByAddress(string address)
        {
            MyJson.JsonNode_Object response = (MyJson.JsonNode_Object)MyJson.Parse(
                await HttpHelper.HttpGet("https://api.nel.group/api/testnet?method=getutxo&id=1&params=['" + address + "']"));
            MyJson.JsonNode_Array             resJA = (MyJson.JsonNode_Array)response["result"];
            Dictionary <string, List <UTXO> > dic   = new Dictionary <string, List <UTXO> >();

            foreach (MyJson.JsonNode_Object j in resJA)
            {
                UTXO utxo = new UTXO(j["addr"].ToString(), new Hash256(j["txid"].ToString()), j["asset"].ToString(),
                                     decimal.Parse(j["value"].ToString()), int.Parse(j["n"].ToString()));
                if (dic.ContainsKey(j["asset"].ToString()))
                {
                    dic[j["asset"].ToString()].Add(utxo);
                }
                else
                {
                    List <UTXO> list = new List <UTXO>();
                    list.Add(utxo);
                    dic[j["asset"].ToString()] = list;
                }
            }
            return(dic);
        }
예제 #16
0
        public void WriteToJson(IResMgr resmgr, GameObject node, Component component, MyJson.JsonNode_Object json)
        {
            MeshRenderer ic = component as MeshRenderer;

            //json["type"] = new MyJson.JsonNode_ValueString(this.comptype.Name.ToLower());//必须的一行
            //放到外面去了

            MyJson.JsonNode_Array mats = new MyJson.JsonNode_Array();

            json["mats"] = mats;
#if UNITY_EDITOR
            foreach (var m in ic.sharedMaterials)
            {
                string hash = resmgr.SaveMat(m);
                mats.Add(new MyJson.JsonNode_ValueString(hash));
            }
#else
            foreach (var m in ic.materials)
            {
                string hash = resmgr.SaveMat(m);
                mats.Add(new MyJson.JsonNode_ValueString(hash));
            }
#endif
        }
예제 #17
0
        MyJson.IJsonNode _rpc_ver_finish(string token, int ver)
        {
            string user;
            string game   = CheckToken(token, out user);
            var    vgroup = versions[game];

            MyJson.JsonNode_Object obj = new MyJson.JsonNode_Object();
            if (commits.ContainsKey(user) == false)
            {
                obj.SetDictValue("status", -2004);
                obj.SetDictValue("msg", "not found commit.");
                return(obj);
            }
            var commit = commits[user];

            if (commit.ver != ver)
            {
                obj.SetDictValue("status", -2005);
                obj.SetDictValue("msg", "not right commit ver.");
                return(obj);
            }
            MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
            bool b = commit.Run(vgroup.path, array);

            obj.SetDictValue("info", array);
            if (!b)
            {
                obj.SetDictValue("status", -2006);
                obj.SetDictValue("msg", "commit fall.");
            }
            else
            {
                obj.SetDictValue("status", 0);
            }
            return(null);
        }
예제 #18
0
        public MyJson.JsonNode_Object ToJson()
        {
            MyJson.JsonNode_Object _op = new MyJson.JsonNode_Object();
            _op.SetDictValue("addr", addr);
            _op.SetDictValue("op", op.ToString());
            if (this.stack != null)
            {
                MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
                _op.SetDictValue("stack", array);
                foreach (var r in stack)
                {
                    if (r.ind > 0)
                    {
                        array.AddArrayValue(r.type.ToString() + "|" + r.ind);
                    }
                    else
                    {
                        array.AddArrayValue(r.type.ToString());
                    }
                }
            }
            if (opresult != null)
            {
                _op.SetDictValue("result", StatkItemToJson(opresult));
            }
            if (opparam != null)
            {
                _op.SetDictValue("param", opparam.ToHexString());
            }
            if (subScript != null)
            {
                _op.SetDictValue("subscript", subScript.ToJson());
            }

            return(_op);
        }
예제 #19
0
        async Task test_setUpgrade()
        {
            byte[] pubkey_admin = ThinNeo.Helper.GetPublicKeyFromPrivateKey(adminPrikey);
            string address      = ThinNeo.Helper.GetAddressFromPublicKey(pubkey_admin);

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

            //从文件中读取合约脚本
            //byte[] script = System.IO.File.ReadAllBytes("C:\\Neo\\SmartContracts\\0x89151760dba47464bbed6600b651e210996a318b.avm"); //这里填你的合约所在地址
            byte[] script = System.IO.File.ReadAllBytes("C:\\Users\\wqq19\\Documents\\workspace\\solution\\OracleContract\\bin\\Debug\\0x2eaef11fa90014ccf4ae8bfabc0f58e7fc8bd591.avm");

            string str_script = ThinNeo.Helper.Bytes2HexString(script);

            byte[] aa = ThinNeo.Helper.HexString2Bytes(str_script);
            var    ss = 1 | 2 | 4;

            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                //倒叙插入数据
                var array = new MyJson.JsonNode_Array();
                array.AddArrayValue("(bytes)" + str_script);
                array.AddArrayValue("(bytes)0710");
                array.AddArrayValue("(bytes)05");
                array.AddArrayValue("(int)" + 5);
                array.AddArrayValue("(str)合约升级测试");                                //name
                array.AddArrayValue("(str)1");                                     //version
                array.AddArrayValue("(str)ss");                                    //author
                array.AddArrayValue("(str)1");                                     //email
                array.AddArrayValue("(str)sssss");                                 //desc
                sb.EmitParamJson(array);                                           //参数倒序入
                sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)upgrade")); //参数倒序入
                //var shash = Config.oracleAssetID;
                sb.EmitAppCall(shash);

                string scriptPublish = ThinNeo.Helper.Bytes2HexString(sb.ToArray());
                byte[] postdata;
                var    url    = Helper.MakeRpcUrlPost(Config.api, "invokescript", out postdata, new MyJson.JsonNode_ValueString(scriptPublish));
                var    result = await Helper.HttpPost(url, postdata);

                //string result = http.Post(api, "invokescript", new MyJson.JsonNode_Array() { new MyJson.JsonNode_ValueString(scriptPublish) },Encoding.UTF8);
                //var consume = (((MyJson.Parse(result) as MyJson.JsonNode_Object)["result"] as MyJson.JsonNode_Array)[0] as MyJson.JsonNode_Object)["gas_consumed"].ToString();
                //decimal gas_consumed = decimal.Parse(consume);
                ThinNeo.InvokeTransData extdata = new ThinNeo.InvokeTransData();
                extdata.gas    = 1010;// Math.Ceiling(gas_consumed - 10);
                extdata.script = sb.ToArray();

                //拼装交易体
                ThinNeo.Transaction tran = Helper.makeTran(dir[Config.id_GAS], null, new ThinNeo.Hash256(Config.id_GAS), extdata.gas);
                tran.version = 1;
                tran.extdata = extdata;
                tran.type    = ThinNeo.TransactionType.InvocationTransaction;
                byte[] msg      = tran.GetMessage();
                byte[] signdata = ThinNeo.Helper.Sign(msg, adminPrikey);
                tran.AddWitness(signdata, pubkey_admin, address);
                string txid    = tran.GetHash().ToString();
                byte[] data    = tran.GetRawData();
                string rawdata = ThinNeo.Helper.Bytes2HexString(data);
                url    = Helper.MakeRpcUrlPost(Config.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
                result = await Helper.HttpPost(url, postdata);

                MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
                Console.WriteLine(resJO.ToString());
            }
        }
예제 #20
0
        public void ZoroTransfer()
        {
            byte[]        prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif);
            var           pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            var           address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            ScriptBuilder sb      = new ScriptBuilder();

            MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
            array.AddArrayValue("(addr)" + from);
            array.AddArrayValue("(addr)" + "AUB7tMoKTzN33iVVqhz98vnT3KiG4bqx3f"); //ZoroBank address   AUB7tMoKTzN33iVVqhz98vnT3KiG4bqx3f
            array.AddArrayValue("(int)" + value);
            byte[] randomBytes = new byte[32];
            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(randomBytes);
            }
            BigInteger randomNum = new BigInteger(randomBytes);

            sb.EmitPushNumber(randomNum);
            sb.Emit(ThinNeo.VM.OpCode.DROP);
            sb.EmitParamJson(array);
            sb.EmitPushString("transfer");
            sb.EmitAppCall(new Hash160("0x67147557c0b6431e9b9297de26b46d9889434e49"));

            Hash160 scripthash    = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);
            string  scriptPublish = ThinNeo.Helper.Bytes2HexString(sb.ToArray());

            byte[] postdata;

            ThinNeo.InvokeTransData extdata = new ThinNeo.InvokeTransData();
            extdata.script = sb.ToArray();
            extdata.gas    = 0;

            ThinNeo.Transaction tran = Helper.makeTran(null, null, new ThinNeo.Hash256(Config.getValue("id_GAS")),
                                                       extdata.gas);
            tran.version = 1;
            tran.extdata = extdata;
            tran.type    = ThinNeo.TransactionType.InvocationTransaction;

            //附加鉴证
            tran.attributes          = new ThinNeo.Attribute[1];
            tran.attributes[0]       = new ThinNeo.Attribute();
            tran.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script;
            tran.attributes[0].data  = scripthash;

            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);

            MyJson.JsonNode_Array postRawArray = new MyJson.JsonNode_Array();
            postRawArray.AddArrayValue(chainHash); //跟链
            postRawArray.AddArrayValue(rawdata);

            var url    = Helper.MakeRpcUrlPost(ZoroRpcUrl, "sendrawtransaction", out postdata, postRawArray.ToArray());
            var result = Helper.HttpPost(url, postdata).Result;

            Console.WriteLine(result + " txid: " + txid);
        }
예제 #21
0
        async public Task Demo()
        {
            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(testwif);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            byte[] scripthash = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);
            Console.WriteLine("address=" + address);

            {//查balance
                string script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(bytes)" + ThinNeo.Helper.Bytes2HexString(scripthash));
                    sb.EmitParamJson(array);                                             //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)balanceOf")); //参数倒序入
                    ThinNeo.Hash160 shash = new ThinNeo.Hash160(nep55);
                    sb.EmitAppCall(shash);                                               //nep5脚本
                    var data = sb.ToArray();
                    script = ThinNeo.Helper.Bytes2HexString(data);
                }

                //var url = Helper.MakeRpcUrl(api, "invokescript", new MyJson.JsonNode_ValueString(script));
                //string result = await Helper.HttpGet(url);

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

                Console.WriteLine("得到的结果是:" + result);
                var json = MyJson.Parse(result).AsDict();
                if (json.ContainsKey("result"))
                {
                    var resultv = json["result"].AsList()[0].AsDict()["stack"].AsList()[0].AsDict();
                    var rtype   = resultv["type"].AsString();
                    var rvalue  = resultv["value"].AsString();
                    Console.WriteLine("type=" + rtype + "  value=" + rvalue);
                    var n = new System.Numerics.BigInteger(ThinNeo.Helper.HexString2Bytes(rvalue));
                    Console.WriteLine("value dec=" + n.ToString());
                }
            }

            if (lastNep5Tran != null)
            {
                string script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(hex256)" + lastNep5Tran.ToString());
                    sb.EmitParamJson(array);                                             //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)getTXInfo")); //参数倒序入
                    ThinNeo.Hash160 shash = new ThinNeo.Hash160(nep55);
                    sb.EmitAppCall(shash);                                               //nep5脚本
                    var data = sb.ToArray();
                    script = ThinNeo.Helper.Bytes2HexString(data);
                }
                byte[] postdata;
                var    url    = Helper.MakeRpcUrlPost(api, "invokescript", out postdata, new MyJson.JsonNode_ValueString(script));
                var    result = await Helper.HttpPost(url, postdata);

                Console.WriteLine("得到的结果是:" + result);
            }
        }
예제 #22
0
        private static async Task parseJAVA(IOwinContext context, FormData formdata)
        {
            try
            {
                string dictname  = null;
                string classname = null;
                var    file      = formdata.mapFiles["file"];
                var    code      = System.Text.Encoding.UTF8.GetString(file);

                //准备临时目录
                {
                    Random i   = new Random();
                    var    num = i.Next();

                    while (System.IO.Directory.Exists("tmp\\tmp_" + num.ToString("X08")))
                    {
                        num++;
                    }
                    dictname = "tmp\\tmp_" + num.ToString("X08");

                    var fc     = code.IndexOf("class");
                    int ibegin = -1;

                    for (int ib = fc + 6; ib < fc + 100; ib++)
                    {
                        if (ibegin < 0)
                        {
                            if (code[ib] == ' ')
                            {
                                continue;
                            }
                            else
                            {
                                ibegin = ib;
                            }
                        }
                        else
                        {
                            if (code[ib] == ' ' || code[ib] == '}')
                            {
                                classname = code.Substring(ibegin, ib - ibegin);
                                break;
                            }
                        }
                    }
                }
                System.IO.Directory.CreateDirectory(dictname);
                string filename = System.IO.Path.Combine(dictname, classname + ".java");
                System.IO.File.WriteAllText(filename, code);
                string jarfile = "AntShares.SmartContract.Framework.jar";
                System.IO.File.Copy(jarfile, System.IO.Path.Combine(dictname, jarfile));

                //编译
                try
                {
                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.FileName               = "cmd.exe";
                    info.UseShellExecute        = false;
                    info.RedirectStandardOutput = true;
                    info.RedirectStandardInput  = true;
                    info.RedirectStandardError  = true;
                    info.WorkingDirectory       = dictname;
                    var proc = System.Diagnostics.Process.Start(info);
                    proc.StandardInput.WriteLine("javac -cp " + jarfile + " " + classname + ".java");
                    proc.StandardInput.WriteLine("exit");


                    string        back      = proc.StandardError.ReadToEnd();
                    string        inerror   = "";
                    int           line      = -1;
                    string        tag       = "";
                    List <string> outline   = new List <string>();
                    List <int>    errorline = new List <int>();
                    List <string> errorTag  = new List <string>();
                    string[]      lines     = back.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    for (var i = 0; i < lines.Length; i++)
                    {
                        if (inerror == "")
                        {
                            var mm = lines[i].Split(':');
                            if (mm.Length > 3)
                            {
                                line     = int.Parse(mm[1]);
                                inerror += mm[3];
                                tag      = mm[2];
                            }
                        }
                        else
                        {
                            if (lines[i].IndexOf("^") >= 0)
                            {
                                outline.Add(inerror);
                                errorline.Add(line);
                                errorTag.Add(tag);
                                inerror = "";
                            }
                            else
                            {
                                inerror += "\n" + lines[i];
                            }
                        }
                    }

                    if (outline.Count == 0)
                    {
                        //succ
                    }
                    else
                    {
                        MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                        json["tag"] = new MyJson.JsonNode_ValueNumber(-3);
                        json["msg"] = new MyJson.JsonNode_ValueString("compile fail.");

                        MyJson.JsonNode_Array errs = new MyJson.JsonNode_Array();
                        json["errors"] = errs;
                        for (var i = 0; i < outline.Count; i++)
                        {
                            MyJson.JsonNode_Object errtag = new MyJson.JsonNode_Object();
                            errs.Add(errtag);
                            errtag.SetDictValue("msg", outline[i]);
                            errtag.SetDictValue("line", errorline[i]);
                            errtag.SetDictValue("tag", errorTag[i]);
                            //errtag.SetDictValue("col", r.Errors[i].Column);
                        }
                        await context.Response.WriteAsync(json.ToString());

                        return;
                    }
                }
                catch (Exception err)
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("unknown fail on comp.");
                    json["err"] = new MyJson.JsonNode_ValueString(err.ToString());
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }

                //conv
                try
                {
                    JavaModule module = new JavaModule();
                    module.LoadJar(jarfile);
                    module.LoadClass(System.IO.Path.Combine(dictname, classname + ".class"));
                    var logjson = new Log2Json();
                    var conv    = new Neo.Compiler.JVM.ModuleConverter(logjson);
                    var neomd   = conv.Convert(module);
                    var mm      = neomd.mapMethods[neomd.mainMethod];

                    var bs = neomd.Build();
                    if (bs != null)
                    {
                        MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                        json["tag"] = new MyJson.JsonNode_ValueNumber(0);
                        StringBuilder sb     = new StringBuilder();
                        StringBuilder sb2    = new StringBuilder();
                        var           hash   = System.Security.Cryptography.SHA256.Create();
                        var           hashbs = hash.ComputeHash(bs);
                        foreach (var b in bs)
                        {
                            sb.Append(b.ToString("X02"));
                        }
                        foreach (var b in hashbs)
                        {
                            sb2.Append(b.ToString("X02"));
                        }
                        json["hex"]  = new MyJson.JsonNode_ValueString(sb.ToString());
                        json["hash"] = new MyJson.JsonNode_ValueString(sb2.ToString());

                        json["returntype"] = new MyJson.JsonNode_ValueString(mm.returntype);
                        MyJson.JsonNode_Array funcparams = new MyJson.JsonNode_Array();
                        json["params"] = funcparams;
                        if (mm.paramtypes != null)
                        {
                            foreach (var v in mm.paramtypes)
                            {
                                funcparams.Add(new MyJson.JsonNode_ValueString(v.type));
                            }
                        }

                        await context.Response.WriteAsync(json.ToString());

                        return;
                    }


                    else
                    {
                        {
                            MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                            json["tag"]  = new MyJson.JsonNode_ValueNumber(-4);
                            json["msg"]  = new MyJson.JsonNode_ValueString("compile fail.");
                            json["info"] = logjson.array;
                            await context.Response.WriteAsync(json.ToString());

                            return;
                        }
                    }
                }
                catch (Exception err)
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("unknown fail on conv.");
                    json["err"] = new MyJson.JsonNode_ValueString(err.ToString());
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
            }
            catch
            {
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("parse fail.");
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
            }
        }
예제 #23
0
        private static async Task parseCSharp(IOwinContext context, FormData formdata)
        {
            try
            {
                var file = formdata.mapFiles["file"];
                var code = System.Text.Encoding.UTF8.GetString(file);

                //编译
                List <string> codes = new List <string>();
                codes.Add(code);
                CompilerResults r = null;

                try
                {
                    r = gencode.GenCode(codes, true);
                    if (r.Errors.Count > 0)
                    {
                        MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                        json["tag"] = new MyJson.JsonNode_ValueNumber(-3);
                        json["msg"] = new MyJson.JsonNode_ValueString("compile fail.");
                        MyJson.JsonNode_Array errs = new MyJson.JsonNode_Array();
                        json["errors"] = errs;
                        for (var i = 0; i < r.Errors.Count; i++)
                        {
                            MyJson.JsonNode_Object errtag = new MyJson.JsonNode_Object();
                            errs.Add(errtag);
                            errtag.SetDictValue("msg", r.Errors[i].ErrorText);
                            errtag.SetDictValue("line", r.Errors[i].Line);
                            errtag.SetDictValue("col", r.Errors[i].Column);
                            errtag.SetDictValue("tag", r.Errors[i].IsWarning ? "警告" : "错误");
                        }
                        await context.Response.WriteAsync(json.ToString());

                        return;
                    }
                }
                catch (Exception err)
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("unknown fail on comp.");
                    json["err"] = new MyJson.JsonNode_ValueString(err.ToString());
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
                //conv
                try
                {
                    var st = System.IO.File.OpenRead(r.PathToAssembly);
                    using (st)
                    {
                        var logjson = new Log2Json();

                        var module = new ILModule();
                        module.LoadModule(st, null);

                        var conv  = new Neo.Compiler.MSIL.ModuleConverter(logjson);
                        var neomd = conv.Convert(module);
                        //var mm = neomd.mapMethods[neomd.mainMethod];


                        var bs = neomd.Build();
                        if (bs != null)
                        {
                            {
                                MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                                json["tag"] = new MyJson.JsonNode_ValueNumber(0);
                                StringBuilder sb     = new StringBuilder();
                                StringBuilder sb2    = new StringBuilder();
                                var           hash   = System.Security.Cryptography.SHA256.Create();
                                var           hashbs = hash.ComputeHash(bs);
                                foreach (var b in bs)
                                {
                                    sb.Append(b.ToString("X02"));
                                }
                                foreach (var b in hashbs)
                                {
                                    sb2.Append(b.ToString("X02"));
                                }
                                json["hex"]  = new MyJson.JsonNode_ValueString(sb.ToString());
                                json["hash"] = new MyJson.JsonNode_ValueString(sb2.ToString());

                                var funcsigns = new MyJson.JsonNode_Object();
                                json["funcsigns"] = funcsigns;
                                foreach (var function in neomd.mapMethods)
                                {
                                    var mm       = function.Value;
                                    var ps       = mm.name.Split(new char[] { ' ', '(' }, StringSplitOptions.RemoveEmptyEntries);
                                    var funcsign = new MyJson.JsonNode_Object();
                                    funcsigns[ps[1]] = funcsign;
                                    funcsign.SetDictValue("name", ps[1]);
                                    var rtype = ConvCSharpType(mm.returntype);
                                    funcsign.SetDictValue("returntype", rtype);
                                    MyJson.JsonNode_Array funcparams = new MyJson.JsonNode_Array();
                                    funcsign["params"] = funcparams;
                                    if (mm.paramtypes != null)
                                    {
                                        foreach (var v in mm.paramtypes)
                                        {
                                            var ptype = ConvCSharpType(v.type);
                                            var item  = new MyJson.JsonNode_Object();
                                            funcparams.Add(item);
                                            item.SetDictValue("name", v.name);
                                            item.SetDictValue("type", ptype);
                                        }
                                    }
                                }
                                await context.Response.WriteAsync(json.ToString());

                                return;
                            }
                        }
                        else
                        {
                            {
                                MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                                json["tag"]  = new MyJson.JsonNode_ValueNumber(-4);
                                json["msg"]  = new MyJson.JsonNode_ValueString("compile fail.");
                                json["info"] = logjson.array;
                                await context.Response.WriteAsync(json.ToString());

                                return;
                            }
                        }
                    }
                }
                catch (Exception err)
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("unknown fail on conv.");
                    json["err"] = new MyJson.JsonNode_ValueString(err.ToString());
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
            }
            catch
            {
                {
                    MyJson.JsonNode_Object json = new MyJson.JsonNode_Object();
                    json["tag"] = new MyJson.JsonNode_ValueNumber(-2);
                    json["msg"] = new MyJson.JsonNode_ValueString("parse fail.");
                    await context.Response.WriteAsync(json.ToString());

                    return;
                }
            }
        }
예제 #24
0
        public static MyJson.JsonNode_Object Export(NeoModule module, byte[] script, Dictionary <int, int> addrConvTable)
        {
            var sha256 = System.Security.Cryptography.SHA256.Create();

            byte[] hash256   = sha256.ComputeHash(script);
            var    ripemd160 = new Neo.Cryptography.RIPEMD160Managed();
            var    hash      = ripemd160.ComputeHash(hash256);

            var outjson = new MyJson.JsonNode_Object();

            //hash
            StringBuilder sb = new StringBuilder();

            sb.Append("0x");
            foreach (var b in hash.Reverse().ToArray())
            {
                sb.Append(b.ToString("x02"));
            }
            outjson.SetDictValue("hash", sb.ToString());

            //functions
            var methods = new MyJson.JsonNode_Array();

            outjson["methods"] = methods;

            List <string> names = new List <string>();

            foreach (var function in module.mapMethods)
            {
                var mm = function.Value;
                if (mm.inSmartContract == false)
                {
                    continue;
                }
                if (mm.isPublic == false)
                {
                    continue;
                }

                var funcsign = new MyJson.JsonNode_Object();
                methods.Add(funcsign);
                funcsign.SetDictValue("name", function.Value.displayName);
                if (names.Contains(function.Value.displayName))
                {
                    throw new Exception("abi not allow same name functions");
                }
                names.Add(function.Value.displayName);
                var offset = addrConvTable?[function.Value.funcaddr] ?? function.Value.funcaddr;
                funcsign.SetDictValue("offset", offset.ToString());
                MyJson.JsonNode_Array funcparams = new MyJson.JsonNode_Array();
                funcsign["parameters"] = funcparams;
                if (mm.paramtypes != null)
                {
                    foreach (var v in mm.paramtypes)
                    {
                        var ptype = ConvType(v.type);
                        var item  = new MyJson.JsonNode_Object();
                        funcparams.Add(item);

                        item.SetDictValue("name", v.name);
                        item.SetDictValue("type", ptype);
                    }
                }

                var rtype = ConvType(mm.returntype);
                funcsign.SetDictValue("returnType", rtype);
            }

            //events
            var eventsigns = new MyJson.JsonNode_Array();

            outjson["events"] = eventsigns;
            foreach (var events in module.mapEvents)
            {
                var mm       = events.Value;
                var funcsign = new MyJson.JsonNode_Object();
                eventsigns.Add(funcsign);

                funcsign.SetDictValue("name", events.Value.displayName);
                MyJson.JsonNode_Array funcparams = new MyJson.JsonNode_Array();
                funcsign["parameters"] = funcparams;
                if (mm.paramtypes != null)
                {
                    foreach (var v in mm.paramtypes)
                    {
                        var ptype = ConvType(v.type);
                        var item  = new MyJson.JsonNode_Object();
                        funcparams.Add(item);

                        item.SetDictValue("name", v.name);
                        item.SetDictValue("type", ptype);
                    }
                }
                //event do not have returntype in nep3
                //var rtype = ConvType(mm.returntype);
                //funcsign.SetDictValue("returntype", rtype);
            }

            return(outjson);
        }
예제 #25
0
        public static MyJson.JsonNode_Object ExportDebugInfo(string avmName, NeoModule module)
        {
            var outjson = new MyJson.JsonNode_Object();

            var           debugMap          = new List <DebugMapEntry>();
            DebugMapEntry currentDebugEntry = null;

            var fileMap = new Dictionary <string, int>();

            List <byte> bytes = new List <byte>();

            foreach (var c in module.total_Codes.Values)
            {
                if (c.debugcode != null && c.debugline > 0 && c.debugline < 2000)
                {
                    currentDebugEntry          = new DebugMapEntry();
                    currentDebugEntry.startOfs = debugMap.Count > 0 ? bytes.Count : 0;
                    currentDebugEntry.endOfs   = currentDebugEntry.startOfs;
                    currentDebugEntry.url      = c.debugcode;
                    currentDebugEntry.line     = c.debugline;

                    if (!fileMap.ContainsKey(c.debugcode))
                    {
                        fileMap[c.debugcode] = fileMap.Count + 1;
                    }

                    debugMap.Add(currentDebugEntry);
                }
                else
                if (currentDebugEntry != null)
                {
                    currentDebugEntry.endOfs = bytes.Count;
                }
                bytes.Add((byte)c.code);
                if (c.bytes != null)
                {
                    for (var i = 0; i < c.bytes.Length; i++)
                    {
                        bytes.Add(c.bytes[i]);
                    }
                }
            }

            var hash = CalculateMD5(bytes.ToArray());

            string compilerName = System.AppDomain.CurrentDomain.FriendlyName.ToLowerInvariant();
            var    version      = Assembly.GetEntryAssembly().GetName().Version.ToString();

            var avmInfo = new MyJson.JsonNode_Object();

            avmInfo.Add("name", new MyJson.JsonNode_ValueString(avmName));
            avmInfo.Add("hash", new MyJson.JsonNode_ValueString(hash));

            var compilerInfo = new MyJson.JsonNode_Object();

            compilerInfo.Add("name", new MyJson.JsonNode_ValueString(compilerName));
            compilerInfo.Add("version", new MyJson.JsonNode_ValueString(version));

            var fileInfo = new MyJson.JsonNode_Array();

            foreach (var entry in fileMap)
            {
                var fileEntry = new MyJson.JsonNode_Object();
                fileEntry.Add("id", new MyJson.JsonNode_ValueNumber(entry.Value));
                fileEntry.Add("url", new MyJson.JsonNode_ValueString(entry.Key));
                fileInfo.AddArrayValue(fileEntry);
            }

            var mapInfo = new MyJson.JsonNode_Array();

            foreach (var entry in debugMap)
            {
                if (!fileMap.ContainsKey(entry.url))
                {
                    continue;
                }

                var fileID = fileMap[entry.url];

                var mapEntry = new MyJson.JsonNode_Object();
                mapEntry.Add("start", new MyJson.JsonNode_ValueNumber(entry.startOfs));
                mapEntry.Add("end", new MyJson.JsonNode_ValueNumber(entry.endOfs));
                mapEntry.Add("file", new MyJson.JsonNode_ValueNumber(fileID));
                mapEntry.Add("line", new MyJson.JsonNode_ValueNumber(entry.line));
                mapInfo.AddArrayValue(mapEntry);
            }

            outjson["avm"]      = avmInfo;
            outjson["compiler"] = compilerInfo;
            outjson["files"]    = fileInfo;
            outjson["map"]      = mapInfo;

            return(outjson);
        }
예제 #26
0
        private void downloadUserInfo()
        {
            try
            {
#if DEBUG
                String[] qqs =
                {
                    //"1532931245",
                    //"657565846",
                    "2517172830",
                    //"305723370",
                    //"947087352",
                };
                for (int i = 0; i < qqs.Length; i++)
                {
                    UserInfoDB info = new UserInfoDB();
                    info.qq = qqs[i];
                    dblist.Add(info);
                }
#else
                PostData nvc = new PostData();
                Func.putPassWord(nvc);
                nvc.Add("order", "time");
                nvc.Add("desc", "DESC");
                nvc.Add("start", "0");
                nvc.Add("count", "0");
                if (nvc != null)
                {
                    string sttuas = Func.HttpPostData(Config.GETLIST_ZONE_URL, 10000, nvc);
                    if (sttuas.Length > 10)
                    {
                        MyJson.JsonNode_Array jsons = MyJson.Parse(sttuas) as MyJson.JsonNode_Array;
                        for (int i = 0; i < jsons.GetListCount(); i++)
                        {
                            MyJson.JsonNode_Object json = jsons.GetArrayItem(i) as MyJson.JsonNode_Object;
                            UserInfoDB             info = new UserInfoDB();
                            info.qq               = json["qq"].AsString();
                            info.pqq              = json["pqq"].AsString();
                            info.nickname         = Func.MyUrlDeCode(json["nickname"].AsString());
                            info.age              = json["age"].AsInt();
                            info.sex              = Func.MyUrlDeCode(json["sex"].AsString());
                            info.birthday         = Func.MyUrlDeCode(json["birthday"].AsString());
                            info.mood             = json["mood"].AsInt();
                            info.photo            = json["photo"].AsInt();
                            info.blog             = json["blog"].AsInt();
                            info.heat             = json["heat"].AsInt();
                            info.zone_authority   = json["zone_authority"].AsInt();
                            info.friend_authority = json["friend_authority"].AsInt();
                            info.logintime        = Func.MyUrlDeCode(json["logintime"].AsString());
                            info.label            = Func.MyUrlDeCode(json["label"].AsString());
                            info.addfriend        = json["addfriend"].AsInt();
                            info.used             = json["used"].AsInt();
                            dblist.Add(info);
                        }
                    }
                }
#endif
            }
            catch (Exception e)
            {
                LogFile.add(e.ToString(), "Stopping.cs:updateUserInfo", 1);
            }
        }
예제 #27
0
        //退款操作
        async Task test_refund()
        {
            Console.WriteLine("Input refund tokens:");
            string refund = Console.ReadLine();

            string nep55_address = ThinNeo.Helper.GetAddressFromScriptHash(sneo_common.sc_sneo);

            Console.WriteLine("nep55_address=" + nep55_address);

            //获取地址的资产列表
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Config.api, nep55_address);

            if (dir.ContainsKey(Config.id_NEO) == false)
            {
                Console.WriteLine("no neo");
                return;
            }
            List <Utxo> newlist = new List <Utxo>(dir[Config.id_NEO]);

            for (var i = newlist.Count - 1; i >= 0; i--)
            {
                var ret = await sneo_common.api_InvokeScript(sneo_common.sc_sneo, "getRefundTarget", "(hex256)" + newlist[i].txid.ToString());

                sneo_common.ResultItem item = ret.value;

                if (newlist[i].n > 0)
                {
                    continue;
                }

                var value = item.subItem[0].AsString();
                if (value.Length > 0)//已经标记的UTXO,不能使用
                {
                    newlist.RemoveAt(i);
                }
            }


            ThinNeo.Transaction tran = null;
            {
                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(bytes)" + ThinNeo.Helper.Bytes2HexString(scripthash));
                    sb.EmitParamJson(array);                                          //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)refund")); //参数倒序入
                    sb.EmitAppCall(sneo_common.sc_sneo);                              //nep5脚本
                    script = sb.ToArray();
                }
                Console.WriteLine("contract address=" + nep55_address);//往合约地址转账

                //生成交易
                tran      = Helper.makeTran(newlist, nep55_address, new ThinNeo.Hash256(Config.id_NEO), Decimal.Parse(refund));
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = script;

                //附加鉴证
                tran.attributes          = new ThinNeo.Attribute[1];
                tran.attributes[0]       = new ThinNeo.Attribute();
                tran.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script;
                tran.attributes[0].data  = scripthash;
            }

            //sign and broadcast
            {//做智能合约的签名
                byte[] iscript = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    sb.EmitPushString("whatever");
                    sb.EmitPushNumber(250);
                    iscript = sb.ToArray();
                }
                tran.AddWitnessScript(n55contract, iscript);
            }
            {//做提款人的签名
                var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);
                tran.AddWitness(signdata, pubkey, address);
            }
            var trandata    = tran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

            ThinNeo.Transaction testde = new ThinNeo.Transaction();
            testde.Deserialize(new System.IO.MemoryStream(trandata));

            byte[] postdata;
            var    url = Helper.MakeRpcUrlPost(Config.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));

            string poststr = System.Text.Encoding.UTF8.GetString(postdata);
            //Console.WriteLine("-----post info begin----");
            //Console.WriteLine(poststr);
            //Console.WriteLine("-----post info end----");
            var result = await Helper.HttpPost(url, postdata);

            Console.WriteLine("得到的结果是:" + result);
            var json = MyJson.Parse(result).AsDict();

            if (json.ContainsKey("result"))
            {
                bool bSucc = false;
                if (json["result"].type == MyJson.jsontype.Value_Number)
                {
                    bSucc = json["result"].AsBool();
                    Console.WriteLine("cli=" + json["result"].ToString());
                }
                else
                {
                    var resultv = json["result"].AsList()[0].AsDict();
                    var txid    = resultv["txid"].AsString();
                    bSucc = txid.Length > 0;
                    Console.WriteLine("txid=" + txid);
                }
                if (bSucc)
                {
                    lasttxid             = tran.GetHash();
                    Nep55_1.lastNep5Tran = tran.GetHash();
                    Console.WriteLine("你可以从这个UTXO拿走NEO了 txid=" + lasttxid.ToString() + "[0]");
                }
                else
                {
                    lasttxid = null;
                }
            }
        }
예제 #28
0
        public static MyJson.JsonNode_Object ToJson(object ScriptObject)
        {
            CLRSharp.CLRSharp_Instance sobj = ScriptObject as CLRSharp.CLRSharp_Instance;
            if (sobj == null) return null;
            MyJson.JsonNode_Object obj = new MyJson.JsonNode_Object();
            var stype = sobj.type;
            //    CSLE.SType stype=sobj.type;
            var ms = stype.GetFieldNames();
            foreach (var m in ms)
            {
                var field = stype.GetField(m);
                if (field.isStatic) continue;
                if ((Type)field.FieldType.TypeForSystem == typeof(int))
                {
                    obj[m] = new MyJson.JsonNode_ValueNumber((int)sobj.Fields[m]);
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(float))
                {
                    obj[m] = new MyJson.JsonNode_ValueNumber((float)sobj.Fields[m]);
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(double))
                {
                    obj[m] = new MyJson.JsonNode_ValueNumber((double)sobj.Fields[m]);
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(string))
                {
                    obj[m] = new MyJson.JsonNode_ValueString((string)sobj.Fields[m]);
                }

        //        else if ((Type)m.Value.type.type == typeof(List<object>))
                else if ((Type)field.FieldType.TypeForSystem == typeof(List<CLRSharp.CLRSharp_Instance>))
                {
                    //处理List
                    List<CLRSharp.CLRSharp_Instance> slist = sobj.Fields[m] as List<CLRSharp.CLRSharp_Instance>;
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;
                    foreach (var item in slist)
                    {
                        list.Add(ToJson(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List<string>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List<string> slist = sobj.Fields[m] as List<string>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueString(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List<int>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List<int> slist = sobj.Fields[m] as List<int>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List<float>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List<float> slist = sobj.Fields[m] as List<float>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List<double>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List<double> slist = sobj.Fields[m] as List<double>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if (field.FieldType is CLRSharp.ICLRType_Sharp)
                //        else if ((CSLE.SType)m.Value.type.type != null)//其他嵌套脚本类型
                {
                    obj[m] = ToJson(sobj.Fields[m]);
                }
                else
                {
                    Logger.Log("发现不能处理的类型:" + stype.Name + ":" + m + ":" + field.FieldType.ToString());
                }
            }
            return obj;
        }
예제 #29
0
        public static MyJson.JsonNode_Object Export(NeoModule module, byte[] script)
        {
            var sha256 = System.Security.Cryptography.SHA256.Create();

            byte[] hash256   = sha256.ComputeHash(script);
            var    ripemd160 = new Neo.Cryptography.RIPEMD160Managed();
            var    hash      = ripemd160.ComputeHash(hash256);

            var outjson = new MyJson.JsonNode_Object();

            //hash
            StringBuilder sb = new StringBuilder();

            sb.Append("0x");
            foreach (var b in hash.Reverse().ToArray())
            {
                sb.Append(b.ToString("x02"));
            }
            outjson.SetDictValue("hash", sb.ToString());

            //entrypoint
            outjson.SetDictValue("entrypoint", "Main");
            var mainmethod = module.mapMethods[module.mainMethod];

            if (mainmethod != null)
            {
                var name = mainmethod.displayName;
                outjson.SetDictValue("entrypoint", name);
            }
            //functions
            var funcsigns = new MyJson.JsonNode_Array();

            outjson["functions"] = funcsigns;

            foreach (var function in module.mapMethods)
            {
                var mm = function.Value;
                if (mm.isPublic == false)
                {
                    continue;
                }
                var ps       = mm.name.Split(new char[] { ' ', '(' }, StringSplitOptions.RemoveEmptyEntries);
                var funcsign = new MyJson.JsonNode_Object();

                funcsigns.Add(funcsign);
                var funcname = ps[1];
                if (funcname.IndexOf("::") > 0)
                {
                    var sps = funcname.Split(new string[] { "::" }, StringSplitOptions.RemoveEmptyEntries);
                    funcname = sps.Last();
                }
                funcsign.SetDictValue("name", function.Value.displayName);
                MyJson.JsonNode_Array funcparams = new MyJson.JsonNode_Array();
                funcsign["parameters"] = funcparams;
                if (mm.paramtypes != null)
                {
                    foreach (var v in mm.paramtypes)
                    {
                        var ptype = ConvType(v.type);
                        var item  = new MyJson.JsonNode_Object();
                        funcparams.Add(item);

                        item.SetDictValue("name", v.name);
                        item.SetDictValue("type", ptype);
                    }
                }

                var rtype = ConvType(mm.returntype);
                funcsign.SetDictValue("returntype", rtype);
            }

            //events
            var eventsigns = new MyJson.JsonNode_Array();

            outjson["events"] = eventsigns;
            foreach (var events in module.mapEvents)
            {
                var mm = events.Value;

                var ps       = mm.name.Split(new char[] { ' ', '(' }, StringSplitOptions.RemoveEmptyEntries);
                var funcsign = new MyJson.JsonNode_Object();

                eventsigns.Add(funcsign);

                funcsign.SetDictValue("name", events.Value.displayName);
                MyJson.JsonNode_Array funcparams = new MyJson.JsonNode_Array();
                funcsign["parameters"] = funcparams;
                if (mm.paramtypes != null)
                {
                    foreach (var v in mm.paramtypes)
                    {
                        var ptype = ConvType(v.type);
                        var item  = new MyJson.JsonNode_Object();
                        funcparams.Add(item);

                        item.SetDictValue("name", v.name);
                        item.SetDictValue("type", ptype);
                    }
                }
                var rtype = ConvType(mm.returntype);
                funcsign.SetDictValue("returntype", rtype);
            }

            return(outjson);
        }
예제 #30
0
 static public void makeRawTransaction(Action <bool, WWW> func_cmd, MyJson.JsonNode_Array paparms)
 {
     sdk_http._instance.makeRawTransaction(func_cmd, paparms);
 }
예제 #31
0
        void Obj2Json(GameObject _obj, MyJson.JsonNode_Object _json)
        {
            _json["name"] = new MyJson.JsonNode_ValueString(_obj.name);
            _json["id"] = new MyJson.JsonNode_ValueNumber(_obj.GetInstanceID());
            //遍历填充组件
            MyJson.JsonNode_Array comps = new MyJson.JsonNode_Array();
            _json["components"] = comps;
            foreach (var c in _obj.GetComponents<Component>())
            {
                if (c == null)
                {
                    Debug.LogWarning("got a commponet null.");
                    continue;
                }
                string type = c.GetType().Name.ToLower();
                var _cjson = new MyJson.JsonNode_Object();
                _cjson["type"] = new MyJson.JsonNode_ValueString(type);
                if (componentParsers.ContainsKey(type) == false)
                {
                    Debug.LogWarning("can't find comparser:" + type);
                    continue;
                }

                componentParsers[type].WriteToJson(resmgr, _obj, c, _cjson);
                comps.Add(_cjson);
            }

            //遍历填充树
            if (_obj.transform.childCount > 0)
            {
                MyJson.JsonNode_Array children = new MyJson.JsonNode_Array();
                _json["children"] = children;

                for (int i = 0; i < _obj.transform.childCount; i++)
                {
                    var subobj = _obj.transform.GetChild(i).gameObject;
                    MyJson.JsonNode_Object _subjson = new MyJson.JsonNode_Object();
                    Obj2Json(subobj, _subjson);
                    children.Add(_subjson);
                }
            }

        }
예제 #32
0
        async Task test_useGas()
        {
            //先sgas的transfer  然后把txid 发给nnc

            //获取地址的资产列表
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Config.api, address);

            if (dir.ContainsKey(Config.id_GAS) == false)
            {
                Console.WriteLine("no gas");
                return;
            }


            //MakeTran
            ThinNeo.Transaction tran = null;
            {
                var who = ThinNeo.Helper.GetAddressFromScriptHash(Config.dapp_nnc);

                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(addr)" + address); //from
                    array.AddArrayValue("(addr)" + who);     //to
                    array.AddArrayValue("(int)200000000");   //value
                    sb.EmitParamJson(array);                 //参数倒序入
                    sb.EmitPushString("transfer");           //参数倒序入
                    sb.EmitAppCall(Config.dapp_sgas);        //nep5脚本

                    //这个方法是为了在同一笔交易中转账并充值
                    //当然你也可以分为两笔交易
                    //插入下述两条语句,能得到txid
                    sb.EmitSysCall("System.ExecutionEngine.GetScriptContainer");
                    sb.EmitSysCall("Neo.Transaction.GetHash");
                    //把TXID包进Array里
                    sb.EmitPushNumber(1);
                    sb.Emit(ThinNeo.VM.OpCode.PACK);
                    sb.EmitPushString("useGas");
                    sb.EmitAppCall(Config.dapp_nnc);

                    script = sb.ToArray();
                }

                tran      = Helper.makeTran(dir[Nep55_1.id_GAS], null, new ThinNeo.Hash256(Nep55_1.id_GAS), 0);
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = script;
                idata.gas    = 0;
            }

            //sign and broadcast
            var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);

            tran.AddWitness(signdata, pubkey, address);
            var trandata    = tran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

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

            Console.WriteLine(result);
        }
예제 #33
0
        public static MyJson.JsonNode_Object ToJson(object ScriptObject)
        {
            CLRSharp.CLRSharp_Instance sobj = ScriptObject as CLRSharp.CLRSharp_Instance;
            if (sobj == null)
            {
                return(null);
            }
            MyJson.JsonNode_Object obj = new MyJson.JsonNode_Object();
            var stype = sobj.type;
            //    CSLE.SType stype=sobj.type;
            var ms = stype.GetFieldNames();

            foreach (var m in ms)
            {
                var field = stype.GetField(m);
                if (field.isStatic)
                {
                    continue;
                }
                if ((Type)field.FieldType.TypeForSystem == typeof(int))
                {
                    obj[m] = new MyJson.JsonNode_ValueNumber((int)sobj.Fields[m]);
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(float))
                {
                    obj[m] = new MyJson.JsonNode_ValueNumber((float)sobj.Fields[m]);
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(double))
                {
                    obj[m] = new MyJson.JsonNode_ValueNumber((double)sobj.Fields[m]);
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(string))
                {
                    obj[m] = new MyJson.JsonNode_ValueString((string)sobj.Fields[m]);
                }

                //        else if ((Type)m.Value.type.type == typeof(List<object>))
                else if ((Type)field.FieldType.TypeForSystem == typeof(List <CLRSharp.CLRSharp_Instance>))
                {
                    //处理List
                    List <CLRSharp.CLRSharp_Instance> slist = sobj.Fields[m] as List <CLRSharp.CLRSharp_Instance>;
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;
                    foreach (var item in slist)
                    {
                        list.Add(ToJson(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List <string>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List <string> slist = sobj.Fields[m] as List <string>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueString(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List <int>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List <int> slist = sobj.Fields[m] as List <int>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List <float>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List <float> slist = sobj.Fields[m] as List <float>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((Type)field.FieldType.TypeForSystem == typeof(List <double>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m] = list;

                    List <double> slist = sobj.Fields[m] as List <double>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if (field.FieldType is CLRSharp.ICLRType_Sharp)
                //        else if ((CSLE.SType)m.Value.type.type != null)//其他嵌套脚本类型
                {
                    obj[m] = ToJson(sobj.Fields[m]);
                }
                else
                {
                    Logger.Log("发现不能处理的类型:" + stype.Name + ":" + m + ":" + field.FieldType.ToString());
                }
            }
            return(obj);
        }
예제 #34
0
        //public const string sc_nnc = "0xbab964febd82c9629cc583596975f51811f25f47";//nnc 合约地址

        //public const string api = "https://api.nel.group/api/testnet";
        //public const string testwif = "L4ZntdDCocMJi4ozpTw4uTtxtAFNNCP2mX6m3P9CMJN66Dt2YJqP";//"L3tDHnEAvwnnPE4sY4oXpTvNtNhsVhbkY4gmEmWmWWf1ebJhVPVW";
        public async Task Demo()
        {
            this.prikey     = ThinNeo.Helper.GetPrivateKeyFromWIF(Config.test_wif);
            this.pubkey     = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            this.address    = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            this.scriptHash = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);

            var roothash = nns_common.nameHash("sell");
            var fullhash = nns_common.nameHashSub(roothash, "helloworld");

            //得到注册器
            var info = await nns_common.api_InvokeScript(Config.sc_nns, "getOwnerInfo", "(hex256)" + roothash.ToString());

            var reg_sc = new Hash160(info.value.subItem[0].subItem[1].data);

            Console.WriteLine("reg=" + reg_sc.ToString());

            Console.WriteLine("address=" + address);

            string addressto = ThinNeo.Helper.GetAddressFromScriptHash(reg_sc);

            Console.WriteLine("addressto=" + addressto);

            //获取地址的资产列表
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Nep55_1.api, address);

            if (dir.ContainsKey(Nep55_1.id_GAS) == false)
            {
                Console.WriteLine("no gas");
                return;
            }

            //MakeTran
            ThinNeo.Transaction tran = null;
            {
                var who = this.scriptHash;

                //得到拍卖ID
                var info3 = await nns_common.api_InvokeScript(reg_sc, "getSellingStateByFullhash", "(hex256)" + fullhash.ToString());

                var id = info3.value.subItem[0].subItem[0].AsHash256();


                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array2 = new MyJson.JsonNode_Array();
                    array2.AddArrayValue("(hex160)" + who.ToString());
                    array2.AddArrayValue("(hex256)" + id.ToString());
                    array2.AddArrayValue("(int)10" + "00000000");
                    sb.EmitParamJson(array2);                    //参数倒序入
                    sb.EmitPushString("addPrice");               //参数倒序入
                    sb.EmitAppCall(new ThinNeo.Hash160(reg_sc)); //nep5脚本


                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(addr)" + address);           //from
                    array.AddArrayValue("(addr)" + addressto);         //to
                    array.AddArrayValue("(int)10" + "00000000");       //value
                    sb.EmitParamJson(array);                           //参数倒序入
                    sb.EmitPushString("transfer");                     //参数倒序入
                    sb.EmitAppCall(new ThinNeo.Hash160(nnc_1.sc_nnc)); //nep5脚本

                    //这个方法是为了在同一笔交易中转账并充值
                    //当然你也可以分为两笔交易
                    //插入下述两条语句,能得到txid
                    sb.EmitSysCall("System.ExecutionEngine.GetScriptContainer");
                    sb.EmitSysCall("Neo.Transaction.GetHash");
                    //把TXID包进Array里
                    sb.EmitPushNumber(1);
                    sb.Emit(ThinNeo.VM.OpCode.PACK);
                    sb.EmitPushString("setmoneyin");
                    sb.EmitAppCall(new ThinNeo.Hash160(reg_sc));

                    script = sb.ToArray();
                }

                tran      = Helper.makeTran(dir[Nep55_1.id_GAS], null, new ThinNeo.Hash256(Nep55_1.id_GAS), 0);
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = script;
                idata.gas    = 0;
            }
            //sign and broadcast
            var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);

            tran.AddWitness(signdata, pubkey, address);
            var trandata    = tran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

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

            Console.WriteLine(result);
        }
예제 #35
0
 static MyJson.IJsonNode UnPackJsonArray(System.IO.Stream stream, byte tagfirst, IList<string> pubdict, IList<string> localdict)
 {
     MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
     int count = ReadCountHead(stream, tagfirst);
     for (int i = 0; i < count; i++)
     {
         array.Add(UnPackJson(stream, pubdict, localdict));
     }
     return array;
 }
예제 #36
0
 public override string ToString()
 {
     MyJson.JsonNode_Object obj = new MyJson.JsonNode_Object();
     foreach(var list in needList)
     {
         MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
         obj[list.Key] = array;
         foreach(var item in list.Value)
         {
             array.Add(new MyJson.JsonNode_ValueString(item));
         }
     }
     return obj.ToString();
 }
예제 #37
0
        async Task test_mintTokens()
        {
            decimal amount = 0;

            while (true)
            {
                subPrintLine("Input amount:");
                string str_amount = Console.ReadLine();
                try
                {
                    amount = decimal.Parse(str_amount);
                    break;
                }
                catch (Exception e)
                {
                    subPrintLine("input number");
                }
            }

            //获取地址的资产列表
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Config.api, address);

            if (dir.ContainsKey(Config.id_GAS) == false)
            {
                subPrintLine("no gas");
                return;
            }
            Transaction tran = null;
            {
                byte[] script = null;
                using (var sb = new ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    sb.EmitParamJson(array);                                              //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)mintTokens")); //参数倒序入
                    Hash160 shash = Config.dapp_sgas;
                    sb.EmitAppCall(shash);                                                //nep5脚本
                    script = sb.ToArray();
                }
                var sgasScripthash = Config.dapp_sgas;
                var targetaddr     = ThinNeo.Helper.GetAddressFromScriptHash(sgasScripthash);
                subPrintLine("contract address=" + targetaddr);//往合约地址转账

                //生成交易
                tran      = Helper.makeTran(dir[Config.id_GAS], targetaddr, new Hash256(Config.id_GAS), amount, (decimal)0.00000000);
                tran.type = TransactionType.InvocationTransaction;
                var idata = new InvokeTransData();
                tran.extdata = idata;
                idata.script = script;
                idata.gas    = (decimal)0.00000000;
                //sign and broadcast
                var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);
                tran.AddWitness(signdata, pubkey, address);
                var    trandata    = tran.GetRawData();
                var    strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);
                byte[] postdata;

                var url    = Helper.MakeRpcUrlPost(Config.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
                var result = await Helper.HttpPost(url, postdata);

                subPrintLine("得到的结果是:" + result);
                var json = MyJson.Parse(result).AsDict();
                if (json.ContainsKey("result"))
                {
                    var resultv = json["result"].AsList()[0].AsDict();
                    var txid    = resultv["txid"].AsString();
                    subPrintLine("txid=" + txid);
                }
            }
        }
예제 #38
0
        public static async Task <string> api_SendbatchTransaction(byte[] prikey, Hash160 schash, string methodname, params string[] subparam)
        {
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            byte[] data = null;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
                byte[] randombytes          = new byte[32];
                using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(randombytes);
                }
                BigInteger randomNum = new BigInteger(randombytes);
                sb.EmitPushNumber(randomNum);
                sb.Emit(ThinNeo.VM.OpCode.DROP);

                if (subparam != null && subparam.Length > 0)
                {
                    for (var i = 0; i < subparam.Length; i++)
                    {
                        array.AddArrayValue(subparam[i]);
                    }
                }
                sb.EmitParamJson(array);
                sb.EmitPushString(methodname);
                sb.EmitAppCall(schash);
                data = sb.ToArray();
            }
            //MakeTran
            ThinNeo.Transaction tran = new ThinNeo.Transaction();
            tran.version = 0;//0 or 1
            tran.inputs  = new ThinNeo.TransactionInput[0];
            tran.outputs = new ThinNeo.TransactionOutput[0];
            tran.type    = ThinNeo.TransactionType.InvocationTransaction;
            tran.extdata = new ThinNeo.InvokeTransData();
            var idata = new ThinNeo.InvokeTransData();

            tran.extdata = idata;
            idata.script = data;
            idata.gas    = 0;

            tran.attributes          = new ThinNeo.Attribute[1];
            tran.attributes[0]       = new ThinNeo.Attribute();
            tran.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script;
            tran.attributes[0].data  = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);

            //sign and broadcast
            var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);

            tran.AddWitness(signdata, pubkey, address);
            var trandata    = tran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

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

            return(result);
        }
예제 #39
0
        async Task test_refund()
        {
            decimal amount = 0;

            while (true)
            {
                subPrintLine("Input amount:");
                string str_amount = Console.ReadLine();
                try
                {
                    amount = decimal.Parse(str_amount);
                    break;
                }
                catch (Exception e)
                {
                    subPrintLine("input number");
                }
            }

            string sgas_address = ThinNeo.Helper.GetAddressFromScriptHash(Config.dapp_sgas);

            //获取sgas合约地址的资产列表
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Config.api, sgas_address);

            if (dir.ContainsKey(Config.id_GAS) == false)
            {
                subPrintLine("no gas");
                return;
            }
            List <Utxo> newlist = new List <Utxo>(dir[Config.id_GAS]);

            //检查sgas地址拥有的gas的utxo是否有被标记过
            for (var i = newlist.Count - 1; i >= 0; i--)
            {
                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(hex256)" + newlist[i].txid.ToString());
                    sb.EmitParamJson(array);                                                   //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)getRefundTarget")); //参数倒序入
                    var shash = Config.dapp_sgas;
                    sb.EmitAppCall(shash);                                                     //nep5脚本
                    script = sb.ToArray();
                }
                if (newlist[i].n > 0)
                {
                    continue;
                }

                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  = stack["value"].AsString();
                if (value.Length > 0)//已经标记的UTXO,不能使用
                {
                    newlist.RemoveAt(i);
                }
            }


            //添加系统费
            Dictionary <string, List <Utxo> > dir2 = await Helper.GetBalanceByAddress(Config.api, address);

            List <Utxo> newlist2 = new List <Utxo>(dir2[Config.id_GAS]);

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

                //sgas 自己给自己转账   用来生成一个utxo  合约会把这个utxo标记给发起的地址使用
                tran      = Helper.makeTran(newlist, sgas_address, new ThinNeo.Hash256(Config.id_GAS), (decimal)0.00000001, (decimal)0.00000001, newlist2, address);
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = script;

                //附加鉴证
                tran.attributes          = new ThinNeo.Attribute[1];
                tran.attributes[0]       = new ThinNeo.Attribute();
                tran.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script;
                tran.attributes[0].data  = scriptHash;
            }

            //sign and broadcast
            {//做智能合约的签名
                byte[] sgasScript = null;
                {
                    var urlgetscript    = Helper.MakeRpcUrl(Config.api, "getcontractstate", new MyJson.JsonNode_ValueString(Config.dapp_sgas.ToString()));
                    var resultgetscript = await Helper.HttpGet(urlgetscript);

                    var _json    = MyJson.Parse(resultgetscript).AsDict();
                    var _resultv = _json["result"].AsList()[0].AsDict();
                    sgasScript = ThinNeo.Helper.HexString2Bytes(_resultv["script"].AsString());
                }
                byte[] iscript = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    sb.EmitPushString("whatever");
                    sb.EmitPushNumber(250);
                    iscript = sb.ToArray();
                }
                tran.AddWitnessScript(sgasScript, iscript);
            }
            {//做提款人的签名
                var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);
                tran.AddWitness(signdata, pubkey, address);
            }
            var trandata    = tran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

            byte[] postdata;
            var    url = Helper.MakeRpcUrlPost(Config.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));

            var result = await Helper.HttpPost(url, postdata);

            subPrintLine("得到的结果是:" + result);
            var json = MyJson.Parse(result).AsDict();

            if (json.ContainsKey("result"))
            {
                bool bSucc = false;
                if (json["result"].type == MyJson.jsontype.Value_Number)
                {
                    bSucc = json["result"].AsBool();
                    subPrintLine("cli=" + json["result"].ToString());
                }
                else
                {
                    var resultv = json["result"].AsList()[0].AsDict();
                    var txid    = resultv["txid"].AsString();
                    bSucc = txid.Length > 0;
                }
                if (bSucc)
                {
                    Hash256 txid = tran.GetHash();
                    url = Helper.MakeRpcUrlPost(Config.api, "getrawtransaction", out postdata, new MyJson.JsonNode_ValueString(txid.ToString()));
                    while (true)
                    {
                        subPrintLine("正在等待交易验证,请稍后。。。。");
                        result = await Helper.HttpPost(url, postdata);

                        json = MyJson.Parse(result).AsDict();
                        if (json.ContainsKey("result"))
                        {
                            //tx的第一个utxo就是给自己的
                            Utxo utxo = new Utxo(address, txid, Config.id_GAS, amount, 0);
                            //把这个txid里的utxo[0]的value转给自己
                            TranGas(new List <Utxo>()
                            {
                                utxo
                            }, amount);
                            break;
                        }
                        await Task.Delay(5000);
                    }
                }
                else
                {
                }
            }
        }
예제 #40
0
    void SaveItem()
    {
        //GameObject setobj = null;//选中的对象
        //bool bUseHashName = true;//是否使用hash作为资源文件名
        //string exportResult = null;//导出结果
        //string exportPath = null;//导出路径
        //bool bUseHashTreeName = false;//是否使用hash作为导出节点名
        //string exportNodeName = "";//导出节点名称

        nodeParser.nodeParser np = new nodeParser.nodeParser();
        np.SaveNode(this.setobj);//先强制使用HashName

        if (System.IO.Directory.Exists(exportPath) == false)
            System.IO.Directory.CreateDirectory(exportPath);
        string respath = System.IO.Path.Combine(exportPath, "resources");
        if (System.IO.Directory.Exists(respath) == false)
            System.IO.Directory.CreateDirectory(respath);

        MyJson.JsonNode_Array indexfile = new MyJson.JsonNode_Array();
        foreach (var f in np.bufs)
        {
            //写入文件
            {
                var file = System.IO.Path.Combine(respath, f.Key);
                System.IO.File.WriteAllBytes(file, f.Value);
            }
            //记录索引
            MyJson.JsonNode_Object indexitem = new MyJson.JsonNode_Object();
            indexitem["Name"] = new MyJson.JsonNode_ValueString("resources/" + f.Key);
            indexitem["Length"] = new MyJson.JsonNode_ValueNumber(f.Value.Length);
            indexfile.Add(indexitem);
        }
        indexfile.Sort((a, b) =>
        {
            return string.Compare(a.asDict()["Name"].AsString(), b.asDict()["Name"].AsString());
        });
        {//保存索引文件
            byte[] indexcode = System.Text.Encoding.UTF8.GetBytes(indexfile.ToString());

            exportResult = exportNodeName;
            if (bUseHashTreeName)
            {
                exportResult = ResLibTool.ComputeHashString(indexcode);
            }
            string outfile = System.IO.Path.Combine(exportPath, exportResult + ".indexlist.txt");

            System.IO.File.WriteAllBytes(outfile, indexcode);
        }

    }
예제 #41
0
        public static MyJson.JsonNode_Object ToJson(object ScriptObject)
        {
            CSLE.SInstance sobj = ScriptObject as CSLE.SInstance;
            if (sobj == null) return null;
            MyJson.JsonNode_Object obj = new MyJson.JsonNode_Object();
            CSLE.SType stype=sobj.type;
            foreach (var m in stype.members)
            {
                if ((Type)m.Value.type.type == typeof(int))
                {
                    obj[m.Key] = new MyJson.JsonNode_ValueNumber((int)sobj.member[m.Key].value);
                }
                else if ((Type)m.Value.type.type == typeof(float))
                {
                    obj[m.Key] = new MyJson.JsonNode_ValueNumber((float)sobj.member[m.Key].value);
                }
                else if ((Type)m.Value.type.type == typeof(double))
                {
                    obj[m.Key] = new MyJson.JsonNode_ValueNumber((double)sobj.member[m.Key].value);
                }
                else if ((Type)m.Value.type.type == typeof(string))
                {
                    obj[m.Key] = new MyJson.JsonNode_ValueString((string)sobj.member[m.Key].value);
                }
                else if ((Type)m.Value.type.type == typeof(List<object>))
                {
                    //处理List
                    List<object> slist = sobj.member[m.Key].value as List<object>;
                    var list = new MyJson.JsonNode_Array();
                    obj[m.Key] = list;
                    foreach(var item in slist)
                    {
                        list.Add(ToJson(item));
                    }
                }
                else if ((Type)m.Value.type.type == typeof(List<string>))
                {
                    var list =new MyJson.JsonNode_Array();
                    obj[m.Key] = list;

                    List<string> slist = sobj.member[m.Key].value as List<string>;
                  
                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueString(item));
                    }
                }
                else if ((Type)m.Value.type.type == typeof(List<int>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m.Key] = list;

                    List<int> slist = sobj.member[m.Key].value as List<int>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((Type)m.Value.type.type == typeof(List<float>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m.Key] = list;

                    List<float> slist = sobj.member[m.Key].value as List<float>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((Type)m.Value.type.type == typeof(List<double>))
                {
                    var list = new MyJson.JsonNode_Array();
                    obj[m.Key] = list;

                    List<double> slist = sobj.member[m.Key].value as List<double>;

                    foreach (var item in slist)
                    {
                        list.Add(new MyJson.JsonNode_ValueNumber(item));
                    }
                }
                else if ((CSLE.SType)m.Value.type.type != null)//其他嵌套脚本类型
                {
                    obj[m.Key] = ToJson(sobj.member[m.Key].value);
                }
                else
                {
                    Debug.Log("发现不能处理的类型:" + stype.Name + ":" + m.Key + ":" + m.Value.type.ToString());
                }
            }
            return obj;
        }