Ejemplo n.º 1
0
    IEnumerator HTTP_nel_post_tan(byte[] script, MyJson.JsonNode_Array pararms, Action <bool, WWW> call_back)
    {
        WWWForm www_getuxo_form = Helper.GetWWWFormPost("getutxo", new MyJson.JsonNode_ValueString(roleInfo.getInstance().address));
        WWW     www             = new WWW(global.api, www_getuxo_form);

        yield return(www);

        Dictionary <string, List <Utxo> > _dir = get_utxo(www.text);

        if (_dir.ContainsKey(global.id_GAS) == false)
        {
            Debug.Log("no gas");
            yield return(null);
        }

        ThinNeo.Transaction tran = null;
        {
            tran      = Helper.makeTran(_dir[global.id_GAS], roleInfo.getInstance().address, new ThinNeo.Hash256(global.id_GAS), 0);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;
            var idata = new ThinNeo.InvokeTransData();
            tran.extdata = idata;
            idata.script = script;
        }

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

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

        WWWForm www_form_sendraw = Helper.GetWWWFormPost("sendrawtransaction", new MyJson.JsonNode_ValueString(strtrandata));
        WWW     sendraw          = new WWW(global.api, www_form_sendraw);

        yield return(sendraw);

        var json = MyJson.Parse(sendraw.text).AsDict();

        if (json.ContainsKey("result"))
        {
            var resultv = json["result"].AsList()[0].AsDict();
            var txid    = resultv["txid"].AsString();
            if (txid.Length > 0)
            {
                //Nep55_1.lastNep5Tran = tran.GetHash();
            }
            Debug.Log("txid=" + txid);

            api_tool._instance.addUserWalletLogs(roleInfo.getInstance().uid, roleInfo.getInstance().token, txid,
                                                 global.game_id.ToString(), "", "5", pararms.ToString(), global.netType, "0",
                                                 (bool timeout1, WWW www1) => { testtool.panel_main.on_refresh_WalletListss(); });
        }
        else
        {
            Debug.Log("交易失败");
            //testtool.showNotice("交易失败");
        }
    }
Ejemplo n.º 2
0
        private static object SendTransaction(byte[] prikey, byte[] script)
        {
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

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

            if (dir.ContainsKey(id_GAS) == false)
            {
                Console.WriteLine("no gas");
                return(null);
            }
            //MakeTran
            ThinNeo.Transaction tran = null;
            {
                byte[] data = script;
                tran      = Helper.makeTran(dir[id_GAS], null, new ThinNeo.Hash256(id_GAS), 0);
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = data;
                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(api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
            var    result = Helper.HttpPost(url, postdata);

            return(result);
        }
Ejemplo n.º 3
0
        private static void SendTransWithoutUtxo(byte[] prikey, byte[] pubkey, string address, byte[] script)
        {
            ThinNeo.Transaction tran = new Transaction();
            tran.inputs              = new ThinNeo.TransactionInput[0];
            tran.outputs             = new TransactionOutput[0];
            tran.attributes          = new ThinNeo.Attribute[1];
            tran.attributes[0]       = new ThinNeo.Attribute();
            tran.attributes[0].usage = TransactionAttributeUsage.Script;
            tran.attributes[0].data  = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);
            tran.version             = 1;
            tran.type = ThinNeo.TransactionType.InvocationTransaction;

            var idata = new ThinNeo.InvokeTransData();

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

            byte[] msg    = tran.GetMessage();
            string msgstr = ThinNeo.Helper.Bytes2HexString(msg);

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

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

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

            Console.WriteLine(txid);
            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
            Console.WriteLine(resJO.ToString());
        }
Ejemplo n.º 4
0
        public async Task publishContract()
        {
            string wif = "L1PSC3LRShi51xHAX2KN9oCFqETrZQhnzhKVu5zbrzdDpxF1LQz3";

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

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

            byte[] script = System.IO.File.ReadAllBytes("0xccd651a5e7d9f4dc698353970df7b7180139cbbe.avm");
            Console.WriteLine("合约脚本:" + ThinNeo.Helper.Bytes2HexString(script));
            Console.WriteLine("合约脚本Hash:" + ThinNeo.Helper.Bytes2HexString(ThinNeo.Helper.GetScriptHashFromScript(script).data.ToArray().Reverse().ToArray()));
            byte[] parameter__list = ThinNeo.Helper.HexString2Bytes("0710");
            byte[] return_type     = ThinNeo.Helper.HexString2Bytes("05");
            int    need_storage    = 1;
            int    need_nep4       = 0;
            int    need_canCharge  = 4;
            string name            = "mygas";
            string version         = "1.0";
            string auther          = "LZ";
            string email           = "0";
            string description     = "0";

            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder()) {
                var ss = need_storage | need_nep4 | need_canCharge;
                sb.EmitPushString(description);
                sb.EmitPushString(email);
                sb.EmitPushString(auther);
                sb.EmitPushString(version);
                sb.EmitPushString(name);
                sb.EmitPushNumber(ss);
                sb.EmitPushBytes(return_type);
                sb.EmitPushBytes(parameter__list);
                sb.EmitPushBytes(script);
                sb.EmitSysCall("Neo.Contract.Create");

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

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

                //return;

                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.script = sb.ToArray();

                extdata.gas = Math.Ceiling(gas_consumed - 10);

                ThinNeo.Transaction tran = makeTran(dir, null, new ThinNeo.Hash256(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, prikey);
                tran.AddWitness(signdata, pubkey, address);
                string txid    = tran.GetHash().ToString();
                byte[] data    = tran.GetRawData();
                string rawdata = ThinNeo.Helper.Bytes2HexString(data);

                url    = Helper.MakeRpcUrlPost(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());
            }
        }
Ejemplo n.º 5
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
                {
                }
            }
        }
Ejemplo n.º 6
0
        //升级合约
        async Task test_setUpgrade()
        {
            byte[] prikey_admin = ThinNeo.Helper.GetPrivateKeyFromWIF(Config.testwif_admin);
            byte[] pubkey_admin = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey_admin);
            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\\0xe7bce3dde514813762b44a11bb5767f343dafb22.avm"); //这里填你的合约所在地址
            string str_script = ThinNeo.Helper.Bytes2HexString(script);

            byte[] aa = ThinNeo.Helper.HexString2Bytes(str_script);
            var    ss = 1 | 0 | 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 = oracle_common.sc_wneo;
                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    = 510;// 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, prikey_admin);
                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());
            }
        }
Ejemplo n.º 7
0
        private static void PubScDemo(string wif)
        {
            string assetid = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7";
            string api     = "https://api.nel.group/api/testnet";

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

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

            //从文件中读取合约脚本
            byte[] script = System.IO.File.ReadAllBytes("dapp_nnc4.0.avm"); //这里填你的合约所在地址
            Console.WriteLine("合约脚本:" + ThinNeo.Helper.Bytes2HexString(script));
            Console.WriteLine("合约脚本hash:" + ThinNeo.Helper.Bytes2HexString(ThinNeo.Helper.GetScriptHashFromScript(script).data.ToArray().Reverse().ToArray()));
            byte[] parameter__list = ThinNeo.Helper.HexString2Bytes("0710"); //这里填合约入参  例:0610代表(string,[])
            byte[] return_type     = ThinNeo.Helper.HexString2Bytes("05");   //这里填合约的出参
            int    need_storage    = 1;
            int    need_nep4       = 2;
            int    need_canCharge  = 4;
            string name            = "XC";
            string version         = "1.0";
            string auther          = "Zhang";
            string email           = "0";
            string description     = "0";

            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                var ss = need_storage;
                //倒叙插入数据
                sb.EmitPushString(description);
                sb.EmitPushString(email);
                sb.EmitPushString(auther);
                sb.EmitPushString(version);
                sb.EmitPushString(name);
                sb.EmitPushNumber(need_storage | need_nep4 | need_canCharge);
                sb.EmitPushBytes(return_type);
                sb.EmitPushBytes(parameter__list);
                sb.EmitPushBytes(script);
                sb.EmitSysCall("Neo.Contract.Create");

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

                byte[] postdata;
                var    url    = MakeRpcUrlPost(api, "invokescript", out postdata, new MyJson.JsonNode_ValueString(scriptPublish));
                var    result = 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.script = sb.ToArray();

                //Console.WriteLine(ThinNeo.Helper.Bytes2HexString(extdata.script));
                extdata.gas = Math.Ceiling(gas_consumed - 10);

                //拼装交易体
                ThinNeo.Transaction tran = MakeTran(dir, null, new ThinNeo.Hash256(assetid), extdata.gas);
                tran.version = 1;
                tran.extdata = extdata;
                tran.type    = ThinNeo.TransactionType.InvocationTransaction;
                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);

                //Console.WriteLine("scripthash:"+scripthash);

                url    = MakeRpcUrlPost(api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
                result = HttpPost(url, postdata);

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



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

            //Dictionary<string, List<UTXO>> dic_UTXO = new Dictionary<string, List<UTXO>>();

            ////读取合约avm文件
            //byte[] script = System.IO.File.ReadAllBytes("NeoContracts.avm");
            //Console.WriteLine("合约脚本:" + ThinNeo.Helper.Bytes2HexString(script));
            //Console.WriteLine("合约脚本哈希:" + ThinNeo.Helper.Bytes2HexString(ThinNeo.Helper.GetScriptHashFromScript(script)
            //                      .data.ToArray().Reverse().ToArray()));
            //byte[] parameter__list = ThinNeo.Helper.HexString2Bytes("0710");//合约入参
            //byte[] return_type = ThinNeo.Helper.HexString2Bytes("05");//合约出参
            //int need_storage = 1;
            ////int need_nep4 = 0;
            ////int need_canCharge = 4;
            //string name = "sgas";
            //string version = "1.0";
            //string auther = "NEL";
            //string email = "0";
            //string description = "0";
            //using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            //{
            //    var ss = need_storage    ;

            //    sb.EmitPushString(description);
            //    sb.EmitPushString(email);
            //    sb.EmitPushString(auther);
            //    sb.EmitPushString(version);
            //    sb.EmitPushString(name);
            //    sb.EmitPushNumber(need_storage    );
            //    sb.EmitPushBytes(return_type);
            //    sb.EmitPushBytes(parameter__list);
            //    sb.EmitPushBytes(script);
            //    sb.EmitSysCall("Neo.Contract.Create");

            //    string scriptPublish = ThinNeo.Helper.Bytes2HexString(sb.ToArray());

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

            //    var consume =
            //        (((MyJson.Parse(result) as MyJson.JsonNode_Object)["result"] as MyJson.JsonNode_Array)[0] as
            //            MyJson.JsonNode_Object)["gas_consumed"].ToString();
            //    decimal gas_consume = decimal.Parse(consume);
            //    ThinNeo.InvokeTransData extdata = new InvokeTransData();
            //    extdata.script = sb.ToArray();
            //    extdata.gas = Math.Ceiling(gas_consume - 10);

            //    ThinNeo.Transaction tran = MakeTran(dic_UTXO, null, new ThinNeo.Hash256(assetid), extdata.gas);

            //    tran.version = 1;
            //    tran.extdata = extdata;
            //    tran.type = ThinNeo.TransactionType.InvocationTransaction;
            //    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);

            //    url = Helper.MakeRpcUrlPost(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());
            //}
        }
Ejemplo n.º 8
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());
            }
        }
Ejemplo n.º 9
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);
        }
Ejemplo n.º 10
0
    IEnumerator HTTP_nel_post_sgas_gas(decimal num)
    {
        var    nep55_shash   = new ThinNeo.Hash160(global.id_sgas);
        string nep55_address = ThinNeo.Helper.GetAddressFromScriptHash(nep55_shash);

        WWWForm www_getuxo_form = Helper.GetWWWFormPost("getutxo", new MyJson.JsonNode_ValueString(nep55_address));
        WWW     www             = new WWW(global.api, www_getuxo_form);

        yield return(www);

        Dictionary <string, List <Utxo> > _dir = get_utxo(www.text);

        if (_dir.ContainsKey(global.id_GAS) == false)
        {
            Debug.Log("no gas");
        }

        List <Utxo> newlist = new List <Utxo>(_dir[global.id_GAS]);

        for (var i = newlist.Count - 1; i >= 0; i--)
        {
            Debug.Log(newlist[i].txid.ToString());

            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 = new ThinNeo.Hash160(global.id_sgas);
                sb.EmitAppCall(shash);                                                     //nep5脚本
                script = sb.ToArray();
            }
            if (newlist[i].n > 0)
            {
                continue;
            }

            WWWForm www_getTarget_form = Helper.GetWWWFormPost("invokescript", new MyJson.JsonNode_ValueString(ThinNeo.Helper.Bytes2HexString(script)));
            WWW     www_form           = new WWW(global.api, www_getTarget_form);

            yield return(www_form);

            var jsonCU = MyJson.Parse(www_form.text);
            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);
            }
        }

        string paparms;

        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(roleInfo.getInstance().scripthash));
                sb.EmitParamJson(array);                                          //参数倒序入
                sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)refund")); //参数倒序入
                var shash = new ThinNeo.Hash160(global.id_sgas);
                sb.EmitAppCall(shash);                                            //nep5脚本
                script = sb.ToArray();


                //拼接发给后台做验证的json字符串
                MyJson.JsonNode_Object account = new MyJson.JsonNode_Object();
                account["sbParamJson"]  = array;
                account["sbPushString"] = new MyJson.JsonNode_ValueString("refund");
                account["nnc"]          = new MyJson.JsonNode_ValueString(global.id_sgas);
                account["cnts"]         = new MyJson.JsonNode_ValueString(num.ToString());
                paparms = account.ToString();
            }

            //生成交易
            tran      = Helper.makeTran(newlist, nep55_address, new ThinNeo.Hash256(global.id_GAS), num);
            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  = roleInfo.getInstance().scripthash;
        }

        //sign and broadcast
        {//做智能合约的签名
            byte[] n55contract = null;
            {
                WWWForm www_getState = Helper.GetWWWFormPost("getcontractstate", new MyJson.JsonNode_ValueString(global.id_sgas));
                WWW     www_state    = new WWW(global.api, www_getState);

                yield return(www_state);

                var _json    = MyJson.Parse(www_state.text).AsDict();
                var _resultv = _json["result"].AsList()[0].AsDict();
                n55contract = 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(n55contract, iscript);
        }
        {//做提款人的签名
            var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), roleInfo.getInstance().prikey);
            tran.AddWitness(signdata, roleInfo.getInstance().pubkey, roleInfo.getInstance().address);
        }
        var trandata    = tran.GetRawData();
        var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

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

        WWWForm www_transaction = Helper.GetWWWFormPost("sendrawtransaction", new MyJson.JsonNode_ValueString(strtrandata));
        WWW     www_tran        = new WWW(global.api, www_transaction);

        yield return(www_tran);


        Debug.Log(www_tran.text);

        var json = MyJson.Parse(www_tran.text).AsDict();

        ThinNeo.Hash256 lasttxid = null;
        if (json.ContainsKey("result"))
        {
            bool bSucc = false;
            if (json["result"].type == MyJson.jsontype.Value_Number)
            {
                bSucc = json["result"].AsBool();
                Debug.Log("cli=" + json["result"].ToString());
            }
            else
            {
                var resultv = json["result"].AsList()[0].AsDict();
                var txid    = resultv["txid"].AsString();
                bSucc = txid.Length > 0;
            }
            if (bSucc)
            {
                lasttxid = tran.GetHash();
                Debug.Log("你可以从这个UTXO拿走GAS了 txid=" + lasttxid.ToString() + "[0]");

                api_tool._instance.addUserWalletLogs(roleInfo.getInstance().uid, roleInfo.getInstance().token, lasttxid.ToString(),
                                                     "0", num.ToString(), "2", paparms, global.netType, "0",
                                                     (bool timeout1, WWW www1) => { testtool.panel_main.on_refresh_WalletListss(); testtool.panel_main.on_refresh_plat_NotifyList(); });
            }
            else
            {
                lasttxid = null;
            }
        }
    }
Ejemplo n.º 11
0
    IEnumerator HTTP_nel_post_gas_sgas(decimal num)
    {
        WWWForm www_getuxo_form = Helper.GetWWWFormPost("getutxo", new MyJson.JsonNode_ValueString(roleInfo.getInstance().address));
        WWW     www             = new WWW(global.api, www_getuxo_form);

        yield return(www);

        Dictionary <string, List <Utxo> > _dir = get_utxo(www.text);

        if (_dir.ContainsKey(global.id_GAS) == false)
        {
            Debug.Log("no gas");
        }

        string paparms;

        ThinNeo.Transaction tran = null;
        {
            byte[] script = null;
            using (var sb = new ThinNeo.ScriptBuilder())
            {
                var array = new MyJson.JsonNode_Array();
                sb.EmitParamJson(array);                                              //参数倒序入
                sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)mintTokens")); //参数倒序入
                ThinNeo.Hash160 shash = new ThinNeo.Hash160(global.id_sgas);
                sb.EmitAppCall(shash);                                                //nep5脚本
                script = sb.ToArray();

                //拼接发给后台做验证的json字符串
                MyJson.JsonNode_Object account = new MyJson.JsonNode_Object();
                account["sbParamJson"]  = array;
                account["sbPushString"] = new MyJson.JsonNode_ValueString("mintTokens");
                account["nnc"]          = new MyJson.JsonNode_ValueString(global.id_sgas);
                account["cnts"]         = new MyJson.JsonNode_ValueString(num.ToString());
                paparms = account.ToString();
                Debug.Log(paparms);
            }
            var nep5scripthash = new ThinNeo.Hash160(global.id_sgas);
            var targetaddr     = ThinNeo.Helper.GetAddressFromScriptHash(nep5scripthash);
            Debug.Log("contract address=" + targetaddr);//往合约地址转账



            //生成交易
            tran      = Helper.makeTran(_dir[global.id_GAS], targetaddr, new ThinNeo.Hash256(global.id_GAS), num);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;
            var idata = new ThinNeo.InvokeTransData();
            tran.extdata = idata;
            idata.script = script;
        }

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

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

        WWWForm www_form_sendraw = Helper.GetWWWFormPost("sendrawtransaction", new MyJson.JsonNode_ValueString(strtrandata));
        WWW     sendraw          = new WWW(global.api, www_form_sendraw);

        yield return(sendraw);

        var json = MyJson.Parse(sendraw.text).AsDict();

        if (json.ContainsKey("result"))
        {
            var resultv = json["result"].AsList()[0].AsDict();
            var txid    = resultv["txid"].AsString();
            if (txid.Length > 0)
            {
                Debug.Log("txid=" + txid);

                api_tool._instance.addUserWalletLogs(roleInfo.getInstance().uid, roleInfo.getInstance().token, txid,
                                                     "0", num.ToString(), "1", paparms, global.netType, "0",
                                                     (bool timeout1, WWW www1) => { testtool.panel_main.on_refresh_WalletListss(); });
            }
            else
            {
                Debug.Log("交易失败");
            }
        }
        else
        {
            Debug.Log("交易失败");
        }
    }
Ejemplo n.º 12
0
        private void SendReturn(string txid, ReturnInfo ret)
        {
            //L2CmHCqgeNHL1i9XFhTLzUXsdr5LGjag4d56YY98FqEi4j5d83Mv
            var prikey     = ThinNeo.Helper.GetPrivateKeyFromWIF("L1WHHa4zmudqzRTYQiF4wbw9duiqEvcz7QY93GG1rzvCVxFVSDud");
            var pubkey     = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            var scripthash = ThinNeo.Helper.GetScriptHashFromPublicKey(pubkey);
            var addres     = ThinNeo.Helper.GetAddressFromScriptHash(scripthash);

            ThinNeo.Transaction tx = new ThinNeo.Transaction();
            tx.inputs  = new ThinNeo.TransactionInput[0];
            tx.outputs = new ThinNeo.TransactionOutput[0];
            tx.type    = ThinNeo.TransactionType.InvocationTransaction;
            tx.version = 1;
            //附加一个见证人  ///要他签名
            tx.attributes          = new ThinNeo.Attribute[1];
            tx.attributes[0]       = new ThinNeo.Attribute();
            tx.attributes[0].usage = ThinNeo.TransactionAttributeUsage.Script;
            tx.attributes[0].data  = scripthash;

            //拼接调用脚本
            var invokedata = new ThinNeo.InvokeTransData();

            tx.extdata     = invokedata;
            invokedata.gas = 0;
            var sb = new ThinNeo.ScriptBuilder();

            MyJson.JsonNode_Array array = new MyJson.JsonNode_Array();
            array.AddArrayValue("(hex256)" + txid);         //txid
            array.AddArrayValue("(int)" + ret.returnvalue); //returnvalue
            var _params = new MyJson.JsonNode_Array();

            array.Add(_params);//params
            Random r = new Random();

            _params.AddArrayValue("(int)" + r.Next());

            sb.EmitParamJson(array);
            sb.EmitPushString("returnvalue");
            ThinNeo.Hash160 contractaddr = new ThinNeo.Hash160("0x24192c2a72e0ce8d069232f345aea4db032faf72");
            sb.EmitAppCall(contractaddr);
            invokedata.script = sb.ToArray();

            //签名 (谁来签名)
            var msg  = tx.GetMessage();
            var data = ThinNeo.Helper.Sign(msg, prikey);

            tx.AddWitness(data, pubkey, addres);

            System.Net.WebClient wc = new System.Net.WebClient();

            wc.Headers["content-type"] = "text/plain;charset=UTF-8";
            Newtonsoft.Json.Linq.JObject upparam = new Newtonsoft.Json.Linq.JObject();
            upparam["jsonrpc"] = "2.0";
            upparam["id"]      = 1;
            upparam["method"]  = "sendrawtransaction";
            var _vparams = new Newtonsoft.Json.Linq.JArray();

            var vdata = tx.GetRawData();

            _vparams.Add(ThinNeo.Helper.Bytes2HexString(vdata));
            upparam["params"] = _vparams;

            var strdata = upparam.ToString(Formatting.None);
            var info    = wc.UploadString(url, strdata);
            //Console.WriteLine(info);
            var this_txid = tx.GetHash();

            ret.txid = this_txid.ToString();
            ret.rsp  = info;
            this.list2.Items.Add(ret);
        }
Ejemplo n.º 13
0
        public static void RefundLoop()
        {
            var JAData = mongoHelper.GetData(Program.conn, Program.db, Program.coll, "{register:\"0xfe041f87b1a4cc0efb827664d6f20a0e990d0969\"}");

            for (var i = 0; i < JAData.Count; i++)
            {
                MyJson.JsonNode_Object json = JAData[i].AsDict();
                var        str_balance      = json["balance"].AsDict()["$numberDecimal"].AsString();
                BigInteger balance          = (BigInteger)(decimal.Parse(str_balance, System.Globalization.NumberStyles.Float) * 100000000);
                string     address          = json["address"].AsString();

                if (balance <= 0)
                {
                    continue;
                }
                byte[] data = null;
                //MakeTran
                ThinNeo.Transaction tran = new Transaction();
                {
                    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.OpCode.DROP);
                        array.AddArrayValue("(addr)" + address); //from
                        array.AddArrayValue("(int)" + balance);  //value

                        sb.EmitParamJson(array);
                        sb.EmitPushString("getmoneyback");
                        sb.EmitAppCall(new Hash160("0xfe041f87b1a4cc0efb827664d6f20a0e990d0969"));
                        data = sb.ToArray();
                    }
                    //sign and broadcast
                    var wif          = "KwZih114osBp58RwpEn4ZAcEcCTLP6yMAhdikb6oPRxqgvWpcqF1";
                    var prikey       = ThinNeo.Helper.GetPrivateKeyFromWIF(wif);
                    var pubkey       = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
                    var scriptHash   = ThinNeo.Helper.GetScriptHashFromPublicKey(pubkey);
                    var addressAdmin = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

                    tran.type = ThinNeo.TransactionType.InvocationTransaction;
                    var idata = new ThinNeo.InvokeTransData();
                    tran.extdata             = idata;
                    idata.script             = data;
                    idata.gas                = 0;
                    tran.inputs              = new ThinNeo.TransactionInput[0];
                    tran.outputs             = new ThinNeo.TransactionOutput[0];
                    tran.attributes          = new ThinNeo.Attribute[1];
                    tran.attributes[0]       = new ThinNeo.Attribute();
                    tran.attributes[0].usage = TransactionAttributeUsage.Script;
                    tran.attributes[0].data  = ThinNeo.Helper.GetPublicKeyHashFromAddress(addressAdmin);

                    var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);

                    tran.AddWitness(signdata, pubkey, addressAdmin);
                    var    trandata    = tran.GetRawData();
                    var    strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);
                    byte[] postdata;
                    var    url    = httpHelper.MakeRpcUrlPost(Program.BlockApi, "sendrawtransaction", out postdata, new JValue(strtrandata));
                    var    result = httpHelper.HttpPost(url, postdata);
                    Console.WriteLine(result);
                    var j_result = MyJson.Parse(result).AsDict()["result"].AsList()[0].AsDict();
                    if (j_result["sendrawtransactionresult"].AsBool())
                    {
                        var    txid   = j_result["txid"].AsString();
                        Record record = new Record();
                        record.txid  = txid;
                        record.addr  = address;
                        record.value = balance.ToString();
                        mongoHelper.InsetOne <Record>(Program.conn, Program.db, Program.collBak, record);
                    }
                    else
                    {
                    }
                }
            }
        }
Ejemplo n.º 14
0
        async Task test_claim()
        {
            var txid = ""; //产生utxo的txid
            var n    = 1;  //utxo 在txid vout中的index

            subPrintLine("Input txid:");
            txid = Console.ReadLine();
            subPrintLine("Input n:");
            string str_n = Console.ReadLine();

            n = int.Parse(str_n);
            byte[] postdata;
            var    url    = Helper.MakeRpcUrlPost(Config.api, "uxtoinfo", out postdata, new MyJson.JsonNode_ValueString(txid), new MyJson.JsonNode_ValueNumber(n));
            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 starttxid          = resultv["starttxid"].ToString();
                var starttxblockheight = resultv["starttxblockheight"].ToString();
                var starttxblockindex  = resultv["starttxblockindex"].ToString();
                var voutN            = resultv["voutN"].ToString();
                var endtxid          = resultv["endtxid"].ToString();
                var endtxblockheight = resultv["endtxblockheight"].ToString();
                var endtxblockindex  = resultv["endtxblockindex"].ToString();
                var vinputN          = resultv["vinputN"].ToString();

                ThinNeo.Transaction tran = null;
                byte[] script;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    //array.AddArrayValue("(hex256)"+ starttxid);
                    array.AddArrayValue("(int)" + starttxblockheight);
                    array.AddArrayValue("(int)" + starttxblockindex);
                    array.AddArrayValue("(int)" + voutN);
                    //array.AddArrayValue("(hex256)"+ endtxid);
                    array.AddArrayValue("(int)" + endtxblockheight);
                    array.AddArrayValue("(int)" + endtxblockindex);
                    array.AddArrayValue("(int)" + vinputN);
                    sb.EmitParamJson(array);              //参数倒序入
                    sb.EmitPushString("claim");           //参数倒序入
                    sb.EmitAppCall(Config.dapp_coinpool); //nep5脚本
                    script = sb.ToArray();
                }
                //生成交易
                //获取地址的资产列表
                Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Config.api, address);

                if (dir.ContainsKey(Config.id_GAS) == false)
                {
                    subPrintLine("no gas");
                    return;
                }
                tran      = Helper.makeTran(dir[Config.id_GAS], address, new ThinNeo.Hash256(Config.id_GAS), 0);
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = script;

                //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);
                url    = Helper.MakeRpcUrlPost(Config.api_local, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
                result = await Helper.HttpPost(url, postdata);

                subPrintLine("得到的结果是:" + result);
                json = MyJson.Parse(result).AsDict();
                if (json.ContainsKey("result"))
                {
                    resultv = json["result"].AsList()[0].AsDict();
                    txid    = resultv["txid"].AsString();
                    subPrintLine("txid=" + txid);
                }
            }
        }
Ejemplo n.º 15
0
        private void Send(byte[] priKey, string assetid, string sendAssetid, string addr, decimal balance, decimal send, decimal totalSend, decimal sendAssetDecimals, UInt32 height, string snapshotColl)
        {
            try
            {
                decimal decimals = decimal.Parse(sendAssetDecimals.ToString());

                byte[] data = null;

                byte[] pubKey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(priKey);
                string address = ThinNeo.Helper.GetAddressFromPublicKey(pubKey);

                if (addr == address)
                {
                    return;
                }
                //MakeTran
                ThinNeo.Transaction tran = new Transaction();
                {
                    var _send = send * decimal.Parse(Math.Pow(10, (double)decimals).ToString());
                    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);
                        array.AddArrayValue("(addr)" + address);
                        array.AddArrayValue("(addr)" + addr);
                        array.AddArrayValue("(int)" + (BigInteger)_send);
                        sb.EmitParamJson(array);
                        sb.EmitPushString("transfer");
                        sb.EmitAppCall(new Hash160(sendAssetid));
                        data = sb.ToArray();
                    }

                    tran.type = ThinNeo.TransactionType.InvocationTransaction;
                    var idata = new ThinNeo.InvokeTransData();
                    tran.extdata             = idata;
                    idata.script             = data;
                    idata.gas                = 0;
                    tran.inputs              = new ThinNeo.TransactionInput[0];
                    tran.outputs             = new ThinNeo.TransactionOutput[0];
                    tran.attributes          = new ThinNeo.Attribute[1];
                    tran.attributes[0]       = new ThinNeo.Attribute();
                    tran.attributes[0].usage = 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      = HttpHelper.MakeRpcUrlPost(Config.Ins.url, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
                    var    result   = HttpHelper.HttpPost(url, postdata);
                    var    j_result = MyJson.Parse(result).AsDict()["result"].AsList()[0].AsDict();
                    if (j_result["sendrawtransactionresult"].AsBool())
                    {
                        Snapshot snapshot = new Snapshot();
                        snapshot.addr        = addr;
                        snapshot.balance     = BsonDecimal128.Create(balance);
                        snapshot.send        = BsonDecimal128.Create(send);
                        snapshot.txid        = j_result["txid"].AsString();
                        snapshot.sendAssetid = sendAssetid;
                        snapshot.applied     = true;
                        snapshot.assetid     = assetid;
                        snapshot.height      = height;
                        snapshot.totalSend   = BsonDecimal128.Create(totalSend);

                        mongoHelper.ReplaceData(Config.Ins.Snapshot_Conn, Config.Ins.Snapshot_DB, snapshotColl, ToolHelper.RemoveUndefinedParams(JsonConvert.SerializeObject(new Snapshot()
                        {
                            addr = addr, applied = true
                        })), snapshot);

                        mongoHelper.InsetOne(Config.Ins.Snapshot_Conn, Config.Ins.Snapshot_DB, Config.Ins.Snapshot_Current_Coll, snapshot);
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }
        }
Ejemplo n.º 16
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;
                }
            }
        }
Ejemplo n.º 17
0
        public async Task Start()
        {
            /**私钥*/
            string privateKey = "7c5a23ddb24c5eacb200874a32a64585bea7f1dd8efa23745e2b2a7753004c81";
            /**gas资产编号*/
            string gasAsset = "0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b";
            /**合约脚本散列*/
            string scriptHash = "0x98f56b5dc40650da5c1ead5894979e0c2fe4bcd6";
            /**合约代码*/
            string scriptCode = "00c56b616168164e656f2e53746f726167652e476574436f6e746578740548656c6c6f05576f726c64615272680f4e656f2e53746f726167652e50757461616c7566";
            /**名称*/
            string name = "helloworld";
            /**版本*/
            string version = "1.0";
            /**作者*/
            string author = "zhan.li";
            /**邮箱*/
            string email = "*****@*****.**";
            /**说明*/
            string description = "test Create Contract";
            /**参数列表*/
            string paramList = "hello";
            /**返回值*/
            string returnValue = "world";

            byte[] priKey  = Encoding.Default.GetBytes(privateKey);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(priKey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            byte[] script = null;
            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitSysCall(HexToBytes(scriptCode), HexToBytes(paramList), returnValue, "0", name, version, author, email, description);
                sb.EmitSysCall("Neo.Contract.Create");
                script = sb.ToArray();
            }

            Dictionary <string, List <UTXO> > dic_UTXO = await GetUTXOByAddress("http://localhost:20332/", address);

            Transaction tran = makeTran(dic_UTXO, address, targetAddress, new Hash256("0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b"), new decimal(90));

            tran.type       = ThinNeo.TransactionType.InvocationTransaction;
            tran.version    = 0;
            tran.attributes = new ThinNeo.Attribute[0];
            var idata = new ThinNeo.InvokeTransData();

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

            byte[] msg    = tran.GetMessage();
            string msgstr = ThinNeo.Helper.Bytes2HexString(msg);

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

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

            byte[] postdata;
            var    url    = HttpHelper.MakeRpcUrlPost("https://api.nel.group/api/testnet", "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
            var    result = await HttpHelper.HttpPost(url, postdata);

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
        }
Ejemplo n.º 18
0
        public async Task Demo()
        {
            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(Config.test_wif);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

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

            //得到注册器
            var info_reg = await nns_tools.api_InvokeScript(Config.sc_nns, "getOwnerInfo", "(hex256)" + nns_tools.nameHash("sell").ToString());

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

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


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

            Console.WriteLine("addressFrom=" + 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;
            {
                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(addr)" + address);                                //who
                    array.AddArrayValue("(int)10000000000");                                //value
                    sb.EmitParamJson(array);                                                //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)getmoneyback")); //参数倒序入
                    sb.EmitAppCall(reg_sc);
                    script = sb.ToArray();
                }

                tran      = Helper.makeTran(dir[Nep55_1.id_GAS], address, new ThinNeo.Hash256(Nep55_1.id_GAS), 0);
                tran.type = ThinNeo.TransactionType.InvocationTransaction;
                var idata = new ThinNeo.InvokeTransData();
                tran.extdata = idata;
                idata.script = script;
            }
            //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(Nep55_1.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
            var    result = await Helper.HttpPost(url, postdata);

            Console.WriteLine("得到的结果是:" + result);
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
0
    private void on_getutxo_1(bool timeout, WWW www)
    {
        Debug.Log(www.text);
        MyJson.JsonNode_Object response = (MyJson.JsonNode_Object)MyJson.Parse(www.text);

        if (!response.AsDict().ContainsKey("result"))
        {
            Debug.Log("交易失败");
            return;
        }
        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;
            }
        }

        if (_dir.ContainsKey(global.id_GAS) == false)
        {
            Debug.Log("no gas");
        }
        ThinNeo.Transaction tran = null;
        {
            byte[] script = null;
            using (var sb = new ThinNeo.ScriptBuilder())
            {
                var array = new MyJson.JsonNode_Array();
                array.AddArrayValue("(addr)" + roleInfo.getInstance().address);     //from
                array.AddArrayValue("(addr)" + global.cp_adress);                   //to
                array.AddArrayValue("(int)" + (m_num * 100000000));                 //value

                sb.EmitParamJson(array);                                            //参数倒序入
                sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)transfer")); //参数倒序入
                ThinNeo.Hash160 shash = new ThinNeo.Hash160(global.id_sgas);
                sb.EmitAppCall(shash);                                              //nep5脚本

                //拼接发给后台做验证的json字符串
                MyJson.JsonNode_Object account = new MyJson.JsonNode_Object();
                account["sbParamJson"]  = array;
                account["sbPushString"] = new MyJson.JsonNode_ValueString("(str)transfer");
                account["nnc"]          = new MyJson.JsonNode_ValueString(global.id_sgas);

                script = sb.ToArray();

                m_paparms = account.ToString();
                Debug.Log(m_paparms);
            }

            tran      = Helper.makeTran(_dir[global.id_GAS], roleInfo.getInstance().address, new ThinNeo.Hash256(global.id_GAS), 0);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;
            var idata = new ThinNeo.InvokeTransData();
            tran.extdata = idata;
            idata.script = script;
        }

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

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

        transaction_game_sgas(strtrandata);
    }
Ejemplo n.º 21
0
    private void on_getutxo(bool timeout, WWW www)
    {
        Debug.Log(www.text);
        MyJson.JsonNode_Object response = (MyJson.JsonNode_Object)MyJson.Parse(www.text);

        if (!response.AsDict().ContainsKey("result"))
        {
            Debug.Log("交易失败");
            //testtool.showNotice("交易失败");
            return;
        }

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

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

            //生成交易
            tran      = Helper.makeTran(_dir[global.id_GAS], targetaddr, new ThinNeo.Hash256(global.id_GAS), m_num);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;
            var idata = new ThinNeo.InvokeTransData();
            tran.extdata = idata;
            idata.script = script;
        }

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

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

        transaction_sgas(strtrandata);
    }
Ejemplo n.º 22
0
        private static void PubScDemo(string wif)
        {
            string assetid = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7";
            string api     = "https://api.nel.group/api/testnet";

            byte[] prikey  = ThinNeo.Helper_NEO.GetPrivateKeyFromWIF(wif);
            byte[] pubkey  = ThinNeo.Helper_NEO.GetPublicKey_FromPrivateKey(prikey);
            string address = ThinNeo.Helper_NEO.GetAddress_FromPublicKey(pubkey);

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

            //从文件中读取合约脚本
            byte[] script = System.IO.File.ReadAllBytes("TestCoin.avm");             //这里填你的合约所在地址
            Console.WriteLine("合约脚本hash:" + ThinNeo.Helper_NEO.CalcHash160(script)); //合约 hash,也就是 assetId

            byte[] parameter__list = ThinNeo.Helper.HexString2Bytes("0710");         //合约入参类型  例:0610代表(string,[])参考:http://docs.neo.org/zh-cn/sc/Parameter.html
            byte[] return_type     = ThinNeo.Helper.HexString2Bytes("05");           //合约返回值类型 05 代表 ByteArray
            int    need_storage    = 1;                                              //是否需要使用存储 0false 1true
            int    need_nep4       = 0;                                              //是否需要动态调用 0false 2true
            int    need_canCharge  = 4;                                              //是否支持收款 4true

            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                //倒序插入数据
                sb.EmitPushString("test");        //description
                sb.EmitPushString("*****@*****.**"); //email
                sb.EmitPushString("test");        //auther
                sb.EmitPushString("1.0");         //version
                sb.EmitPushString("ABC Coin");    //name
                sb.EmitPushNumber(need_storage | need_nep4 | need_canCharge);
                sb.EmitPushBytes(return_type);
                sb.EmitPushBytes(parameter__list);
                sb.EmitPushBytes(script);
                sb.EmitSysCall("Neo.Contract.Create");

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

                //用ivokescript试运行得到 gas 消耗
                var     result       = HttpGet($"{api}?method=invokescript&id=1&params=[\"{scriptPublish}\"]");
                var     consume      = (JObject.Parse(result)["result"] as JArray)[0]["gas_consumed"].ToString();
                decimal gas_consumed = decimal.Parse(consume);

                ThinNeo.InvokeTransData extdata = new ThinNeo.InvokeTransData();
                extdata.script = sb.ToArray();
                extdata.gas    = Math.Ceiling(gas_consumed - 10);

                //拼装交易体
                ThinNeo.Transaction tran = MakeTran(dir, null, new ThinNeo.Hash256(assetid), extdata.gas);
                tran.version = 1;
                tran.extdata = extdata;
                tran.type    = ThinNeo.TransactionType.InvocationTransaction;
                byte[] msg      = tran.GetMessage();
                byte[] signdata = ThinNeo.Helper_NEO.Sign(msg, prikey);
                tran.AddWitness(signdata, pubkey, address);
                string txid    = tran.GetHash().ToString();
                byte[] data    = tran.GetRawData();
                string rawdata = ThinNeo.Helper.Bytes2HexString(data);

                string input = @"{
	            'jsonrpc': '2.0',
                'method': 'sendrawtransaction',
	            'params': ['#'],
	            'id': '1'
                }";
                input = input.Replace("#", rawdata);

                result = HttpPost(api, input);

                Console.WriteLine(result.ToString());
            }
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
0
        private void Send(byte[] priKey, string assetid, string addr, decimal value, NnsAward nnsAward)
        {
            try
            {
                //获取资产的精度
                byte[]  postdata;
                var     url       = HttpHelper.MakeRpcUrlPost(Config.Ins.url, "getnep5asset", out postdata, new MyJson.JsonNode_ValueString(assetid));
                var     result    = HttpHelper.HttpPost(url, postdata);
                var     Jo_result = MyJson.Parse(result) as MyJson.JsonNode_Object;
                decimal decimals  = 0;
                if (Jo_result.ContainsKey("result"))
                {
                    decimals = (decimal)Math.Pow(10, Jo_result["result"].AsList()[0].AsDict()["decimals"].AsInt());
                }
                else
                {
                    return;
                }


                byte[] data = null;

                byte[] pubKey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(priKey);
                string address = ThinNeo.Helper.GetAddressFromPublicKey(pubKey);

                if (addr == address)
                {
                    return;
                }
                //MakeTran
                ThinNeo.Transaction tran = new Transaction();
                {
                    BigInteger sendValue = (BigInteger)((decimal)value * decimals);
                    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);
                        array.AddArrayValue("(addr)" + address);
                        array.AddArrayValue("(addr)" + addr);
                        array.AddArrayValue("(int)" + sendValue);
                        sb.EmitParamJson(array);
                        sb.EmitPushString("transfer");
                        sb.EmitAppCall(new Hash160(assetid));
                        data = sb.ToArray();
                    }

                    tran.type = ThinNeo.TransactionType.InvocationTransaction;
                    var idata = new ThinNeo.InvokeTransData();
                    tran.extdata             = idata;
                    idata.script             = data;
                    idata.gas                = 0;
                    tran.inputs              = new ThinNeo.TransactionInput[0];
                    tran.outputs             = new ThinNeo.TransactionOutput[0];
                    tran.attributes          = new ThinNeo.Attribute[1];
                    tran.attributes[0]       = new ThinNeo.Attribute();
                    tran.attributes[0].usage = 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);

                    url    = HttpHelper.MakeRpcUrlPost(Config.Ins.url, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
                    result = HttpHelper.HttpPost(url, postdata);
                    Console.WriteLine(result);
                    var j_result = MyJson.Parse(result).AsDict()["result"].AsList()[0].AsDict();
                    if (j_result["sendrawtransactionresult"].AsBool())
                    {
                        nnsAward.txid     = j_result["txid"].AsString();
                        nnsAward.maxBuyer = addr;
                        nnsAward.maxBonus = Decimal128.Parse(value.ToString());
                        mongoHelper.ReplaceData(Config.Ins.Applyfornnc_Conn, Config.Ins.Applyfornnc_DB, Config.Ins.Applyfornnc_Coll, "{maxBuyer:\"" + addr + "\"}", nnsAward);
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return;
            }
        }