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
        //增加个人账户见证人(就是用这个人的私钥对交易签个名,signdata传进来)
        public void AddWitness(byte[] signdata, byte[] pubkey, string addrs)
        {
            {//额外的验证
                byte[] msg = null;
                using (var ms = new System.IO.MemoryStream())
                {
                    SerializeUnsigned(ms);
                    msg = ms.ToArray();
                }
                bool bsign = ThinNeo.Helper.VerifySignature(msg, signdata, pubkey);
                if (bsign == false)
                {
                    throw new Exception("wrong sign");
                }

                var addr = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
                if (addr != addrs)
                {
                    throw new Exception("wrong script");
                }
            }

            var vscript = ThinNeo.Helper.GetScriptFromPublicKey(pubkey);

            //iscript 对个人账户见证人他是一条pushbytes 指令

            var sb = new ThinNeo.ScriptBuilder();

            sb.EmitPushBytes(signdata);

            var iscript = sb.ToArray();

            AddWitnessScript(vscript, iscript);
        }
Ejemplo n.º 4
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.º 5
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());
            }
        }
        ThinNeo.Transaction signAndBroadcast()
        {
            ThinNeo.Transaction trans = GenTran();
            if (trans == null)
            {
                return(null);
            }

            var msg = trans.GetMessage();

            trans.witnesses = new ThinNeo.Witness[this.listWitness.Items.Count];
            //检查签名
            for (var i = 0; i < listWitness.Items.Count; i++)
            {
                var item    = listWitness.Items[i] as ThinNeo.Witness;
                var witness = new ThinNeo.Witness();
                witness.VerificationScript = item.VerificationScript;
                witness.InvocationScript   = item.InvocationScript;
                //autoresign
                {
                    var pubkey = ThinNeo.Helper.GetPublicKeyFromPrivateKey(this.privatekey);
                    var addr   = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
                    if (item.Address == addr)
                    {
                        var signdata = ThinNeo.Helper.Sign(msg, 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 str = Tools.CoinTool.RecordTran(trans);
                this.UpdateTranData();

                Tools.CoinTool.SaveRecord();
                MessageBox.Show("txid=" + str);
                ClearTran();
                return(trans);
            }
            else
            {
                MessageBox.Show("transaction error");
                ClearTran();
                return(null);
            }
        }
Ejemplo n.º 7
0
        public void FillRaw()
        {
            this.txraw.witnesses = new ThinNeo.Witness[keyinfos.Count];
            List <KeyInfo> keys = new List <KeyInfo>();

            foreach (var key in keyinfos)
            {
                keys.Add(key.Value);
            }
            //keys 這個需要排序
            for (var i = 0; i < keys.Count; i++)
            {
                this.txraw.witnesses[i] = new ThinNeo.Witness();
                if (keys[i].type == KeyType.Simple)
                {
                    //算出vscript
                    this.txraw.witnesses[i].VerificationScript = ThinNeo.Helper.GetScriptFromPublicKey(keys[i].pubkey);
                    using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
                    {
                        sb.EmitPushBytes(keys[i].signdata[0]);
                        this.txraw.witnesses[i].InvocationScript = sb.ToArray();
                    }
                }
                if (keys[i].type == KeyType.MultiSign)
                {
                    //算出vscript
                    this.txraw.witnesses[i].VerificationScript = keys[i].MultiSignKey.GetMultiContract();
                    List <byte[]> signs = new List <byte[]>();
                    foreach (var s in keys[i].signdata)
                    {
                        if (s != null && s.Length > 0)
                        {
                            signs.Add(s);
                        }
                    }
                    //?這個signs 要不要倒序?试一试
                    using (ThinNeo.ScriptBuilder sb = new ThinNeo.ScriptBuilder())
                    {
                        for (var iss = 0; iss < keys[i].MultiSignKey.MKey_NeedCount; iss++)
                        {
                            sb.EmitPushBytes(signs[iss]);
                        }
                        this.txraw.witnesses[i].InvocationScript = sb.ToArray();
                    }
                }
            }
        }
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
 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.º 10
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");
            }
        }
Ejemplo n.º 11
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.º 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
        public async Task <byte[]> MakeScript(bool sign)
        {
            var payaddr = label_addr.Text;
            var paygas  = 0.001;
            var utxos   = await Demo.Helper.GetUtxosToPay(api, payaddr, id_GAS, paygas);

            if (utxos.Count == 0)
            {
                MessageBox.Show("you do not have gas for sendraw.");
                return(null);
            }
            var asset = listAsset.SelectedItem as Asset;

            if (asset == null || asset.isnep5 == false)
            {
                MessageBox.Show("this is not a nep5");
                return(null);
            }
            var targetaddr    = txt_get_addr.Text;
            var targetbalance = double.Parse(txt_get_balance.Text);

            for (var i = 0; i < asset.decimals; i++)
            {
                targetbalance *= 10;
            }


            if (sign)
            {
                var paywif  = txt_wifGetter.Text;
                var prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(paywif);
                var pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
                var address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);
                if (address != payaddr)
                {
                    MessageBox.Show("error wif for pubkey in lock contract.");
                    return(null);
                }
            }
            //MakeTran
            ThinNeo.Transaction tran = null;
            {
                byte[] script = null;
                using (var sb = new ThinNeo.ScriptBuilder())
                {
                    var array = new MyJson.JsonNode_Array();
                    array.AddArrayValue("(addr)" + address_LockContract);               //from
                    array.AddArrayValue("(addr)" + targetaddr);                         //to
                    array.AddArrayValue("(int)" + (ulong)targetbalance);                //value
                    sb.EmitParamJson(array);                                            //参数倒序入
                    sb.EmitParamJson(new MyJson.JsonNode_ValueString("(str)transfer")); //参数倒序入
                    ThinNeo.Hash160 shash = new ThinNeo.Hash160(asset.assetID);
                    sb.EmitAppCall(shash);                                              //nep5脚本
                    script = sb.ToArray();
                }

                tran      = Demo.Helper.makeTran(null, payaddr, new ThinNeo.Hash256(id_GAS), 0, (decimal)0.001, utxos, payaddr);
                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_LockContract;
            }

            if (sign)
            {
                var paywif  = txt_wifGetter.Text;
                var prikey  = ThinNeo.Helper.GetPrivateKeyFromWIF(paywif);
                var pubkey  = ThinNeo.Helper.GetPublicKeyFromPrivateKey(prikey);
                var address = ThinNeo.Helper.GetAddressFromPublicKey(pubkey);

                ////sign
                var signdata = ThinNeo.Helper.Sign(tran.GetMessage(), prikey);
                tran.AddWitness(signdata, pubkey, address);

                var sb2 = new ThinNeo.ScriptBuilder();
                sb2.EmitPushBytes(signdata);

                var iscript = sb2.ToArray();
                tran.AddWitnessScript(script_LockContract, iscript);
                return(tran.GetRawData());
            }
            else
            {
                return(tran.GetMessage());
            }
        }
        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);
        }