Ejemplo n.º 1
0
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
            sb.EmitPushString(iDescription.Text);
            sb.EmitPushString(iEmail.Text);
            sb.EmitPushString(iAuthor.Text);
            sb.EmitPushString(iVersion.Text);
            sb.EmitPushString(iName.Text);
            int need_storage = iStorage.IsChecked == true ? 1 : 0;
            int need_nep4    = iDyncall.IsChecked == true ? 2 : 0;

            sb.EmitPushNumber(need_storage | need_nep4);
            var br = ThinNeo.Helper.HexString2Bytes(iRType.Text);
            var bp = ThinNeo.Helper.HexString2Bytes(iPList.Text);

            sb.EmitPushBytes(br);
            sb.EmitPushBytes(bp);
            var _ss = ThinNeo.Helper.HexString2Bytes(this.asmBinText.Text);

            sb.EmitPushBytes(_ss);

            sb.EmitSysCall("Neo.Contract.Create");

            //sb.EmitSysCall("Neo.Contract.Create", script, parameter_list, return_type, need_storage | need_nep4, name, version, author, email, description);
            this.script = sb.ToArray();

            this.DialogResult = true;
        }
Ejemplo n.º 2
0
 void dapp_EmitParam(ThinNeo.ScriptBuilder sb, MyJson.IJsonNode param)
 {
     if (param is MyJson.JsonNode_ValueNumber)//bool 或小整数
     {
         sb.EmitParamJson(param);
     }
     else if (param is MyJson.JsonNode_Array)
     {
         var list = param.AsList();
         for (var i = list.Count - 1; i >= 0; i--)
         {
             dapp_EmitParam(sb, list[i]);
         }
         sb.EmitPushNumber(param.AsList().Count);
         sb.Emit(ThinNeo.VM.OpCode.PACK);
     }
     else if (param is MyJson.JsonNode_ValueString)//复杂格式
     {
         var str   = param.AsString();
         var bytes = dapp_getCallParam(str);
         sb.EmitPushBytes(bytes);
     }
     else
     {
         throw new Exception("should not pass a {}");
     }
 }
Ejemplo n.º 3
0
        public void NeoTransfer()
        {
            byte[] prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(wif);
            var    pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
            var    address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

            using (var sb = new ThinNeo.ScriptBuilder())
            {
                var array = new MyJson.JsonNode_Array();
                array.AddArrayValue("(addr)" + from);
                array.AddArrayValue("(addr)" + "AMjCDmrbfcBxGPitHcdrUYRyPXD7DfC52c");//NeoBank address   AMjCDmrbfcBxGPitHcdrUYRyPXD7DfC52c
                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("0x04e31cee0443bb916534dad2adf508458920e66d")); //nep5脚本
                script = sb.ToArray();
            }

            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    = MakeRpcUrlPost(NeoRpcUrl, "sendrawtransaction", out postdata, new MyJson.JsonNode_ValueString(rawdata));
            var    result = HttpPost(url, postdata);

            Console.WriteLine(result + " txid: " + txid);
            return(result);
        }
Ejemplo n.º 4
0
        //private void updateHasSendGas(string mongodbConnStr, string mongodbDatabase, string addr, decimal gas)
        //{
        //    string findFliter = "{addr:" + addr + "}";
        //    JArray array = mh.GetData(mongodbConnStr, mongodbDatabase, "HasSendGas", findFliter);
        //    JObject ob = new JObject();
        //    if (array.Count > 0)
        //    {
        //        ob = (JObject)array[0];
        //        decimal remainGas = (decimal)ob["gas"];
        //        if (remainGas >= 0)
        //        {

        //        }
        //    }
        //}

        public JObject claimContract(string mongodbConnStr, string mongodbDatabase, string conAddr, string addrClaim, string url, string hash)
        {
            JObject claimGas = getClaimGas(mongodbConnStr, mongodbDatabase, conAddr, true);

            string unsignHexTx = tx.getClaimTxHex(addrClaim, claimGas);

            byte[] txScript = unsignHexTx.HexString2Bytes();

            ThinNeo.Transaction claimTran = new ThinNeo.Transaction();
            claimTran.Deserialize(new MemoryStream(txScript));

            JObject contract = ct.getContractState(url, hash);

            //做智能合约的签名
            byte[] iscript = null;
            using (var sb = new ThinNeo.ScriptBuilder())
            {
                sb.EmitPushString("whatever");
                sb.EmitPushNumber(250);
                iscript = sb.ToArray();
            }
            byte[] conbytes = ThinNeo.Debug.DebugTool.HexString2Bytes((string)contract["script"]);
            claimTran.AddWitnessScript(conbytes, iscript);

            var trandata    = claimTran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

            JObject result = tx.sendrawtransaction(url, strtrandata);
            bool    re     = (bool)result["sendrawtransactionresult"];

            Console.WriteLine("得到的结果是:" + re);
            if (re)
            {
                Console.WriteLine("txid:" + (string)result["txid"]);
                try
                {
                    //处理提取后的utxo,记录每笔utxo原始账户信息
                    new Thread(o =>
                    {
                        proClaimData(mongodbConnStr, mongodbDatabase, claimGas);
                    })
                    {
                        IsBackground = true
                    }
                    .Start();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Console.WriteLine("errorMessage:" + (string)result["errorMessage"]);
            }
            return(result);
        }
Ejemplo n.º 5
0
 public byte[] GetMultiContract()
 {
     if (!(1 <= this.MKey_NeedCount && MKey_NeedCount <= MKey_Pubkeys.Count && MKey_Pubkeys.Count <= 1024))
     {
         throw new ArgumentException();
     }
     using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
     {
         sb.EmitPushNumber(MKey_NeedCount);
         foreach (var pkey in this.MKey_Pubkeys)
         {
             sb.EmitPushBytes(pkey);
         }
         sb.EmitPushNumber(MKey_Pubkeys.Count);
         sb.Emit(ThinNeo.VM.OpCode.CHECKMULTISIG);
         return(sb.ToArray());
     }
 }
Ejemplo n.º 6
0
        static byte[] createNep5FindScript(string _assetid)
        {
            var asset = ThinNeo.Helper.HexString2Bytes(_assetid);

            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
            sb.EmitPushNumber(0);
            sb.Emit(ThinNeo.VM.OpCode.PACK);
            sb.EmitPushString("name"); //name//totalSupply//symbol//decimals
            sb.EmitAppCall(asset.Reverse().ToArray());

            sb.EmitPushNumber(0);
            sb.Emit(ThinNeo.VM.OpCode.PACK);
            sb.EmitPushString("symbol"); //name//totalSupply//symbol//decimals
            sb.EmitAppCall(asset.Reverse().ToArray());

            sb.EmitPushNumber(0);
            sb.Emit(ThinNeo.VM.OpCode.PACK);
            sb.EmitPushString("decimals"); //name//totalSupply//symbol//decimals
            sb.EmitAppCall(asset.Reverse().ToArray());

            return(sb.ToArray());
        }
Ejemplo n.º 7
0
        public JObject publishContractForTest(string neoCliJsonRPCUrl, string avmHexstring, JObject infoJ)
        {
            string cName            = (string)infoJ["cName"];
            string cVersion         = (string)infoJ["cVersion"];
            string cAuthor          = (string)infoJ["cAuthor"];
            string cEmail           = (string)infoJ["cEmail"];
            string cDescription     = (string)infoJ["cDescription"];
            bool   iStorage         = (bool)infoJ["iStorage"];
            bool   iDyncall         = (bool)infoJ["iDyncall"];
            string inputParamsType  = (string)infoJ["inputParamsType"];
            string outputParamsType = (string)infoJ["outputParamsType"];

            //实例化脚本构造器
            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
            //加入合约基本信息
            sb.EmitPushString(cDescription);
            sb.EmitPushString(cEmail);
            sb.EmitPushString(cAuthor);
            sb.EmitPushString(cVersion);
            sb.EmitPushString(cName);

            //加入是否需要私有存储区、是否需要动态合约调用信息
            int need_storage = iStorage == true ? 1 : 0;
            int need_nep4    = iDyncall == true ? 2 : 0;

            sb.EmitPushNumber(need_storage | need_nep4);//二进制或操作

            //加入输入输出参数类型信息
            var outputType = ThinNeo.Helper.HexString2Bytes(outputParamsType);
            var inputType  = ThinNeo.Helper.HexString2Bytes(inputParamsType);

            sb.EmitPushBytes(outputType);
            sb.EmitPushBytes(inputType);

            //加入合约编译后二进制码
            var contractScript = ThinNeo.Helper.HexString2Bytes(avmHexstring);

            sb.EmitPushBytes(contractScript);

            sb.EmitSysCall("Neo.Contract.Create");

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

            //调用cli RPC 用neoVM试运行,并获得费用估算
            return(invokeScript(neoCliJsonRPCUrl, scriptPublish));
        }
Ejemplo n.º 8
0
        decimal rpc_getNep5Balance(string nep5asset)
        {
            //make callscript
            var pubkey     = ThinNeo.Helper.GetPublicKeyFromPrivateKey(this.privatekey);
            var pubkeyhash = ThinNeo.Helper.GetScriptHashFromPublicKey(pubkey);

            var asset = ThinNeo.Helper.HexString2Bytes(nep5asset);

            ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder();
            sb.EmitPushBytes(pubkeyhash);
            sb.EmitPushNumber(1);
            sb.Emit(ThinNeo.VM.OpCode.PACK);
            sb.EmitPushString("balanceOf"); //name//totalSupply//symbol//decimals
            sb.EmitAppCall(asset.Reverse().ToArray());

            var nep5 = Tools.CoinTool.assetNep5[nep5asset];

            var symbol    = ThinNeo.Helper.Bytes2HexString(sb.ToArray());
            var str       = WWW.MakeRpcUrl(labelRPC.Text, "invokescript", new MyJson.JsonNode_ValueString(symbol));
            var resultstr = WWW.GetWithDialog(this, str);
            var json      = MyJson.Parse(resultstr).AsDict()["result"].AsDict();

            if (json["state"].AsString().Contains("HALT") == false)
            {
                throw new Exception("error state");
            }
            var     value    = json["stack"].AsList()[0].AsDict();
            decimal outvalue = 0;

            if (value["type"].AsString() == "Integer")
            {
                outvalue = decimal.Parse(value["value"].AsString());
            }
            else
            {
                var bts = ThinNeo.Helper.HexString2Bytes(value["value"].AsString());
                var bi  = new System.Numerics.BigInteger(bts);
                outvalue = (decimal)bi;
            }
            for (var i = 0; i < nep5.decimals; i++)
            {
                outvalue /= 10;
            }
            return(outvalue);
        }
Ejemplo n.º 9
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());
            }
        }
Ejemplo n.º 10
0
        public JObject claimContract2(string mongodbConnStr, string mongodbDatabase, string conAddr, string addrClaim, string url, string hash)
        {
            JObject claimGas = getClaimGas(mongodbConnStr, mongodbDatabase, conAddr, true);

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

            JObject contract = ct.getContractState(url, hash);

            //做智能合约的签名
            byte[] iscript = null;
            using (var sb = new ThinNeo.ScriptBuilder())
            {
                sb.EmitPushString("whatever");
                sb.EmitPushNumber(250);
                iscript = sb.ToArray();
            }
            byte[] conbytes = ThinNeo.Debug.DebugTool.HexString2Bytes((string)contract["script"]);
            claimTran.AddWitnessScript(conbytes, iscript);

            var trandata    = claimTran.GetRawData();
            var strtrandata = ThinNeo.Helper.Bytes2HexString(trandata);

            JObject result = tx.sendrawtransaction(url, strtrandata);
            bool    re     = (bool)result["sendrawtransactionresult"];

            Console.WriteLine("得到的结果是:" + re);
            if (re)
            {
                Console.WriteLine("txid:" + (string)result["txid"]);
            }
            else
            {
                Console.WriteLine("errorMessage:" + (string)result["errorMessage"]);
            }
            return(result);
        }
Ejemplo n.º 11
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;
                }
            }
        }
Ejemplo n.º 12
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //显示lock合约地址
            var lockbin = ThinNeo.Helper.HexString2Bytes(lockscript);
            var hash    = ThinNeo.Helper.GetScriptHashFromScript(lockbin);
            var hashstr = hash.ToString();

            //addr d3cce84d0800172d09c88ccad61130611bd047a4
            label_lockscript.Text = hashstr;


            //显示公钥-》地址
            var pubkey = ThinNeo.Helper.HexString2Bytes(this.txt_pubkey.Text);

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

            label_addr.Text = addr;

            //默认提取地址就是私钥地址
            txt_get_addr.Text = addr;
            //显示日期
            var date = datepicker.SelectedDate;

            if (date == null)
            {
                date = datepicker.DisplayDate;
            }
            var hour    = int.Parse(txt_time.Text.Split(':')[0]);
            var datemix = new DateTime(date.Value.Year, date.Value.Month, date.Value.Day,
                                       hour,
                                       date.Value.Minute,
                                       date.Value.Second);

            label_time.Text    = datemix.ToLongDateString() + " " + datemix.ToLongTimeString();
            label_timeutc.Text = datemix.ToUniversalTime().ToLongDateString() + " " + datemix.ToUniversalTime().ToLongTimeString();


            //生成脚本
            var timestamp = ToTimestamp(datemix);

            byte[] script;
            //on genbutton
            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                sb.EmitPushBytes(pubkey);     //sb.EmitPush(GetKey().PublicKey);

                sb.EmitPushNumber(timestamp); //sb.EmitPush(timestamp);

                //// Lock 2.0 in mainnet tx:4e84015258880ced0387f34842b1d96f605b9cc78b308e1f0d876933c2c9134b
                sb.EmitAppCall(hash); // script hash  = d3cce84d0800172d09c88ccad61130611bd047a4
                //return Contract.Create(new[] { ContractParameterType.Signature }, sb.ToArray());
                script = sb.ToArray();
            }


            var callscripthash = ThinNeo.Helper.GetScriptHashFromScript(script);
            var contractaddr   = ThinNeo.Helper.GetAddressFromScriptHash(callscripthash);

            this.txt_contract.Text = ThinNeo.Helper.Bytes2HexString(script);
            this.txt_addrout.Text  = contractaddr;


            //from addr
            this.txt_get_srcaddr.Text = contractaddr;

            address_LockContract    = contractaddr;
            script_LockContract     = script;
            scripthash_LockContract = callscripthash;
        }
Ejemplo n.º 13
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());
                }
            }
        }
        async Task SetLockAccount(UTC_Time time)
        {
            //lockscript;
            var lockbin = ThinNeo.Helper.HexString2Bytes(lockscript);
            var hash    = ThinNeo.Helper.GetScriptHashFromScript(lockbin);
            var hashstr = hash.ToString();

            //生成脚本
            var timestamp = time.ToTimestamp();

            byte[] script;
            //on genbutton
            using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
            {
                sb.EmitPushBytes(main_pubkey); //sb.EmitPush(GetKey().PublicKey);

                sb.EmitPushNumber(timestamp);  //sb.EmitPush(timestamp);

                //// Lock 2.0 in mainnet tx:4e84015258880ced0387f34842b1d96f605b9cc78b308e1f0d876933c2c9134b
                sb.EmitAppCall(hash); // script hash  = d3cce84d0800172d09c88ccad61130611bd047a4
                //return Contract.Create(new[] { ContractParameterType.Signature }, sb.ToArray());
                script = sb.ToArray();
            }


            var    callscripthash = ThinNeo.Helper.GetScriptHashFromScript(script);
            var    contractaddr   = ThinNeo.Helper.GetAddressFromScriptHash(callscripthash);
            string outline        = time.Time_UTC.ToLongDateString() + " : " + contractaddr + "  PET=";



            {//fill nep5 balance.
                var urlb     = Demo.Helper.MakeRpcUrlPost(api, "getnep5balanceofaddress", out byte[] databsub, new MyJson.JsonNode_ValueString(id_PET), new MyJson.JsonNode_ValueString(contractaddr));
                var jsonbsub = await Demo.Helper.HttpPost(urlb, databsub);

                var jsonbsubb = Newtonsoft.Json.Linq.JObject.Parse(jsonbsub);
                outline += (double)jsonbsubb["result"][0]["nep5balance"];

                //var url2 = Demo.Helper.MakeRpcUrlPost(api, "getallnep5assetofaddress", out byte[] data2, new MyJson.JsonNode_ValueString(contractaddr));
                //var json = await Demo.Helper.HttpPost(url2, data2);
                //var jsonb = Newtonsoft.Json.Linq.JObject.Parse(json);
                //var result = (jsonb["result"] as JArray);
                //if (result != null)
                //{
                //    foreach (JObject item in result)
                //    {
                //        var asset = new Asset();
                //        asset.isnep5 = true;
                //        asset.assetID = (string)item["assetid"];
                //        var urlsub = Demo.Helper.MakeRpcUrlPost(api, "getnep5asset", out byte[] datasub, new MyJson.JsonNode_ValueString(asset.assetID));
                //        var jsonsub = await Demo.Helper.HttpPost(urlsub, datasub);
                //        var jsonsubb = Newtonsoft.Json.Linq.JObject.Parse(jsonsub);
                //        asset.name = (string)jsonsubb["result"][0]["name"];
                //        asset.decimals = (int)jsonsubb["result"][0]["decimals"];

                //        var urlb = Demo.Helper.MakeRpcUrlPost(api, "getnep5balanceofaddress", out byte[] databsub, new MyJson.JsonNode_ValueString(asset.assetID), new MyJson.JsonNode_ValueString(contractaddr));
                //        var jsonbsub = await Demo.Helper.HttpPost(urlb, databsub);
                //        var jsonbsubb = Newtonsoft.Json.Linq.JObject.Parse(jsonbsub);
                //        asset.balance = (double)jsonbsubb["result"][0]["nep5balance"];

                //    }
                //}
            }

            this.listLocks.Items.Add(outline);
            var link = new Button();

            link.Width   = 100;
            link.Height  = 20;
            link.Content = "show in browser";
            link.Click  += (s, e) =>
            {
                System.Diagnostics.Process.Start("https://neotracker.io/address/" + contractaddr);
            };
            this.listLocks.Items.Add(link);
        }