Ejemplo n.º 1
0
        private void OnGetAccountState(UInt160 address)
        {
            string notice = "Notice: No vote record!";
            var    arg    = new JObject();

            arg["type"]  = "Hash160";
            arg["value"] = address.ToString();

            if (!OnInvokeWithResult(NativeContract.NEO.Hash, "getAccountState", out StackItem result, null, new JArray(arg)))
            {
                return;
            }
            Console.WriteLine();
            if (result.IsNull)
            {
                Console.WriteLine(notice);
                return;
            }
            var resJArray = (VM.Types.Array)result;

            foreach (StackItem value in resJArray)
            {
                if (value.IsNull)
                {
                    Console.WriteLine(notice);
                    return;
                }
            }
            var publickey = ECPoint.Parse(((ByteString)resJArray?[2])?.GetSpan().ToHexString(), ECCurve.Secp256r1);

            Console.WriteLine("Voted: " + Contract.CreateSignatureRedeemScript(publickey).ToScriptHash().ToAddress(NeoSystem.Settings.AddressVersion));
            Console.WriteLine("Amount: " + new BigDecimal(((Integer)resJArray?[0]).GetInteger(), NativeContract.NEO.Decimals));
            Console.WriteLine("Block: " + ((Integer)resJArray?[1]).GetInteger());
        }
Ejemplo n.º 2
0
        public override JObject ToJson()
        {
            JObject json = base.ToJson();

            json["hash"] = Hash.ToString();
            return(json);
        }
Ejemplo n.º 3
0
        private void BtnTransfer_Click(object sender, EventArgs e)
        {
            TransferFrm transferFrm = new TransferFrm(Account, AssetHash.ToString(), AssetSymbol, Decimals);

            transferFrm.Show();
            transferFrm.TopMost = true;
        }
Ejemplo n.º 4
0
        public void AddScript(byte[] script)
        {
            UInt160 scriptHash = script.ToScriptHash();

            scripts[scriptHash] = script;
            Console.WriteLine($"AddScript: scriptHash {scriptHash.ToString()} has {script.Length} bytes: {script.ToHexString()}");;
            storage[scriptHash] = new Storage();
        }
Ejemplo n.º 5
0
 public Task RpcInvokefunctionCommand
 (
     IPEndPoint endPoint, UInt160 scriptHash, string operation,
     [PromptCommandParameterBody(FromJson = true)] ContractParameter[] args
 )
 {
     return(RpcCallCommand(endPoint, "invokefunction", (new object[] { scriptHash.ToString(false), operation, args }.ToJson(false))));
 }
        private JObject ProcessGetAccountState(JArray _params)
        {
            UInt160 scriptHash    = GetScriptHashFromParam(_params[0].AsString());
            var     snapshot      = Blockchain.Singleton.GetSnapshot();
            var     assets        = snapshot.Assets.Find().ToList();
            var     txs           = snapshot.Transactions;
            var     unspentsCache = new DbCache <UserSystemAssetCoinOutputsKey, UserSystemAssetCoinOutputs>(
                _db, null, null, SystemAssetUnspentCoinsPrefix);

            JObject json = new JObject();

            JArray unpsentsArray = new JArray();

            json["unspent"]     = unpsentsArray;
            json["unclaimed"]   = ProcessGetUnclaimedTransactions(scriptHash);
            json["version"]     = "0";
            json["votes"]       = new JArray();
            json["frozen"]      = false; // TODO : get from blockchain state
            json["script_hash"] = scriptHash.ToString();

            foreach (var asset in assets)
            {
                var th = asset.Key;

                var    tokenId = GetTokenID(assets, th, txs);
                byte[] prefix = new[] { tokenId }.Concat(scriptHash.ToArray()).ToArray();

                var    unspents      = new JArray();
                Fixed8 total         = new Fixed8(0);
                var    unpsentsInTxs = unspentsCache.Find(prefix);
                foreach (var unspentInTx in unpsentsInTxs)
                {
                    if (!AddAccountUnspents(unspents, ref total, unspentInTx))
                    {
                        break;
                    }
                }

                foreach (var tmp in unspents)
                {
                    unpsentsArray.Add(tmp);
                }
            }

            AccountState account = Blockchain.Singleton.Store.GetAccounts().TryGet(scriptHash) ??
                                   new AccountState(scriptHash);

            json["balances"] = account.Balances.Select(p =>
            {
                JObject balance  = new JObject();
                balance["asset"] = p.Key.ToString();
                balance["value"] = p.Value.ToString();
                return(balance);
            }).ToArray();


            return(json);
        }
Ejemplo n.º 7
0
        public JObject ToJson()
        {
            var json = new JObject();

            json["scriptHash"] = ScriptHash.ToString();
            json["symbol"]     = Symbol;
            json["decimals"]   = Decimals;
            return(json);
        }
 public Variable GetVariable(IVariableContainerSession session, string name)
 {
     return(new Variable()
     {
         Name = name,
         Type = "StorageContext",
         Value = ScriptHash.ToString(),
     });
 }
Ejemplo n.º 9
0
        public override JObject ToJson()
        {
            JObject json = base.ToJson();

            json["MultiSigRedeemScript"] = MultiSigRedeemScript.ToString();
            json["ValidatorCount"]       = ValidatorCount;
            JArray jValidator = new JArray();

            for (int i = 0; i < WalletValidatorList.Count; i++)
            {
                JObject jMember = new JObject();
                jMember["PublicKey"] = WalletValidatorList[i].ToString();
                jMember["Address"]   = Wallet.ToAddress(Contract.CreateSignatureRedeemScript(WalletValidatorList[i]).ToScriptHash());
                jValidator.Add(jMember);
            }
            json["ValidatorList"] = jValidator;
            return(json);
        }
Ejemplo n.º 10
0
        /**
         * the value of scripthash has changed - attempt to evaluate and display contract details
         */
        private void txtScriptHash_TextChanged(object sender, EventArgs e)
        {
            ClearScriptDetails();

            if (txtScriptHash.Text.Trim().Equals(""))
            {
                // no scripthash has been provided - clenup just in case previous script values are still showing
                return;
            }

            if (!UInt160.TryParse(txtScriptHash.Text, out UInt160 parsedHash))
            {
                // invalid script hash, reset script details form and highlight field with red text
                txtScriptHash.ForeColor = Color.Red;
                return;
            }

            scriptHash = parsedHash;
            txtScriptHash.ForeColor = Color.Empty;

            ContractState contract = Blockchain.Default.GetContract(scriptHash);

            if (contract == null)
            {
                return;
            }

            // valid script hash was found on blockchain
            requiredParameters.AddRange(contract.Code.ParameterList.Select(p => new ContractParameter {
                Type = p
            }));
            requiredParameters.Add(new ContractParameter {
                Type = ContractParameterType.Array, Value = new List <ContractParameter>()
            });
            numRequiredParameters = requiredParameters.Count - 1;

            // populate contract details to form
            txtName.Text    = contract.Name;
            txtVersion.Text = contract.CodeVersion;
            txtAuthor.Text  = contract.Author;
            if (!contract.Email.Trim().Equals(""))
            {
                // append email address to author field
                txtAuthor.Text += $" ({contract.Email})";
            }
            txtDescription.Text = contract.Description;
            txtParamList.Text   = string.Join(", ", contract.Code.ParameterList);

            // show any required parameters for this contract
            InitParmTreeView();

            MainForm.Instance.scList.scListAdd(scriptHash.ToString(), true);

            btnClearScript.Enabled = true;
            UpdateScript();
        }
Ejemplo n.º 11
0
        public JObject ToJsonString()
        {
            JObject json = new JObject();

            json["assetId"]    = AssetId.ToString().Substring(2);
            json["value"]      = Value.ToString();
            json["scriptHash"] = ScriptHash.ToString().Substring(2);
            json["fee"]        = Fee.ToString();
            return(json);
        }
Ejemplo n.º 12
0
        public JObject ToJson(ushort index)
        {
            JObject json = new JObject();

            json["n"]          = index;
            json["asset"]      = AssetId.ToString();
            json["value"]      = Value.ToString();
            json["scripthash"] = ScriptHash.ToString();
            return(json);
        }
Ejemplo n.º 13
0
        /**
         * add a new list item to the event log tab
         */
        private void AddEventLog_Row(UInt160 scriptHash, string eventType, string eventMessage)
        {
            ContractState contract = Blockchain.Default.GetContract(scriptHash);

            if (contract == null)
            {
                return;
            }

            DateTime     localDateTime = DateTime.Now;
            ListViewItem newLogRow     = new ListViewItem(new[] {
                new ListViewItem.ListViewSubItem
                {
                    Name = "Time",
                    Text = localDateTime.ToString()
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "Block",
                    Text = Blockchain.Default.Height.ToString()
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "Script Hash",
                    Text = scriptHash.ToString()
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "Name",
                    Text = contract.Name.ToString()
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "Type",
                    Text = eventType
                },
                new ListViewItem.ListViewSubItem
                {
                    Name = "Message",
                    Text = eventMessage
                }
            }, -1);

            if (listView4.InvokeRequired)
            {
                // call is coming from a non ui thread
                AddEventLogCallback logCallback = new AddEventLogCallback(AddEventLog_RowItem);
                Invoke(logCallback, new object[] { newLogRow });
            }
            else
            {
                AddEventLog_RowItem(newLogRow);
            }
        }
Ejemplo n.º 14
0
        static Disassembly ToDisassembly(int sourceRef, UInt160 scriptHash, Script script, DebugInfo?debugInfo)
        {
            var digitCount = Utility.DigitCount(EnumerateInstructions(script).Last().address);
            var padString  = new string('0', digitCount);

            var sourceBuilder     = new StringBuilder();
            var addressMapBuilder = ImmutableDictionary.CreateBuilder <int, int>();
            var lineMapBuilder    = ImmutableDictionary.CreateBuilder <int, int>();

            if (debugInfo == null)
            {
                var line = 1;
                foreach (var t in EnumerateInstructions(script))
                {
                    AddSource(sourceBuilder, t.address, t.instruction, padString);
                    addressMapBuilder.Add(t.address, line);
                    lineMapBuilder.Add(line, t.address);
                    line++;
                }
            }
            else
            {
                var instructions = EnumerateInstructions(script).ToList();
                int line         = 1;
                foreach (var m in debugInfo.Methods.OrderBy(m => m.Range.Start))
                {
                    if (sourceBuilder.Length > 0)
                    {
                        sourceBuilder.Append("\n");
                    }
                    sourceBuilder.Append($"# Start Method {m.Namespace}.{m.Name}");
                    line++;

                    var methodInstructions = instructions
                                             .SkipWhile(t => t.address < m.Range.Start)
                                             .TakeWhile(t => t.address <= m.Range.End);
                    foreach (var t in methodInstructions)
                    {
                        AddSource(sourceBuilder, t.address, t.instruction, padString);
                        addressMapBuilder.Add(t.address, line);
                        lineMapBuilder.Add(line, t.address);
                        line++;
                    }
                    sourceBuilder.Append($"\n# End Method {m.Namespace}.{m.Name}");
                    line++;
                }
            }

            return(new Disassembly(
                       scriptHash.ToString(),
                       sourceBuilder.ToString(),
                       sourceRef,
                       addressMapBuilder.ToImmutable(),
                       lineMapBuilder.ToImmutable()));
 public static void RemoveBlockPool(UInt160 scripthash)
 {
     lock (block_pool)
     {
         if (block_pool.ContainsKey(scripthash))
         {
             block_pool.Remove(scripthash);
         }
         Console.WriteLine("Block item removed - " + scripthash.ToString());
     }
 }
Ejemplo n.º 16
0
        public JObject ToJson()
        {
            JObject json = new JObject();

            json["id"]            = Id;
            json["updatecounter"] = UpdateCounter;
            json["hash"]          = Hash.ToString();
            json["script"]        = Convert.ToBase64String(Script);
            json["manifest"]      = Manifest.ToJson();
            return(json);
        }
 public void AddBlockAddressToPool(UInt160 scripthash)
 {
     lock (block_pool)
     {
         if (!block_pool.ContainsKey(scripthash))
         {
             block_pool.Add(scripthash, Blockchain.Default.Height);
         }
         Console.WriteLine("Block item added - " + scripthash.ToString());
     }
 }
Ejemplo n.º 18
0
        public void getNativeNEP5Asset(MySqlConnection conn, UInt160 Contract)
        {
            try
            {
                ScriptBuilder sb = new ScriptBuilder();

                sb.EmitSysCall("Zoro.NativeNEP5.Call", "TotalSupply", Contract);
                sb.EmitSysCall("Zoro.NativeNEP5.Call", "Name", Contract);
                sb.EmitSysCall("Zoro.NativeNEP5.Call", "Symbol", Contract);
                sb.EmitSysCall("Zoro.NativeNEP5.Call", "Decimals", Contract);

                IO.Json.JObject jObject;

                Blockchain        blockchain = ZoroChainSystem.Singleton.GetBlockchain(ChainHash);;
                ApplicationEngine engine     = ApplicationEngine.Run(sb.ToArray(), blockchain, testMode: true);
                if (engine.State.HasFlag(VMState.FAULT))
                {
                    return;
                }

                JArray jStack = new JArray(engine.ResultStack.Select(p => p.ToParameter().ToJson()));

                string totalSupply = jStack[0]["type"].AsString() == "ByteArray" ? new BigInteger(SpiderHelper.HexString2Bytes(jStack[0]["value"].AsString())).ToString() : jStack[0]["value"].AsString();
                string name        = jStack[1]["type"].AsString() == "ByteArray" ? Encoding.UTF8.GetString(SpiderHelper.HexString2Bytes(jStack[1]["value"].AsString())) : jStack[1]["value"].AsString();
                string symbol      = jStack[2]["type"].AsString() == "ByteArray" ? Encoding.UTF8.GetString(SpiderHelper.HexString2Bytes(jStack[2]["value"].AsString())) : jStack[2]["value"].AsString();
                string decimals    = jStack[3]["type"].AsString() == "ByteArray" ? BigInteger.Parse(jStack[3]["value"].AsString()).ToString() : jStack[3]["value"].AsString();

                //BCT没有限制,可以随意增发
                if (symbol == "BCT")
                {
                    totalSupply = "0";
                }

                List <string> slist = new List <string>();
                slist.Add(Contract.ToString());
                slist.Add(totalSupply);
                slist.Add(name);
                slist.Add(symbol);
                slist.Add(decimals);


                //这里有个bug,我们的bcp会因为转账而增长
                {
                    MysqlConn.ExecuteDataInsert(conn, DataTableName, slist);
                }

                LogConfig.Log($"SaveNEP5Asset {ChainHash} {Contract}", LogConfig.LogLevel.Info, ChainHash.ToString());
            }
            catch (Exception e)
            {
                LogConfig.Log($"error occured when call invokescript, chainhash:{ChainHash}, nep5contract:{Contract.ToString()}, reason:{e.Message}", LogConfig.LogLevel.Error);
                throw e;
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Converts the contract to a JSON object.
 /// </summary>
 /// <returns>The contract represented by a JSON object.</returns>
 public JObject ToJson()
 {
     return(new JObject
     {
         ["id"] = Id,
         ["updatecounter"] = UpdateCounter,
         ["hash"] = Hash.ToString(),
         ["nef"] = Nef.ToJson(),
         ["manifest"] = Manifest.ToJson()
     });
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Converts the token to a JSON object.
 /// </summary>
 /// <returns>The token represented by a JSON object.</returns>
 public JObject ToJson()
 {
     return(new JObject
     {
         ["hash"] = Hash.ToString(),
         ["method"] = Method,
         ["paramcount"] = ParametersCount,
         ["hasreturnvalue"] = HasReturnValue,
         ["callflags"] = CallFlags
     });
 }
Ejemplo n.º 21
0
 public JObject ToJson()
 {
     JObject jo = new JObject();
     jo["BlockNumber"] = BlockNumber;
     jo["TransactionHash"] = TransactionHash.ToString();
     jo["LogIndex"] = LogIndex;
     jo["Asset"] = Asset.ToString();
     jo["From"] = From.ToString();
     jo["To"] = To.ToString();
     jo["Value"] = Value;
     return jo;
 }
Ejemplo n.º 22
0
        public void Test_UInt160_Parse()
        {
            string  uint160strbig = "0x0001020304050607080900010203040506070809";
            UInt160 num1          = UInt160.Parse(uint160strbig);

            num1.ToString().Should().Be("0x0001020304050607080900010203040506070809");

            string  uint160strbig2 = "0X0001020304050607080900010203040506070809";
            UInt160 num2           = UInt160.Parse(uint160strbig2);

            num2.ToString().Should().Be("0x0001020304050607080900010203040506070809");
        }
Ejemplo n.º 23
0
        public void Start(int startHeight)
        {
            this.currentHeight = startHeight >= 0 ? (uint)startHeight : listHeight.getHeight(chainHash.ToString());
            checkHeight        = currentHeight;

            LogConfig.Log($"Starting chain spider {chainHash} {currentHeight}", LogConfig.LogLevel.Warning);

            task = Task.Factory.StartNew(() =>
            {
                Process();
            });
        }
Ejemplo n.º 24
0
        string GetContractName(UInt160 scriptHash)
        {
            if (neoSystem != null)
            {
                var contract = NativeContract.ContractManagement.GetContract(neoSystem.StoreView, scriptHash);
                if (contract != null)
                {
                    return(contract.Manifest.Name);
                }
            }

            return(scriptHash.ToString());
        }
Ejemplo n.º 25
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType != typeof(string))
            {
                throw new NotSupportedException();
            }

            return(value switch
            {
                UInt160 i => i.ToString(),
                UInt256 i => i.ToString(),
                _ => null,
            });
Ejemplo n.º 26
0
        private void AddAsset(Snapshot snapshot, UInt160 scriptHash)
        {
            JObject    asset = new JObject();
            string     n     = GetAssetString(snapshot, scriptHash, "name");
            string     s     = GetAssetString(snapshot, scriptHash, "symbol");
            BigInteger d     = GetAssetInteger(snapshot, scriptHash, "decimals");

            if (n.Length > 0 && s.Length > 0)
            {
                ContractState contract = snapshot.Contracts.TryGet(scriptHash);
                asset["scripthash"] = scriptHash.ToString();
                asset["firstseen"]  = snapshot.Height;
                asset["name"]       = n;
                asset["symbol"]     = s;
                asset["decimals"]   = d.ToString();
                asset["state"]      = contract.ToJson();
            }
            Document b = Document.FromJson(asset.ToString());

            AssetsTable.UpdateItemAsync(b);
            Assets.Add(scriptHash.ToString());
        }
Ejemplo n.º 27
0
        public InvokeContractDialog(UInt160 scriptHash)
        {
            InitializeComponent();

            txtFeeNetwork.Validating += TxtFeeNetwork_Validating;

            tabControl1.SelectedTab = tabPage1;


            textBox1.Text = scriptHash.ToString();

            button1_Click(button1, new EventArgs {
            });
        }
Ejemplo n.º 28
0
        public static JObject[] MakeFindStatesParams(UInt256 rootHash, UInt160 scriptHash, ReadOnlySpan <byte> prefix, ReadOnlySpan <byte> from = default, int?count = null)
        {
            var @params = new JObject[count.HasValue ? 5 : 4];

            @params[0] = rootHash.ToString();
            @params[1] = scriptHash.ToString();
            @params[2] = Convert.ToBase64String(prefix);
            @params[3] = Convert.ToBase64String(from);
            if (count.HasValue)
            {
                @params[4] = count.Value;
            }
            return(@params);
        }
Ejemplo n.º 29
0
 private void button7_Click(object sender, EventArgs e)
 {
     if (openFileDialog2.ShowDialog() != DialogResult.OK)
     {
         return;
     }
     abi           = JObject.Parse(File.ReadAllText(openFileDialog2.FileName));
     script_hash   = UInt160.Parse(abi["hash"].AsString());
     textBox8.Text = script_hash.ToString();
     comboBox1.Items.Clear();
     comboBox1.Items.AddRange(((JArray)abi["functions"]).Select(p => p["name"].AsString()).ToArray());
     textBox9.Clear();
     button8.Enabled = false;
 }
Ejemplo n.º 30
0
        public (Source source, int line) GetSource(byte[] scriptHash, int instructionPointer)
        {
            var _scriptHash = new UInt160(scriptHash);
            var hashCode    = _scriptHash.GetHashCode();
            var name        = _scriptHash.ToString();
            var source      = new Source()
            {
                SourceReference = hashCode,
                Name            = name,
                Path            = name,
                AdapterData     = name,
            };

            return(source, sourceMap[hashCode][instructionPointer]);