Ejemplo n.º 1
0
        public JObject sendTxPlusSign(string neoCliJsonRPCUrl, string txScriptHex, string signHex, string publicKeyHex)
        {
            byte[] txScript = txScriptHex.HexString2Bytes();
            byte[] sign     = signHex.HexString2Bytes();
            byte[] pubkey   = publicKeyHex.HexString2Bytes();
            //byte[] prikey = privateKeyHex.HexToBytes();

            //byte[] sign = null;

            //sign = ThinNeo.Helper.Sign(txScript, prikey);

            //var pubkey = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);

            var addr = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            ThinNeo.Transaction lastTran = new ThinNeo.Transaction();
            lastTran.Deserialize(new MemoryStream(txScript));
            lastTran.witnesses = null;
            lastTran.AddWitness(sign, pubkey, addr);

            string TxPlusSignStr = string.Empty;

            using (var ms = new System.IO.MemoryStream())
            {
                lastTran.Serialize(ms);
                TxPlusSignStr = ms.ToArray().ToHexString();
            }

            return(sendrawtransaction(neoCliJsonRPCUrl, TxPlusSignStr));
        }
Ejemplo n.º 2
0
        private static async void TransGasForNep5(string address, byte[] prikey, byte[] pubkey, string targetAddr,
                                                  decimal sendCount)
        {
            var    assetnep5 = "0xa0b53d2efa8b1c4a62fcc1fcb54b7641510810c7";
            var    assetgas  = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7";
            string api       = "https://api.nel.group/api/testnet";

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

            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(assetnep5);
                    sb.EmitAppCall(shash);                                                //nep5脚本
                    script = sb.ToArray();
                }

                var nep5scripthash = new ThinNeo.Hash160(assetnep5);
                var targetaddr     = ThinNeo.Helper.GetAddressFromScriptHash(nep5scripthash);
                Console.WriteLine("contract address=" + targetaddr); //往合约地址转账

                //生成交易
                tran      = makeTran(dir[assetgas], targetaddr, new ThinNeo.Hash256(assetgas), 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    = HttpHelper.MakeRpcUrlPost("http://127.0.0.1:20332", "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
            var    result = await HttpHelper.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)
                {
                    Hash256 test = tran.GetHash();
                }

                Console.WriteLine("txid=" + txid);
            }
        }
Ejemplo n.º 3
0
        public Transaction MakeTran(byte[] script, decimal systemfee, decimal netfee, bool sign = true)
        {
            Transaction tran = new ThinNeo.Transaction();

            tran.type    = TransactionType.InvocationTransaction;
            tran.version = 0;
            tran.extdata = new InvokeTransData();
            (tran.extdata as InvokeTransData).script = script;
            (tran.extdata as InvokeTransData).gas    = 0;
            //没有系统费用就不用utxo模式的交易发放了
            if (netfee <= 0 && systemfee <= 0)
            {
                MakeTran_Nofee(tran);
            }
            else
            {
                MakeTran_Hasfee(tran, systemfee, netfee);
            }
            if (systemfee > 0)
            {
                tran.version = 1;
                (tran.extdata as InvokeTransData).gas = systemfee;
            }

            if (sign)
            {
                SignTran(tran);
            }

            return(tran);
        }
Ejemplo n.º 4
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);

            subPrintLine("Get Total Supply for " + this.ID + ":");

            var result = await nns_tools.api_InvokeScript(sc, "totalSupply");

            subPrintLine("Total Supply : " + result.value.subItem[0].AsInteger());

            //获取地址的资产列表
            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);                            //from
                    array.AddArrayValue("(str)" + "totalSupply");                       //to
                    array.AddArrayValue("(int)22");                                     //value
                    sb.EmitParamJson(array);                                            //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)transfer")); //参数倒序入
                    ThinNeo.Hash160 shash = new ThinNeo.Hash160(sc);
                    sb.EmitAppCall(shash);                                              //nep5脚本
                    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;//Nep55_1.api
            var    url     = Helper.MakeRpcUrlPost(nnc_1.api_local, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(strtrandata));
            var    result2 = await Helper.HttpPost(url, postdata);

            Console.WriteLine("得到的结果是:" + result2);
        }
Ejemplo n.º 5
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.º 6
0
        async Task test_batchTransferNEO()
        {
            DateTime dt = DateTime.Now;

            Console.WriteLine("Start time:" + dt);
            byte[] postdata;

            string api = "http://api.alchemint.io/api/privatenet";
            //查询交易,总数可能很多
            var url = Helper.MakeRpcUrlPost(api, "getaddrs", out postdata,
                                            new JsonNode_ValueNumber(1000),
                                            new JsonNode_ValueNumber(1));
            var result = await Helper.HttpPost(url, postdata);

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

            MyJson.JsonNode_Object json = MyJson.Parse(result) as MyJson.JsonNode_Object;
            JsonNode_Array         arrs = json["result"].AsList();

            foreach (JsonNode_Object ob in arrs)
            {
                string to = ob["addr"].AsString();
                Console.WriteLine("to:" + to);
                //获取地址的资产列表
                Dictionary <string, List <Utxo> > dir = await Helper.GetBalanceByAddress(Config.api, this.address);

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

                ThinNeo.Transaction tran = Helper.makeTran(newlist, to, new ThinNeo.Hash256(Config.id_NEO), 100);

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

                string poststr = System.Text.Encoding.UTF8.GetString(postdata);

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

                Console.WriteLine("得到的结果是:" + result);
                Thread.Sleep(40000);
            }
            DateTime end = DateTime.Now;

            Console.WriteLine("End time:" + end);
            //等待时间
        }
Ejemplo n.º 7
0
        public string getInvokeTxHex(JArray utxoJA, string addrOut, string script, decimal scriptFee)
        {
            var assetIDStr = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"; //选择GAS支付合约调用费用
            var assetID    = assetIDStr.Replace("0x", "").HexString2Bytes().Reverse().ToArray();

            //linq查找指定asset最大的utxo
            var query = from utxos in utxoJA.Children()
                        where (string)utxos["asset"] == assetIDStr
                        orderby(decimal) utxos["value"] descending
                        select utxos;

            var utxo = query.ToList()[0];

            byte[]  utxo_txid  = ThinNeo.Debug.DebugTool.HexString2Bytes(((string)utxo["txid"]).Replace("0x", "")).Reverse().ToArray();
            ushort  utxo_n     = (ushort)utxo["n"];
            decimal utxo_value = (decimal)utxo["value"];

            //构建交易体
            ThinNeo.Transaction invokeTran = new ThinNeo.Transaction
            {
                type       = ThinNeo.TransactionType.InvocationTransaction,//调用合约
                attributes = new ThinNeo.Attribute[0],
                inputs     = new ThinNeo.TransactionInput[1],
                outputs    = new ThinNeo.TransactionOutput[1],
                extdata    = new ThinNeo.InvokeTransData()
            };
            //输入
            invokeTran.inputs[0] = new ThinNeo.TransactionInput
            {
                hash  = utxo_txid,
                index = utxo_n
            };
            //找零(输出)
            invokeTran.outputs[0] = new ThinNeo.TransactionOutput
            {
                assetId   = assetID,
                toAddress = ThinNeo.Helper.GetPublicKeyHashFromAddress(addrOut),
                value     = utxo_value //实际应该还要考虑大于10Gas的情况
            };
            //调用脚本与费用
            (invokeTran.extdata as ThinNeo.InvokeTransData).script = script.HexString2Bytes();
            (invokeTran.extdata as ThinNeo.InvokeTransData).gas    = scriptFee;

            using (var ms = new MemoryStream())
            {
                invokeTran.SerializeUnsigned(ms);
                return(ms.ToArray().ToHexString());
            }
        }
Ejemplo n.º 8
0
        public static ThinNeo.Transaction makeTran(Dictionary <string, List <Utxo> > dir_utxos, string targetaddr, ThinNeo.Hash256 assetid, decimal sendcount)
        {
            var tran = new ThinNeo.Transaction();

            tran.type    = ThinNeo.TransactionType.ContractTransaction;
            tran.version = 0;
            tran.extdata = null;

            tran.attributes = new ThinNeo.Attribute[0];
            List <ThinNeo.TransactionInput> list_inputs = new List <ThinNeo.TransactionInput>();

            tran.inputs = list_inputs.ToArray();
            List <ThinNeo.TransactionOutput> list_outputs = new List <ThinNeo.TransactionOutput>();

            tran.outputs = list_outputs.ToArray();

            return(tran);
        }
Ejemplo n.º 9
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);

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

                ////从已签名交易体分析出未签名交易体,并做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);
        }
Ejemplo n.º 10
0
        public string getClaimTxHex(string addrClaim, JObject claimGas)
        {
            var assetIDStr = "0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"; //选择GAS支付合约调用费用
            var assetID    = assetIDStr.Replace("0x", "").HexString2Bytes().Reverse().ToArray();

            //构建交易体
            ThinNeo.Transaction claimTran = new ThinNeo.Transaction
            {
                type       = ThinNeo.TransactionType.ClaimTransaction,//领取Gas合约
                attributes = new ThinNeo.Attribute[0],
                inputs     = new ThinNeo.TransactionInput[0],
                outputs    = new ThinNeo.TransactionOutput[1],
                extdata    = new ThinNeo.ClaimTransData()
            };

            claimTran.outputs[0] = new ThinNeo.TransactionOutput
            {
                assetId   = assetID,
                toAddress = ThinNeo.Helper.GetPublicKeyHashFromAddress(addrClaim),
                value     = (decimal)claimGas["gas"]
            };

            List <ThinNeo.TransactionInput> claimVins = new List <ThinNeo.TransactionInput>();

            foreach (JObject j in (JArray)claimGas["claims"])
            {
                claimVins.Add(new ThinNeo.TransactionInput {
                    hash  = ThinNeo.Debug.DebugTool.HexString2Bytes(((string)j["txid"]).Replace("0x", "")).Reverse().ToArray(),
                    index = (ushort)j["n"]
                });
            }

            (claimTran.extdata as ThinNeo.ClaimTransData).claims = claimVins.ToArray();

            using (var ms = new MemoryStream())
            {
                claimTran.SerializeUnsigned(ms);
                return(ms.ToArray().ToHexString());
            }
        }
Ejemplo n.º 11
0
        async Task test_transferNEO()
        {
            Console.WriteLine("transfer to:");
            var to = Console.ReadLine();

            Console.WriteLine("send mount:");
            var mount = Console.ReadLine();

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

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

            ThinNeo.Transaction tran = Helper.makeTran(newlist, to, new ThinNeo.Hash256(Config.id_NEO), decimal.Parse(mount));

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

            string poststr = System.Text.Encoding.UTF8.GetString(postdata);

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

            Console.WriteLine("得到的结果是:" + result);
        }
Ejemplo n.º 12
0
        public string getTransferTxHex(JArray utxoJA, string addrOut, string addrIn, string assetID, decimal amounts)
        {
            ////string findFliter = "{addr:'" + addrOut + "',used:''}";
            ////JArray outputJA = mh.GetData(mongodbConnStr, mongodbDatabase, "utxo", findFliter);

            ////linq查找指定asset
            //var query = from utxos in utxoJA.Children()
            //            where (string)utxos["asset"] == assetID
            //            orderby (decimal)utxos["value"] //descending
            //            select utxos;
            ////var utxo = query.ToList()[0];

            //JArray utxo2pay = new JArray();
            //decimal utxo_value = 0; //所有utxo总值
            //foreach (JObject utxo in query)
            //{
            //    if (utxo_value < amounts)//如utxo总值小于需支付则继续加utxo
            //    {
            //        utxo2pay.Add(utxo);
            //        utxo_value += (decimal)utxo["value"];
            //    }
            //    else { break; }//utxo总值大于等于需支付则跳出
            //}
            ////byte[] utxo_txid = ThinNeo.Debug.DebugTool.HexString2Bytes(((string)utxo["txid"]).Replace("0x", "")).Reverse().ToArray();
            ////ushort utxo_n = (ushort)utxo["n"];
            ////decimal utxo_value = (decimal)utxo["value"];

            //if (amounts > utxo_value)
            //{
            //    return string.Empty;
            //}

            JArray utxo2pay = getUtxo2Pay(utxoJA, addrOut, assetID, amounts);

            if (utxo2pay == new JArray())
            {
                return(string.Empty);
            }

            byte[] assetBytes = assetID.Replace("0x", "").HexString2Bytes().Reverse().ToArray();

            ThinNeo.Transaction lastTran;
            lastTran = new ThinNeo.Transaction
            {
                type       = ThinNeo.TransactionType.ContractTransaction,//转账
                attributes = new ThinNeo.Attribute[0],
                inputs     = new ThinNeo.TransactionInput[utxo2pay.Count]
            };
            //构造输入
            decimal utxo_value = 0;//所有utxo总金额
            int     i          = 0;

            foreach (var utxo in utxo2pay)
            {
                lastTran.inputs[i] = new ThinNeo.TransactionInput
                {
                    hash  = ((string)utxo["txid"]).Replace("0x", "").HexString2Bytes().Reverse().ToArray(),
                    index = (ushort)utxo["n"]
                };
                utxo_value += (decimal)utxo["value"];//加总所有utxo金额
                i++;
            }

            bool isNeedRefund = (utxo_value - amounts) > 0 ? true : false;

            if (isNeedRefund)
            {
                lastTran.outputs = new ThinNeo.TransactionOutput[2];
            }
            else
            {
                lastTran.outputs = new ThinNeo.TransactionOutput[1];
            }

            lastTran.outputs[0] = new ThinNeo.TransactionOutput
            {
                assetId   = assetBytes,
                toAddress = ThinNeo.Helper.GetPublicKeyHashFromAddress(addrIn),
                value     = amounts
            };//给对方转账

            if (isNeedRefund)
            {
                lastTran.outputs[1] = new ThinNeo.TransactionOutput
                {
                    assetId   = assetBytes,
                    toAddress = ThinNeo.Helper.GetPublicKeyHashFromAddress(addrOut),
                    value     = utxo_value - amounts
                };
            }//如需要,处理给自己找零

            using (var ms = new MemoryStream())
            {
                lastTran.SerializeUnsigned(ms);
                return(ms.ToArray().ToHexString());
            }
        }