/// <summary>
        /// Converts a big end script hash to its equivalent address
        /// </summary>
        /// <param name="script">
        /// String that represents the scripthash to be converted
        /// </param>
        /// <returns>
        /// Returns null when the string does not represent an scripthash;
        /// otherwise, returns the string that represents the converted address
        /// </returns>
        private string ScripthashToAddress(string script)
        {
            try
            {
                UInt160 scriptHash;
                if (script.StartsWith("0x"))
                {
                    if (!UInt160.TryParse(script, out scriptHash))
                    {
                        return(null);
                    }
                }
                else
                {
                    if (!UInt160.TryParse(script, out UInt160 littleEndScript))
                    {
                        return(null);
                    }
                    string bigEndScript = littleEndScript.ToArray().ToHexString();
                    if (!UInt160.TryParse(bigEndScript, out scriptHash))
                    {
                        return(null);
                    }
                }

                var hexScript = scriptHash.ToAddress(NeoSystem.Settings.AddressVersion);
                return(hexScript);
            }
            catch
            {
                return(null);
            }
        }
Exemple #2
0
        private void scListLoad()
        {
            if (listLoaded)
            {
                return;
            }

            if (!File.Exists(smartContractJSON))
            {
                File.Create(smartContractJSON).Close();
                return;
            }

            listLoaded = true;

            UInt160 ignore;
            JavaScriptSerializer jsonHelper = new JavaScriptSerializer();

            smartContractList = jsonHelper.Deserialize <List <Dictionary <string, string> > >(File.ReadAllText(smartContractJSON));
            if (smartContractList == null)
            {
                smartContractList = new List <Dictionary <string, string> >();
            }
            foreach (Dictionary <string, string> contract in smartContractList)
            {
                if (UInt160.TryParse(contract["ContractHash"], out ignore))
                {
                    scListAdd(contract["ContractHash"], false);
                }
            }
        }
Exemple #3
0
        public void ParseAddressToUInt160InvalidAddress()
        {
            var actual = UInt160.TryParse("LhYzeoL7r7CLggtnyFpgF9kSxKuekWMGgx0", out var a);

            actual.Should().BeFalse();
            a.Should().Be(UInt160.Zero);
        }
Exemple #4
0
        public void Can_parse_invalid_string_safely()
        {
            var actual = UInt160.TryParse("0x4520462a8c80056291f871da523bff0eb17e29d4x0", out var a);

            actual.Should().BeFalse();
            a.Should().Be(UInt160.Zero);
        }
Exemple #5
0
        /// <summary>
        /// Constructor
        /// </summary>
        public MainService() : base()
        {
            RegisterCommandHander <string, UInt160>(false, (str) =>
            {
                switch (str.ToLowerInvariant())
                {
                case "neo": return(NativeContract.NEO.Hash);

                case "gas": return(NativeContract.GAS.Hash);
                }

                // Try to parse as UInt160

                if (UInt160.TryParse(str, out var addr))
                {
                    return(addr);
                }

                // Accept wallet format

                return(str.ToScriptHash());
            });

            RegisterCommandHander <string, UInt256>(false, (str) => UInt256.Parse(str));
            RegisterCommandHander <string[], UInt256[]>((str) => str.Select(u => UInt256.Parse(u.Trim())).ToArray());
            RegisterCommandHander <string[], UInt160[]>((arr) => arr.Select(str => StringToAddress(str)).ToArray());
            RegisterCommandHander <string, ECPoint>((str) => ECPoint.Parse(str.Trim(), ECCurve.Secp256r1));
            RegisterCommandHander <string[], ECPoint[]>((str) => str.Select(u => ECPoint.Parse(u.Trim(), ECCurve.Secp256r1)).ToArray());
            RegisterCommandHander <string, JObject>((str) => JObject.Parse(str));
            RegisterCommandHander <string, decimal>((str) => decimal.Parse(str, CultureInfo.InvariantCulture));
            RegisterCommandHander <JObject, JArray>((obj) => (JArray)obj);

            RegisterCommand(this);
        }
Exemple #6
0
        public void ParseAddressToUInt160NotZero()
        {
            var actual = UInt160.TryParse("LhYzeoL7r7CLggtnyFpgF9kSxKuekWMGgx0", out var a);
            var b      = UInt160.Zero;

            (a == b).Should().BeTrue();
        }
Exemple #7
0
        public async Task <Script> BuildInvocationScriptAsync(string contract, string operation, IReadOnlyList <string>?arguments = null)
        {
            if (string.IsNullOrEmpty(operation))
            {
                throw new InvalidOperationException($"invalid contract operation \"{operation}\"");
            }

            var parser = await expressNode.GetContractParameterParserAsync(chainManager.Chain).ConfigureAwait(false);

            var scriptHash = parser.TryLoadScriptHash(contract, out var value)
                ? value
                : UInt160.TryParse(contract, out var uint160)
                    ? uint160
                    : throw new InvalidOperationException($"contract \"{contract}\" not found");

            arguments ??= Array.Empty <string>();
            var @params = new ContractParameter[arguments.Count];

            for (int i = 0; i < arguments.Count; i++)
            {
                @params[i] = ConvertArg(arguments[i], parser);
            }

            using var scriptBuilder = new ScriptBuilder();
            scriptBuilder.EmitDynamicCall(scriptHash, operation, @params);
            return(scriptBuilder.ToArray());
Exemple #8
0
        internal static UInt160 AddressToScriptHash(string address)
        {
            if (UInt160.TryParse(address, out var scriptHash))
            {
                return(scriptHash);
            }

            return(address.ToScriptHash());
        }
Exemple #9
0
        public void Can_TryParse()
        {
            UInt160      a       = new UInt160(0x0807060504030201, 0x100f0e0d0c0b0a09, 0x14131211);
            const string @string = "0x14131211100f0e0d0c0b0a090807060504030201";

            UInt160.TryParse(@string, out var b).Should().BeTrue();

            a.Equals(b).Should().BeTrue();
        }
Exemple #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();
        }
Exemple #11
0
        public void TestTryParse()
        {
            UInt160 temp = new UInt160();

            Assert.AreEqual(false, UInt160.TryParse(null, out temp));
            Assert.AreEqual(true, UInt160.TryParse("0x0000000000000000000000000000000000000000", out temp));
            Assert.AreEqual(UInt160.Zero, temp);
            Assert.AreEqual(false, UInt160.TryParse("000000000000000000000000000000000000000", out temp));
            Assert.AreEqual(false, UInt160.TryParse("0xKK00000000000000000000000000000000000000", out temp));
        }
 public void TestTryParse()
 {
     Assert.AreEqual(false, UInt160.TryParse(null, out _));
     Assert.AreEqual(true, UInt160.TryParse("0x0000000000000000000000000000000000000000", out var temp));
     Assert.AreEqual("0x0000000000000000000000000000000000000000", temp.ToString());
     Assert.AreEqual(UInt160.Zero, temp);
     Assert.AreEqual(true, UInt160.TryParse("0x1230000000000000000000000000000000000000", out temp));
     Assert.AreEqual("0x1230000000000000000000000000000000000000", temp.ToString());
     Assert.AreEqual(false, UInt160.TryParse("000000000000000000000000000000000000000", out _));
     Assert.AreEqual(false, UInt160.TryParse("0xKK00000000000000000000000000000000000000", out _));
 }
Exemple #13
0
        public void TryParse_0x_matches_NEO()
        {
            const string @string = "0x30f41a14ca6019038b055b585d002b287b5fdd47";

            Neo.UInt160.TryParse(@string, out var neo).Should().BeTrue();
            UInt160.TryParse(@string, out var fx).Should().BeTrue();

            byte[] buffer = new byte[UInt160.Size];
            fx.TryWrite(buffer).Should().BeTrue();
            buffer.AsSpan().SequenceEqual(neo.ToArray()).Should().BeTrue();
            (fx.ToString() == neo.ToString()).Should().BeTrue();
        }
Exemple #14
0
        public static UInt160 ParseScriptHash(this ContractParameterParser parser, string hashOrContract)
        {
            if (UInt160.TryParse(hashOrContract, out var hash))
            {
                return(hash);
            }

            if (parser.TryLoadScriptHash(hashOrContract, out var value))
            {
                return(value);
            }

            throw new ArgumentException(nameof(hashOrContract));
        }
Exemple #15
0
        public void SetNEP5WatchScriptHashes(IEnumerable <string> nep5WatchScriptHashesHex)
        {
            var scriptHashes = new List <UInt160>();

            foreach (var scriptHashHex in nep5WatchScriptHashesHex)
            {
                if (!UInt160.TryParse(scriptHashHex, out var scriptHash))
                {
                    continue;
                }

                scriptHashes.Add(scriptHash);
            }

            this.nep5WatchScriptHashes = scriptHashes.ToArray();
        }
 private void scListLoad()
 {
     if (File.Exists(Application.StartupPath + "\\smartcontracts.txt"))
     {
         UInt160  ignore;
         String[] smartContracts = File.ReadAllLines(Application.StartupPath + "\\smartcontracts.txt");
         foreach (var smartContract in smartContracts)
         {
             string[] parameters = smartContract.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
             if (UInt160.TryParse(parameters[2], out ignore))
             {
                 scListAdd(parameters[0], parameters[1], parameters[2], false);
             }
         }
     }
 }
        private Script LoadInvocationScript(JToken document)
        {
            var scriptBuilder = new ScriptBuilder();

            switch (document.Type)
            {
            case JTokenType.Object:
                EmitAppCall((JObject)document);
                break;

            case JTokenType.Array:
            {
                foreach (var item in document)
                {
                    EmitAppCall((JObject)item);
                }
            }
            break;

            default:
                throw new FormatException("invalid invocation file");
            }
            return(scriptBuilder.ToArray());

            void EmitAppCall(JObject json)
            {
                var contract = json.Value <string>("contract")
                               ?? throw new JsonException("missing contract field");

                contract = contract.Length > 0 && contract[0] == '#'
                    ? contract[1..] : contract;

                var scriptHash = TryLoadScriptHash(contract, out var value)
                    ? value
                    : UInt160.TryParse(contract, out var uint160)
                        ? uint160
                        : throw new InvalidOperationException($"contract \"{contract}\" not found");

                var operation = json.Value <string>("operation")
                                ?? throw new JsonException("missing operation field");

                var args = json.TryGetValue("args", out var jsonArgs)
                    ? ParseParameters(jsonArgs).ToArray()
                    : Array.Empty <ContractParameter>();

                scriptBuilder.EmitDynamicCall(scriptHash, operation, args);
            }
Exemple #18
0
        public JObject AccountBalance(AccountBalanceRequest request)
        {
            if (request.AccountIdentifier is null)
            {
                return(Error.ACCOUNT_IDENTIFIER_INVALID.ToJson());
            }

            UInt160 account;

            try
            {
                account = request.AccountIdentifier.Address.ToScriptHash();
            }
            catch (Exception)
            {
                return(Error.ACCOUNT_ADDRESS_INVALID.ToJson());
            }

            // can only get current balance
            Amount[] balances = GetUtxoBalance(account);
            if (balances is null)
            {
                return(Error.ACCOUNT_NOT_FOUND.ToJson());
            }

            if (request.AccountIdentifier.SubAccountIdentifier != null) // then need to get the nep5 balance
            {
                if (!UInt160.TryParse(request.AccountIdentifier.SubAccountIdentifier.Address, out UInt160 scriptHash))
                {
                    return(Error.CONTRACT_ADDRESS_INVALID.ToJson());
                }
                Amount[] nep5Balances = GetNep5Balance(scriptHash, account);
                if (nep5Balances is null)
                {
                    return(Error.VM_FAULT.ToJson());
                }
                balances = balances.Concat(nep5Balances).ToArray();
            }

            NeoBlock               currentBlock    = Blockchain.Singleton.GetBlock(Blockchain.Singleton.CurrentBlockHash);
            BlockIdentifier        blockIdentifier = new BlockIdentifier(currentBlock.Index, currentBlock.Hash.ToString());
            AccountBalanceResponse response        = new AccountBalanceResponse(blockIdentifier, balances);

            return(response.ToJson());
        }
Exemple #19
0
        internal static TransactionOutput FromNode(DataNode root)
        {
            var hex     = root.GetString("id");
            var assetID = hex.HexToByte();

            hex = root.GetString("hash");
            UInt160 hash;

            if (!UInt160.TryParse(hex, out hash))
            {
                hash = new UInt160(new byte[20]);
            }

            var amm    = root.GetString("amount", "1");
            var amount = BigInteger.Parse(amm);

            return(new TransactionOutput(assetID, amount, hash));
        }
Exemple #20
0
        public IEnumerable <Breakpoint> SetBreakpoints(Source source, IReadOnlyList <SourceBreakpoint> sourceBreakpoints)
        {
            breakpointCache.Clear();
            this.sourceBreakpointMap[source.Path] = sourceBreakpoints;

            if (UInt160.TryParse(source.Name, out var scriptHash))
            {
                var lineMap = disassemblyManager.TryGetDisassembly(scriptHash, out var disassembly)
                    ? disassembly.LineMap : ImmutableDictionary <int, int> .Empty;

                foreach (var sbp in sourceBreakpoints)
                {
                    yield return(new Breakpoint()
                    {
                        Verified = lineMap.TryGetValue(sbp.Line, out var _) ? true : false,
                        Column = sbp.Column,
                        Line = sbp.Line,
                        Source = source
                    });
 public void updateStatus()
 {
     foreach (ListViewItem Item in listView1.Items)
     {
         if (!UInt160.TryParse(Item.Name, out ignore))
         {
             continue;
         }
         script_hash = UInt160.Parse(Item.Name);
         ContractState contract = Blockchain.Default.GetContract(script_hash);
         if (contract != null)
         {
             Item.SubItems[2].Text      = contract.Name;
             Item.SubItems[2].Font      = SystemFonts.DefaultFont;
             Item.SubItems[4].Text      = "Found! ツ";
             Item.SubItems[4].ForeColor = Color.Green;
         }
     }
 }
        /// <summary>
        /// Converts an Base64 byte array to address
        /// </summary>
        /// <param name="bytearray">
        /// String that represents the Base64 value
        /// </param>
        /// <returns>
        /// Returns null when the string does not represent an Base64 value or when
        /// it is not possible to parse the Base64 value to address; otherwise,
        /// returns the string that represents the converted address
        /// </returns>
        private string Base64ToAddress(string bytearray)
        {
            try
            {
                byte[] result = Convert.FromBase64String(bytearray).Reverse().ToArray();
                string hex    = result.ToHexString();

                if (!UInt160.TryParse(hex, out var scripthash))
                {
                    return(null);
                }

                string address = scripthash.ToAddress(NeoSystem.Settings.AddressVersion);
                return(address);
            }
            catch
            {
                return(null);
            }
        }
Exemple #23
0
        internal static UInt160 StringToAddress(string input)
        {
            switch (input.ToLowerInvariant())
            {
            case "neo": return(NativeContract.NEO.Hash);

            case "gas": return(NativeContract.GAS.Hash);
            }

            // Try to parse as UInt160

            if (UInt160.TryParse(input, out var addr))
            {
                return(addr);
            }

            // Accept wallet format

            return(input.ToScriptHash());
        }
        object ParseAutoObject(CommandToken token)
        {
            if (!token.Quoted)
            {
                if (token.Value.StartsWith("0x"))
                {
                    return(token.Value.HexToBytes());
                }
                else
                {
                    // Number?

                    if (BigInteger.TryParse(token.Value, out BigInteger bi))
                    {
                        return(bi);
                    }

                    // Decimal?

                    if (BigDecimal.TryParse(token.Value, 20, out BigDecimal bd))
                    {
                        return(bd);
                    }

                    // Hashes

                    if (UInt160.TryParse(token.Value, out UInt160 hash160))
                    {
                        return(hash160);
                    }

                    if (UInt256.TryParse(token.Value, out UInt256 hash256))
                    {
                        return(hash256);
                    }
                }
            }

            return(token.Value);
        }
Exemple #25
0
        async Task BalanceOfNativeNEP5(string nativeNEP5Hash, UInt160 address, string[] chainHashList)
        {
            if (!UInt160.TryParse(nativeNEP5Hash, out UInt160 nativeNEP5AssetId))
            {
                return;
            }

            using (ScriptBuilder sb = new ScriptBuilder())
            {
                sb.EmitSysCall("Zoro.NativeNEP5.Call", "BalanceOf", nativeNEP5AssetId, address);
                sb.EmitSysCall("Zoro.NativeNEP5.Call", "Decimals", nativeNEP5AssetId);

                foreach (var chainHash in chainHashList)
                {
                    var info = await ZoroHelper.InvokeScript(sb.ToArray(), chainHash);

                    var    value     = GetBalanceFromJson(info);
                    string chainName = chainHash.Length > 0 ? chainHash : "Root";
                    Console.WriteLine($"BalanceOf NativeNEP5:{value}, chain:{chainName}");
                }
            }
        }
        /// <summary>
        /// Here we don't know the type that we should return, and we need to create the best one
        /// </summary>
        /// <param name="token">Token</param>
        /// <returns>Return object</returns>
        static object ParseObjectFromToken(CommandToken token)
        {
            if (!token.Quoted)
            {
                if (token.Value.StartsWith("0x"))
                {
                    return(token.Value.HexToBytes());
                }

                // Number?

                if (BigInteger.TryParse(token.Value, out var bi))
                {
                    return(bi);
                }

                // Decimal?

                if (BigDecimal.TryParse(token.Value, 20, out var bd))
                {
                    return(bd);
                }

                // Hashes

                if (UInt160.TryParse(token.Value, out var hash160))
                {
                    return(hash160);
                }

                if (UInt256.TryParse(token.Value, out var hash256))
                {
                    return(hash256);
                }
            }

            return(token.Value);
        }
Exemple #27
0
 public void updateStatus()
 {
     foreach (ListViewItem Item in listViewSmartContracts.Items)
     {
         if (!UInt160.TryParse(Item.Name, out ignore))
         {
             continue;
         }
         script_hash = UInt160.Parse(Item.Name);
         ContractState contract = Blockchain.Default.GetContract(script_hash);
         if (contract != null && Item.SubItems[0].Text != contract.Name)
         {
             Item.SubItems[0].Text      = contract.Name;
             Item.SubItems[0].Font      = SystemFonts.DefaultFont;
             Item.SubItems[1].Text      = contract.CodeVersion;
             Item.SubItems[2].Text      = contract.Author;
             Item.SubItems[3].Text      = contract.HasStorage.ToString();
             Item.SubItems[4].Text      = "Found! ツ";
             Item.SubItems[4].Tag       = contract.Description;
             Item.SubItems[4].ForeColor = Color.Green;
         }
     }
 }
Exemple #28
0
 public void updateStatus()
 {
     foreach (ListViewItem Item in listView1.Items)
     {
         if (!UInt160.TryParse(Item.Name, out ignore))
         {
             continue;
         }
         script_hash = UInt160.Parse(Item.Name);
         ContractState contract = Blockchain.Default.GetContract(script_hash);
         if (contract != null)
         {
             if (Item.SubItems[2].Text != contract.Name)
             {
                 // don't attempt to redraw unless something has changed (in this case name goes from pending -> contract name)
                 Item.SubItems[2].Text      = contract.Name;
                 Item.SubItems[2].Font      = SystemFonts.DefaultFont;
                 Item.SubItems[4].Text      = "Found! ツ";
                 Item.SubItems[4].ForeColor = Color.Green;
             }
         }
     }
 }
Exemple #29
0
        public JObject?ExpressGetContractState(JArray @params)
        {
            using var snapshot = neoSystem.GetSnapshot();

            if (@params[0] is JNumber number)
            {
                var id = (int)number.AsNumber();
                foreach (var native in NativeContract.Contracts)
                {
                    if (id == native.Id)
                    {
                        var contract = NativeContract.ContractManagement.GetContract(snapshot, native.Hash);
                        return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
                    }
                }
            }

            var param = @params[0].AsString();

            if (UInt160.TryParse(param, out var scriptHash))
            {
                var contract = NativeContract.ContractManagement.GetContract(snapshot, scriptHash);
                return(contract?.ToJson() ?? throw new RpcException(-100, "Unknown contract"));
            }

            var contracts = new JArray();

            foreach (var contract in NativeContract.ContractManagement.ListContracts(snapshot))
            {
                if (param.Equals(contract.Manifest.Name, StringComparison.OrdinalIgnoreCase))
                {
                    contracts.Add(contract.ToJson());
                }
            }
            return(contracts);
        }
Exemple #30
0
 private void textBox1_TextChanged(object sender, EventArgs e)
 {
     button1.Enabled = UInt160.TryParse(textBox1.Text, out _);
 }