示例#1
0
        async public Task Demo()
        {
            string wif1       = "KwwJMvfFPcRx2HSgQRPviLv4wPrxRaLk7kfQntkH8kCXzTgAts8t";
            string targetAddr = "AdsNmzKPPG7HfmQpacZ4ixbv9XJHJs2ACz";

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

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

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

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

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

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

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
            Console.WriteLine(resJO.ToString());
        }
示例#2
0
        public JObject sendrawtransaction(string neoCliJsonRPCUrl, string txSigned)
        {
            httpHelper hh   = new httpHelper();
            var        resp = hh.Post(neoCliJsonRPCUrl, "{'jsonrpc':'2.0','method':'sendrawtransaction','params':['" + txSigned + "'],'id':1}", System.Text.Encoding.UTF8, 1);

            bool    isSendSuccess = (bool)JObject.Parse(resp)["result"];
            JObject Jresult       = new JObject();

            Jresult.Add("sendrawtransactionresult", isSendSuccess);
            if (isSendSuccess)
            {
                ThinNeo.Transaction lastTran = new ThinNeo.Transaction();
                lastTran.Deserialize(new MemoryStream(txSigned.HexString2Bytes()));
                string txid = lastTran.GetHash().ToString();

                ////从已签名交易体分析出未签名交易体,并做Hash获得txid
                //byte[] txUnsigned = txSigned.Split("014140")[0].HexString2Bytes();
                //string txid = ThinNeo.Helper.Sha256(ThinNeo.Helper.Sha256(txUnsigned)).Reverse().ToArray().ToHexString();

                Jresult.Add("txid", txid);
            }
            else
            {
                //上链失败则返回空txid
                Jresult.Add("txid", string.Empty);
            }

            return(Jresult);
        }
示例#3
0
        private async Task <JObject> asyncApplyGas(List <string> targetAddress, decimal amount, Dictionary <string, List <Utxo> > dir)
        {
            // 转换私钥
            byte[] prikey  = accountInfo.prikey;
            byte[] pubkey  = accountInfo.pubkey;
            string address = accountInfo.address;

            // 获取余额
            string id_gas = assetid;

            //Dictionary<string, List<Utxo>> dir2 = await TransHelper.GetBalanceByAddress(nelJsonRpcUrl, address);
            if (dir == null || dir[id_gas] == null)
            {
                // 余额不足
                return(insufficientBalance());
            }
            List <Utxo> balanceUtxo = dir[id_gas];

            if (balanceUtxo.Sum(p => p.value) < amount * targetAddress.Count())
            {
                // 余额不足
                return(insufficientBalance());
            }

            // 构造并发送交易
            ThinNeo.Transaction tran = TransHelper.makeTran(dir[id_gas], targetAddress, new ThinNeo.Hash256(id_gas), amount);
            tran.type = ThinNeo.TransactionType.ContractTransaction;
            byte[] msg      = tran.GetMessage();
            byte[] signdata = ThinNeo.Helper.Sign(msg, prikey);
            tran.AddWitness(signdata, pubkey, address);
            string txid = tran.GetHash().ToString();

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

            byte[] postdata;
            try
            {
                string url    = TransHelper.MakeRpcUrlPost(nelJsonRpcUrl, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
                var    result = await TransHelper.HttpPost(url, postdata);

                Console.WriteLine("result:" + result);
                if (JObject.Parse(result)["result"] == null)
                {
                    return(txFail(txid));
                }
                JObject res  = (JObject)(((JArray)(JObject.Parse(result)["result"]))[0]);
                string  flag = res["sendrawtransactionresult"].ToString();
                if (flag != "True" && res["txid"].ToString() != txid)
                {
                    return(txFail(txid));
                }
                return(txSucc(txid));
            } catch (Exception)
            {
                return(txFail(txid));
            }
        }
示例#4
0
        static async void DelContract(string avmPath, string strurl, string rpcurl, string assetId, string wif, string change_address)
        {
            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(strurl, address);

            //从文件中读取合约脚本
            byte[] script = System.IO.File.ReadAllBytes(avmPath); //这里填你的合约所在地址
            //Console.WriteLine("合约脚本:"+ThinNeo.Helper.Bytes2HexString(script));
            Console.WriteLine("合约脚本hash:" + ThinNeo.Helper.GetScriptHashFromScript(script));


            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                //倒叙插入数据
                sb.EmitPushBytes(script);
                sb.EmitSysCall("Neo.Contract.Destroy");

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

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

                //string result = http.Post(api, "invokescript", new MyJson.JsonNode_Array() { new MyJson.JsonNode_ValueString(scriptPublish) },Encoding.UTF8);
                var     resultObj               = MyJson.Parse(result) as MyJson.JsonNode_Object;
                var     consume                 = resultObj["result"].AsDict()["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 = (gas_consumed >= 10) ? Math.Ceiling(gas_consumed - 10) : gas_consumed;

                //拼装交易体
                ThinNeo.Transaction tran = makeTran(dir, null, new ThinNeo.Hash256(assetId), extdata.gas, change_address);
                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    = Helper.MakeRpcUrlPost(rpcurl, "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());
            }
        }
示例#5
0
        static async void nep53(string strurl, string rpcurl, string avmPath, string wif, string toaddr, string asset)
        {
            //从文件中读取合约脚本
            byte[] script = System.IO.File.ReadAllBytes(avmPath); //这里填你的合约所在地址
            var    nnc    = ThinNeo.Helper.GetScriptHashFromScript(script);

            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(strurl, address);


            string targeraddr = address;  //Transfer it to yourself.

            ThinNeo.Transaction tran = Helper.makeTran(dir[asset], targeraddr, new ThinNeo.Hash256(asset), decimal.Zero);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;

            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();

            var scriptaddress = new ThinNeo.Hash160(nnc);

            //Parameter inversion
            MyJson.JsonNode_Array JAParams = new MyJson.JsonNode_Array();
            JAParams.Add(new MyJson.JsonNode_ValueString("(address)" + address));
            JAParams.Add(new MyJson.JsonNode_ValueString("(address)" + toaddr));
            JAParams.Add(new MyJson.JsonNode_ValueString("(integer)" + 1));
            sb.EmitParamJson(JAParams);    //Parameter list
            sb.EmitPushString("transfer"); //Method
            sb.EmitAppCall(scriptaddress); //Asset contract

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

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

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


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

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(response);
            if (resJO.ContainsKey("result"))
            {
                Console.WriteLine(resJO["result"].ToString());
            }
        }
示例#6
0
        static async void SendtoAddress(string strurl, string rpcurl, string assetId, string wif1, string toadd, string value, string change_address)
        {
            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif1);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string fromadd = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            Dictionary <string, List <Utxo> > dir = null;

            try
            {
                dir = await Helper.GetBalanceByAddress(strurl, fromadd);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            //拼装交易体
            string[] targetAddrs = new string[1] {
                toadd
            };
            decimal sendCount = decimal.Parse(value);

            try
            {
                ThinNeo.Transaction tran = makeTran(dir, targetAddrs, new ThinNeo.Hash256(assetId), sendCount, change_address);
                tran.version = 0;
                tran.type    = ThinNeo.TransactionType.ContractTransaction;
                byte[] msg      = tran.GetMessage();
                string msgstr   = ThinNeo.Helper.Bytes2HexString(msg);
                byte[] signdata = ThinNeo.Helper.Sign(msg, prikey);
                tran.AddWitness(signdata, pubkey, fromadd);
                string txid    = tran.GetHash().ToString();
                byte[] data    = tran.GetRawData();
                string rawdata = ThinNeo.Helper.Bytes2HexString(data);

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

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

                MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
                Console.WriteLine(resJO.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.Write("cmd>");
        }
示例#7
0
        async public Task Demo()
        {
            string nnc = "0x3fccdb91c9bb66ef2446010796feb6ca4ed96b05";

            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF("L3tDHnEAvwnnPE4sY4oXpTvNtNhsVhbkY4gmEmWmWWf1ebJhVPVW");
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            string toaddr  = "APwCdakS1NpJsiq6j9SfvkQFS9ubt347a2";
            string id_GAS  = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7";

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


            string targeraddr = address;  //Transfer it to yourself.

            ThinNeo.Transaction tran = Helper.makeTran(dir[id_GAS], targeraddr, new ThinNeo.Hash256(id_GAS), decimal.Zero);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;

            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();

            var scriptaddress = new ThinNeo.Hash160(nnc);

            //Parameter inversion
            MyJson.JsonNode_Array JAParams = new MyJson.JsonNode_Array();
            JAParams.Add(new MyJson.JsonNode_ValueString("(address)" + address));
            JAParams.Add(new MyJson.JsonNode_ValueString("(address)" + toaddr));
            JAParams.Add(new MyJson.JsonNode_ValueString("(integer)" + 1));
            sb.EmitParamJson(JAParams);    //Parameter list
            sb.EmitPushString("transfer"); //Method
            sb.EmitAppCall(scriptaddress); //Asset contract

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

            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 scripthash = ThinNeo.Helper.Bytes2HexString(data);

            string response = await Helper.HttpGet(api + "?method=sendrawtransaction&id=1&params=[\"" + scripthash + "\"]");

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(response);
            Console.WriteLine(resJO["result"].ToString());
        }
示例#8
0
        public static string RecordTran(ThinNeo.Transaction trans)
        {
            var      txid = ThinNeo.Helper.Bytes2HexString(trans.GetHash().Reverse().ToArray());
            TranInfo info = new TranInfo();

            info.time = DateTime.Now;
            info.type = trans.type;
            info.txid = txid;
            TxHistory.Add(info);
            foreach (var input in trans.inputs)
            {
                var txid2   = ThinNeo.Helper.Bytes2HexString(input.hash.Reverse().ToArray());
                var strutxo = txid2 + "_" + input.index;
                UtxoHistory.Add(strutxo);
            }
            return(txid);
        }
示例#9
0
        async public Task Demo()
        {
            string wif1        = "KwwJMvfFPcRx2HSgQRPviLv4wPrxRaLk7kfQntkH8kCXzTgAts8t";
            string wif2        = "L2EHemxzCYKxhH81QVwPDwUT5Bd8yBgbPt7GnUFpGuttiiYroRFi";
            string targetAddr1 = "AHDV7M54NHukq8f76QQtBTbrCqKJrBH9UF";
            string targetAddr2 = "AdsNmzKPPG7HfmQpacZ4ixbv9XJHJs2ACz";

            byte[] prikey1  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif1);
            byte[] pubkey1  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey1);
            string address1 = ThinNeo.Helper.GetAddressFromPublicKey(pubkey1);

            byte[] prikey2  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif2);
            byte[] pubkey2  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey2);
            string address2 = ThinNeo.Helper.GetAddressFromPublicKey(pubkey2);

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

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


            //拼装交易体
            string[] targetAddrs = new string[2] {
                targetAddr1, targetAddr2
            };
            ThinNeo.Transaction tran = makeTran(dir1, dir2, targetAddrs, new ThinNeo.Hash256(id_GAS), 2);
            tran.version = 0;
            tran.type    = ThinNeo.TransactionType.ContractTransaction;
            byte[] msg       = tran.GetMessage();
            byte[] signdata  = ThinNeo.Helper.Sign(msg, prikey1);
            byte[] signdata2 = ThinNeo.Helper.Sign(msg, prikey2);
            tran.AddWitness(signdata, pubkey1, address1);
            tran.AddWitness(signdata2, pubkey2, address2);
            string txid = tran.GetHash().ToString();

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

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

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(result);
            Console.WriteLine(resJO.ToString());
        }
示例#10
0
        private JObject sendrawtransaction(string neoCliJsonRPCUrl, string txSigned)
        {
            var resp = httpHelper.Post(neoCliJsonRPCUrl, "{'jsonrpc':'2.0','method':'sendrawtransaction','params':['" + txSigned + "'],'id':1}", System.Text.Encoding.UTF8, 1);

            JObject Jresult       = new JObject();
            bool    isSendSuccess = false;
            var     res           = JObject.Parse(resp);

            if (res["error"] != null && res["error"]["message"] != null)
            {
                isSendSuccess = false;

                Jresult.Add("errorMessage", res["error"]["message"]);
            }
            else
            {
                isSendSuccess = (bool)JObject.Parse(resp)["result"];
            }
            //bool isSendSuccess = (bool)JObject.Parse(resp)["result"];
            //JObject Jresult = new JObject();
            Jresult.Add("sendrawtransactionresult", isSendSuccess);
            if (isSendSuccess)
            {
                ThinNeo.Transaction lastTran = new ThinNeo.Transaction();
                lastTran.Deserialize(new MemoryStream(txSigned.HexString2Bytes()));
                string txid = lastTran.GetHash().ToString();
                Jresult.Add("txid", txid);
            }
            else
            {
                //上链失败则返回空txid
                Jresult.Add("txid", string.Empty);
            }

            return(Jresult);
        }
示例#11
0
        void DoCallTran(ThinNeo.Transaction tx)
        {
            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 _params = new Newtonsoft.Json.Linq.JArray();

            var data = tx.GetRawData();

            _params.Add(ThinNeo.Helper.Bytes2HexString(data));
            upparam["params"] = _params;

            var info = wc.UploadString(url, upparam.ToString());

            Console.WriteLine(info);

            var   txid = tx.GetHash();
            State s    = new State();

            s.state = 0;
            mapTxState[txid.ToString()] = s;
        }
示例#12
0
        public void ZoroTransfer()
        {
            byte[]        prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif);
            var           pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            var           address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            ScriptBuilder sb      = new ScriptBuilder();

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

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

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

            byte[] postdata;

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

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

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

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

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

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

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

            Console.WriteLine(result + " txid: " + txid);
        }
示例#13
0
 public static string getTxidFromSignedTx(string txSigned)
 {
     ThinNeo.Transaction lastTran = new ThinNeo.Transaction();
     lastTran.Deserialize(new MemoryStream(txSigned.HexString2Bytes()));
     return(lastTran.GetHash().ToString());
 }
示例#14
0
        async public Task Demo()
        {
            Console.WriteLine("请输入你的wif");
            string wif = Console.ReadLine();

            if (string.IsNullOrEmpty(wif))
            {
                wif = "";  //这里填你用于支付发布合约消耗的私钥
            }
            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("Nep5.5gas_Contract.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       = 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 | need_nep4 | need_canCharge;
                //倒叙插入数据
                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    = Helper.MakeRpcUrlPost(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.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(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);

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

                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());
            }
        }
示例#15
0
        async public Task Demo()
        {
            byte[] prikey     = ThinNeo.Helper.GetPrivateKeyFromWIF(Nep55_1.testwif);
            byte[] pubkey     = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address    = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            var    scripthash = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);

            var    nep55_shash   = new ThinNeo.Hash160(Nep55_1.nep55);
            string nep55_address = ThinNeo.Helper.GetAddressFromScriptHash(nep55_shash);


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

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

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

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

                var    urlCheckUTXO    = Helper.MakeRpcUrl(Nep55_1.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);
                }
            }


            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 = new ThinNeo.Hash160(Nep55_1.nep55);
                    sb.EmitAppCall(shash);                                            //nep5脚本
                    script = sb.ToArray();
                }
                Console.WriteLine("contract address=" + nep55_address);//往合约地址转账

                //生成交易
                tran      = Helper.makeTran(newlist, nep55_address, new ThinNeo.Hash256(Nep55_1.id_GAS), (decimal)2.1);
                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[] n55contract = null;
                {
                    var urlgetscript    = Helper.MakeRpcUrl(Nep55_1.api, "getcontractstate", new MyJson.JsonNode_ValueString(Nep55_1.nep55));
                    var resultgetscript = await Helper.HttpGet(urlgetscript);

                    var _json    = MyJson.Parse(resultgetscript).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(), 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(Nep55_1.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));


            //bug
            //sendraw api 有bug,所以先加这个
            //url = "http://localhost:20332";

            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拿走GAS了 txid=" + lasttxid.ToString() + "[0]");
                }
                else
                {
                    lasttxid = null;
                }
            }
        }
示例#16
0
        async public Task Demo()
        {
            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(Nep55_1.testwif);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

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

            //获取地址的资产列表
            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;
            }
            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(Nep55_1.nep55);
                    sb.EmitAppCall(shash);                                                //nep5脚本
                    script = sb.ToArray();
                }
                var nep5scripthash = new ThinNeo.Hash160(Nep55_1.nep55);
                var targetaddr     = ThinNeo.Helper.GetAddressFromScriptHash(nep5scripthash);
                Console.WriteLine("contract address=" + targetaddr);//往合约地址转账

                //生成交易
                tran      = Helper.makeTran(dir[Nep55_1.id_GAS], targetaddr, new ThinNeo.Hash256(Nep55_1.id_GAS), 5);
                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);
            var json = MyJson.Parse(result).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();
                }
                Console.WriteLine("txid=" + txid);
            }
        }
示例#17
0
        void signAndBroadcast()
        {
            if (this.listInput.Items.Count == 0)
            {
                MessageBox.Show("no input");
                return;
            }
            if (this.listOutput.Items.Count == 0)
            {
                MessageBox.Show("no output");
                return;
            }
            if (this.listWitness.Items.Count == 0)
            {
                MessageBox.Show("no witness");
                return;
            }
            ThinNeo.Transaction trans = new ThinNeo.Transaction();
            trans.attributes = new ThinNeo.Attribute[0];
            if (tabCType.SelectedIndex == 0)
            {
                trans.type = ThinNeo.TransactionType.ContractTransaction;
            }
            else if (tabCType.SelectedIndex == 1)
            {
                if (lastScript == null)
                {
                    throw new Exception("need script");
                }
                if (lastFee.HasValue == false)
                {
                    throw new Exception("need test script");
                }

                trans.type    = ThinNeo.TransactionType.InvocationTransaction;
                trans.extdata = new ThinNeo.InvokeTransData();
                (trans.extdata as ThinNeo.InvokeTransData).script = lastScript;
                (trans.extdata as ThinNeo.InvokeTransData).gas    = lastFee.Value;
            }
            trans.inputs    = new ThinNeo.TransactionInput[this.listInput.Items.Count];
            trans.outputs   = new ThinNeo.TransactionOutput[this.listOutput.Items.Count];
            trans.witnesses = new ThinNeo.Witness[this.listWitness.Items.Count];
            for (var i = 0; i < listInput.Items.Count; i++)
            {
                var item  = listInput.Items[i] as Tools.Input;
                var input = new ThinNeo.TransactionInput();
                input.index     = (ushort)item.Coin.fromN;
                input.hash      = ThinNeo.Helper.HexString2Bytes(item.Coin.fromID).Reverse().ToArray();//反转
                trans.inputs[i] = input;
            }
            for (var i = 0; i < listOutput.Items.Count; i++)
            {
                var item   = listOutput.Items[i] as Tools.Output;
                var output = new ThinNeo.TransactionOutput();
                output.assetId   = ThinNeo.Helper.HexString2Bytes(item.assetID).Reverse().ToArray();//反转
                output.toAddress = ThinNeo.Helper.GetPublicKeyHashFromAddress(item.Target);
                output.value     = item.Fix8;
                trans.outputs[i] = output;
            }
            for (var i = 0; i < listWitness.Items.Count; i++)
            {
                var item    = listWitness.Items[i] as Tools.Witnees;
                var witness = new ThinNeo.Witness();

                if (item.IsSmartContract)
                {
                    if (item.iscript == null)
                    {
                        throw new Exception("a smartContract witness not set InvocationScript.");
                    }
                    var s = ThinNeo.Helper.GetPublicKeyHashFromAddress(item.address);
                    witness.VerificationScript = rpc_getScript(s);
                    witness.InvocationScript   = item.iscript;
                    return;
                }
                else //个人鉴证人
                {
                    var pubkey = ThinNeo.Helper.GetPublicKeyFromPrivateKey(this.privatekey);
                    var addr   = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
                    if (item.address != addr)
                    {
                        MessageBox.Show("the key is no match with your witness.");
                    }

                    witness.VerificationScript = ThinNeo.Helper.GetScriptFromPublicKey(pubkey);

                    var signdata = ThinNeo.Helper.Sign(trans.GetMessage(), this.privatekey);
                    var sb       = new ThinNeo.ScriptBuilder();
                    sb.EmitPushBytes(signdata);

                    witness.InvocationScript = sb.ToArray();
                }
                trans.witnesses[i] = witness;
            }

            var  rawdata = trans.GetRawData();
            bool b       = rpc_SendRaw(rawdata);

            if (b)
            {
                var hash = trans.GetHash();
                var str  = ThinNeo.Helper.Bytes2HexString(hash.Reverse().ToArray());
                MessageBox.Show("txid=" + str);
            }
            else
            {
                MessageBox.Show("transaction error");
            }
        }
示例#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);

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

            //从文件中读取合约脚本
            byte[] script     = System.IO.File.ReadAllBytes("dapp_sgas_migrate.avm"); //这里填你的合约所在地址
            string str_script = ThinNeo.Helper.Bytes2HexString(script);

            byte[] aa = ThinNeo.Helper.HexString2Bytes(str_script);
            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.dapp_sgas;
                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    = 500;// 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);
                tran.AddWitness(signdata, pubkey, 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());
            }
        }
示例#19
0
文件: SCDUtil.cs 项目: hwlsniper/MVP
        async public Task <string> Operation(string script, string prikeyStr, string method, List <string> args)
        {
            // string script = "0x342c8b1242c195929b109079da947b1e973fe2be";
            // string script = "0x96babb04e415a402b973350df71e10d24c725f78";
            //   string script = "0x55b300f8468d9e2bb9c3a4b8ff870c8c3b6ddf7c";//测试网


            // byte[] prikey = ThinNeo.Helper.GetPrivateKeyFromWIF(prikeyStr);
            // byte[] prikey = ThinNeo.Helper.GetPrivateKeyFromWIF("L3tDHnEAvwnnPE4sY4oXpTvNtNhsVhbkY4gmEmWmWWf1ebJhVPVW");//测试网
            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(prikeyStr);
            byte[] pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            //  string toaddr = "APwCdakS1NpJsiq6j9SfvkQFS9ubt347a2";
            string id_GAS = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7";
            //   Console.WriteLine("prikey:" + prikeyStr);
            //获取地址的资产列表
            Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(api, address);

            string targeraddr = address;  //Transfer it to yourself.

            ThinNeo.Transaction tran = Helper.makeTran(dir[id_GAS], targeraddr, new ThinNeo.Hash256(id_GAS), decimal.Zero);
            tran.type = ThinNeo.TransactionType.InvocationTransaction;
            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
            var scriptaddress        = new ThinNeo.Hash160(script);

            //Parameter inversion
            MyJson.JsonNode_Array JAParams = new MyJson.JsonNode_Array();
            var uuidN = "";

            //加入循环记录参数
            if ("saveValidateInfo".Equals(method) || "savePayInfo".Equals(method))
            {
                uuidN = Guid.NewGuid().ToString("N");
                JAParams.Add(new MyJson.JsonNode_ValueString("(str)" + uuidN));
                JAParams.Add(new MyJson.JsonNode_ValueString("(str)" + args[0]));
            }
            else if ("saveResult".Equals(method))
            {
                uuidN = args[0];
                JAParams.Add(new MyJson.JsonNode_ValueString("(str)" + uuidN));
                JAParams.Add(new MyJson.JsonNode_ValueString("(str)" + args[1]));
            }
            else if ("transfer".Equals(method))
            {
                JAParams.Add(new MyJson.JsonNode_ValueString("(address)" + args[0]));
                JAParams.Add(new MyJson.JsonNode_ValueString("(address)" + args[1]));
                JAParams.Add(new MyJson.JsonNode_ValueString("(integer)" + args[2]));
            }
            else if ("allotTKY".Equals(method))
            {
                uuidN = Guid.NewGuid().ToString("N");
                JAParams.Add(new MyJson.JsonNode_ValueString("(str)" + uuidN));
                JAParams.Add(new MyJson.JsonNode_ValueString("(integer)" + args[0]));
                JAParams.Add(new MyJson.JsonNode_ValueString("(integer)" + args[1]));
            }
            else
            {
            }
            sb.EmitParamJson(JAParams);//Parameter list
            if ("saveValidateInfo".Equals(method))
            {
                sb.EmitPushString("save"); //Method
            }
            sb.EmitPushString(method);     //Method
            sb.EmitAppCall(scriptaddress); //Asset contract
            //转账
            //加入循环记录参数
            //JAParams.Add(new MyJson.JsonNode_ValueString("(addr)AeP5KqSJxPEpWCGRfoDiCr3Xtg6jJbRbbH"));
            //JAParams.Add(new MyJson.JsonNode_ValueString("(addr)AMZiiAnBg5uFLXGVMSt4hPEA2ubRCiNZg5"));
            //JAParams.Add(new MyJson.JsonNode_ValueString("(integer)9"));
            //// JAParams.Add(new MyJson.JsonNode_ValueString("(integer)" + 1));
            //sb.EmitParamJson(JAParams);//Parameter list
            ////方法名
            //sb.EmitPushString("transfer");//Method
            ThinNeo.InvokeTransData extdata = new ThinNeo.InvokeTransData();
            extdata.script = sb.ToArray();
            extdata.gas    = 1;
            tran.extdata   = extdata;

            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 scripthash = ThinNeo.Helper.Bytes2HexString(data);
            //String url2 = "http://47.96.168.8:20332";//测试网
            String url2 = "http://192.168.70.25:10332";
            //   Console.WriteLine("txid:" + txid);
            // Console.WriteLine("签名:"+scripthash);
            // return scripthash;
            string response = await Helper.HttpGet(url2 + "?method=sendrawtransaction&id=1&params=[\"" + scripthash + "\"]");

            MyJson.JsonNode_Object resJO = (MyJson.JsonNode_Object)MyJson.Parse(response);
            //  Console.WriteLine(resJO["result"].ToString());
            string resultStr = "";

            if ("saveValidateInfo".Equals(method) || "savePayInfo".Equals(method))
            {
                resultStr = "sendrawtransactionResult:" + resJO["result"].ToString() + ",chainKey:" + uuidN + ",txid:" + txid;;
            }
            else if ("saveResult".Equals(method))
            {
                resultStr = "sendrawtransactionResult:" + resJO["result"].ToString() + ",chainKey:" + args[0] + "rs,txid:" + txid;
            }
            else if ("transfer".Equals(method))
            {
                resultStr = "sendrawtransactionResult:" + resJO["result"].ToString();
            }
            else if ("allotTKY".Equals(method))
            {
                resultStr = "sendrawtransactionResult:" + resJO["result"].ToString() + ",chainKey:" + uuidN + ",txid:" + txid;
            }
            else
            {
            }
            //    Console.WriteLine(resultStr);
            return(resultStr);
        }
示例#20
0
        async public Task Demo()
        {
            var lasthash = "0x0963614006fda9ebb3ecbc1a7bd604a393cfe66cf9234882abc860cdb4694970";

            if (lasthash == null)
            {
                Console.WriteLine("你还没有正确执行N5 3");
                return;
            }
            byte[] prikey     = ThinNeo.Helper.GetPrivateKeyFromWIF(Nep55_1.testwif);
            byte[] pubkey     = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            string address    = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
            var    scripthash = ThinNeo.Helper.GetPublicKeyHashFromAddress(address);

            var    nep55_shash   = new ThinNeo.Hash160(Nep55_1.nep55);
            string nep55_address = ThinNeo.Helper.GetAddressFromScriptHash(nep55_shash);


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

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

            if (dir.ContainsKey(Nep55_1.id_GAS) == false)
            {
                Console.WriteLine("no gas");
                return;
            }
            List <Utxo> newlist = new List <Utxo>();

            foreach (var utxo in dir[Nep55_1.id_GAS])
            {
                if (utxo.n == 0 && utxo.txid.ToString().Equals(lasthash))
                {
                    newlist.Add(utxo);
                }
            }
            if (newlist.Count == 0)
            {
                Console.WriteLine("找不到要使用的UTXO");
                return;
            }

            {//检查utxo
                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(hex256)" + newlist[0].txid.ToString());
                    sb.EmitParamJson(array);                                                   //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)getRefundTarget")); //参数倒序入
                    var shash = new ThinNeo.Hash160(Nep55_1.nep55);
                    sb.EmitAppCall(shash);                                                     //nep5脚本
                    script = sb.ToArray();
                }
                var    urlCheckUTXO    = Helper.MakeRpcUrl(Nep55_1.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,不能使用
                {
                    Console.WriteLine("这个utxo没有标记");
                    return;
                }
                var hash = new ThinNeo.Hash160(ThinNeo.Helper.HexString2Bytes(value));
                //if (hash.ToString()!= scripthash.ToString())
                //{
                //    Console.WriteLine("这个utxo不是标记给你用的");
                //    return;
                //}
            }


            ThinNeo.Transaction tran = Helper.makeTran(newlist, address, new ThinNeo.Hash256(Nep55_1.id_GAS), newlist[0].value);
            tran.type    = ThinNeo.TransactionType.ContractTransaction;
            tran.version = 0;


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

                    var _json    = MyJson.Parse(resultgetscript).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.EmitPushNumber(0);
                    sb.EmitPushNumber(0);
                    iscript = sb.ToArray();
                }
                tran.AddWitnessScript(n55contract, iscript);
            }


            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(Nep55_1.api, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));


            //bug
            //sendraw api 有bug,所以先加这个
            //url = "http://localhost:20332";


            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)
                {
                    Nep55_1.lastNep5Tran = tran.GetHash();
                    Console.WriteLine("besucc txid=" + tran.GetHash().ToString());
                }
            }
        }