Ejemplo n.º 1
0
        public override void Execute(string[] args, Action <ShellMessageType, string> output)
        {
            if (Shell.Debugger.IsSteppingOrOnBreakpoint)
            {
                output(ShellMessageType.Error, $"Please finish debugging the current invoke: {Shell.Debugger.Emulator.currentMethod}");
                return;
            }

            DataNode inputs;

            try
            {
                inputs = JSONReader.ReadFromString(args[1]);
            }
            catch
            {
                output(ShellMessageType.Error, "Invalid arguments format. Must be valid JSON.");
                return;
            }

            if (args.Length >= 3)
            {
                bool valid = false;

                if (args[2].ToLower() == "with")
                {
                    if (args.Length >= 5)
                    {
                        var assetAmount = BigInteger.Parse(args[3]);
                        var assetName   = args[4];

                        foreach (var entry in Asset.Entries)
                        {
                            if (entry.name == assetName)
                            {
                                output(ShellMessageType.Default, $"Attaching {assetAmount} {assetName} to transaction");
                                Shell.Debugger.Emulator.SetTransaction(entry.id, assetAmount);
                                break;
                            }
                        }

                        valid = true;
                    }
                }

                if (!valid)
                {
                    output(ShellMessageType.Error, "Invalid sintax.");
                    return;
                }
            }

            output(ShellMessageType.Default, "Executing transaction...");

            var methodName   = inputs.ChildCount > 0 ? inputs[0].Value : null;
            var loaderScript = Shell.Debugger.Emulator.GenerateLoaderScriptFromInputs(inputs, Shell.Debugger.ABI);

            Shell.Debugger.Emulator.Reset(loaderScript, Shell.Debugger.ABI, methodName);

            Runtime.OnLogMessage = (x => output(ShellMessageType.Default, x));

            Shell.Debugger.Run();
            ShellRunner.UpdateState(Shell, output);
        }
        public static DataNode GetArgsListAsNode(string argList)
        {
            var node = JSONReader.ReadFromString("{\"params\": [" + argList + "]}");

            return(node.GetNode("params"));
        }
Ejemplo n.º 3
0
        public static IEnumerator RPCRequest(string url, string method, int timeout, Action <EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback,
                                             Action <DataNode> callback, params object[] parameters)
        {
            var paramData = DataNode.CreateArray("params");

            if (parameters != null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);

            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);

            UnityWebRequest request;
            string          json;

            try
            {
                json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }

            var requestNumber = GetNextRequestNumber();

            Log.Write($"RPC request [{requestNumber}]\nurl: {url}\njson: {json}", Log.Level.Networking);

            request = new UnityWebRequest(url, "POST");
            byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
            request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            DateTime startTime = DateTime.Now;

            if (timeout > 0)
            {
                request.timeout = timeout;
            }

            yield return(request.SendWebRequest());

            TimeSpan responseTime = DateTime.Now - startTime;

            if (request.isNetworkError || request.isHttpError)
            {
                Log.Write($"RPC error [{requestNumber}]\nurl: {url}\nResponse time: {responseTime.Seconds}.{responseTime.Milliseconds} sec\n{request.error}\nisNetworkError: {request.isNetworkError}\nisHttpError: {request.isHttpError}\nresponseCode: {request.responseCode}", Log.Level.Networking);
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, request.error + $"\nURL: {url}\nIs network error: {request.isNetworkError}\nIs HTTP error: {request.isHttpError}\nResponse code: {request.responseCode}");
                }
            }
            else
            {
                Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nResponse time: {responseTime.Seconds}.{responseTime.Milliseconds} sec\n{request.downloadHandler.text}", Log.Level.Networking);
                DataNode root = null;

                try
                {
                    root = JSONReader.ReadFromString(request.downloadHandler.text);
                }
                catch (Exception e)
                {
                    Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nFailed to parse JSON: " + e.Message, Log.Level.Networking);
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "Failed to parse JSON: " + e.Message);
                    }
                    yield break;
                }

                if (root == null)
                {
                    Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nFailed to parse JSON", Log.Level.Networking);
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
                    }
                }
                else
                if (root.HasNode("error"))
                {
                    var errorDesc = root["error"].GetString("message");
                    Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nError node found: {errorDesc}", Log.Level.Networking);
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                    }
                }
                else
                if (root.HasNode("result"))
                {
                    var result = root["result"];

                    if (result.HasNode("error"))
                    {
                        // This is incorrect way of RPC error reporting,
                        // but it happens sometimes and should be handeled at least for now.
                        var errorDesc = result.GetString("error");
                        Log.Write($"RPC response [{requestNumber}]\nurl: {url}\nError node found (2): {errorDesc}", Log.Level.Networking);
                        if (errorHandlingCallback != null)
                        {
                            errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                        }
                    }
                    else
                    {
                        callback(result);
                    }
                }
                else
                {
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
                    }
                }
            }

            yield break;
        }
Ejemplo n.º 4
0
        internal void SendRequest(string url, string method, Action <EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback,
                                  Action <DataNode> callback, params object[] parameters)
        {
            var paramData = DataNode.CreateArray("params");

            if (parameters != null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);

            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);

            string json;

            try
            {
                json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }

            string contents;

            try {
                using (var wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                    contents = wc.UploadString(url, json);
                }
            }
            catch (Exception e)
            {
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, e.Message);
                }
                return;
            }

            var root = JSONReader.ReadFromString(contents);

            if (root == null)
            {
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
                }
            }
            else
            if (root.HasNode("error"))
            {
                var errorDesc = root["error"].GetString("message");
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                }
            }
            else
            if (root.HasNode("result"))
            {
                var result = root["result"];
                callback(result);
            }
            else
            {
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
                }
            }
        }
Ejemplo n.º 5
0
        private bool InitInvoke()
        {
            var key = paramsList.Text;
            var f   = _abi.functions[key];

            DebugParameters = new DebugParameters();

            //Get the private key used
            DebugParameters.PrivateKey = privateKeyInput.Text;

            //Get the witness mode
            CheckWitnessMode witnessMode;
            var ws = witnessComboBox.SelectedItem.ToString().Replace(" ", "");

            if (!Enum.TryParse <CheckWitnessMode>(ws, out witnessMode))
            {
                return(false);
            }
            DebugParameters.WitnessMode = witnessMode;

            //Get the trigger type
            TriggerType type;
            var         ts = triggerComboBox.SelectedItem.ToString().Replace(" ", "");

            if (!Enum.TryParse <TriggerType>(ts, out type))
            {
                return(false);
            }
            DebugParameters.TriggerType = type;

            var HasRawScript = RawScriptText.Text.Length != 0;

            //Get the arguments list
            if (!HasRawScript)
            {
                var argList = "";
                if (f.inputs != null)
                {
                    int index = 0;
                    foreach (var p in f.inputs)
                    {
                        var temp = ($"{key}_{f.name}").ToLower();
                        var name = inputGrid.Rows[index].Cells[0].Value;

                        object val;

                        // detect placeholder
                        if (inputGrid.Rows[index].Cells[1].Style.ForeColor == Color.Gray)
                        {
                            val = "";
                        }
                        else
                        {
                            val = ReadCellVal(index, 1);
                        }

                        if (val == null)
                        {
                            val = ""; // temporary hack, necessary to avoid VM crash
                        }

                        if (val != null && !val.Equals(""))
                        {
                            var param_key = (currentContractName + "_" + f.name + "_" + p.name).ToLower();
                            //Add our default running parameters for next time
                            DebugParameters.DefaultParams[param_key] = val.ToString();
                        }

                        if (index > 0)
                        {
                            argList += ",";
                        }

                        if (p.type == Emulator.Type.Array || p.type == Emulator.Type.ByteArray)
                        {
                            var s = val.ToString();

                            if (s.StartsWith("[") && s.EndsWith("]"))
                            {
                                val = s;
                            }
                            else
                            if (s.StartsWith("\"") && s.EndsWith("\""))
                            {
                                s   = s.Substring(1, s.Length - 2);
                                val = ConvertArray(s);

                                if (val == null && p.type == Emulator.Type.ByteArray)
                                {
                                    val = DebuggerUtils.BytesToString(LuxUtils.ReverseHex(LuxUtils.ByteToHex(System.Text.Encoding.UTF8.GetBytes(s))).HexToBytes());
                                }
                                else
                                {
                                    if (val == null)
                                    {
                                        ShowArgumentError(f, index, val);
                                        return(false);
                                    }
                                }
                            }
                            else
                            {
                                ShowArgumentError(f, index, val);
                                return(false);
                            }

                            var items = JSONReader.ReadFromString(val.ToString());

                            val = "";
                            int itemIndex = 0;
                            foreach (var item in items)
                            {
                                if (itemIndex > 0)
                                {
                                    val += ",";
                                }

                                if (item.Kind == LunarParser.NodeKind.String)
                                {
                                    var vv = ConvertArray(item.Value);
                                    if (vv != null)
                                    {
                                        val += vv;
                                    }
                                    else
                                    {
                                        val += "\"" + item.Value + "\"";
                                    }
                                }
                                else
                                {
                                    val += item.Value;
                                }

                                itemIndex++;
                            }

                            val = $"[{val}]";
                        }
                        else
                        {
                            switch (p.type)
                            {
                            case Emulator.Type.String:
                            {
                                var s = val.ToString();
                                if (!s.StartsWith("\"") || !s.EndsWith("\""))
                                {
                                    ShowArgumentError(f, index, val);
                                    return(false);
                                }

                                break;
                            }

                            case Emulator.Type.Integer:
                            {
                                BigInteger n;
                                var        s = val.ToString();
                                if (string.IsNullOrEmpty(s) || !BigInteger.TryParse(s, out n))
                                {
                                    ShowArgumentError(f, index, val);
                                    ResetTabs();
                                    return(false);
                                }
                                break;
                            }

                            case Emulator.Type.Boolean:
                            {
                                switch (val.ToString().ToLower())
                                {
                                case "true": val = true; break;

                                case "false": val = false; break;

                                default:
                                {
                                    ShowArgumentError(f, index, val);
                                    ResetTabs();
                                    return(false);
                                }
                                }
                                break;
                            }
                            }
                        }

                        argList += val;
                        index++;
                    }
                }
                if (key != _abi.entryPoint.name)
                {
                    if (f.inputs == null || f.inputs.Count == 0)
                    {
                        argList = "[]";
                    }
                    var operation = Char.ToLowerInvariant(key[0]) + key.Substring(1);
                    argList = $"\"{operation}\", [{argList}]";
                }

                //Set the arguments list
                try
                {
                    DebugParameters.ArgList = DebuggerUtils.GetArgsListAsNode(argList);
                }
                catch
                {
                    MessageBox.Show("Error parsing input!");
                    ResetTabs();
                    return(false);
                }
            }

            if (assetComboBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetComboBox.SelectedItem.ToString())
                    {
                        BigInteger amount;
                        BigInteger.TryParse(assetAmount.Text, out amount);
                        if (amount > 0)
                        {
                            lastSentSymbol = entry.name;
                            lastSentAmount = assetAmount.Text;

                            amount *= Asset.Decimals; // fix decimals

                            //Add the transaction info
                            DebugParameters.Transaction.Add(entry.id, amount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " amount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            uint timestamp;

            if (!uint.TryParse(timestampBox.Text, out timestamp))
            {
                MessageBox.Show("Invalid timestamp");
                return(false);
            }
            else
            {
                DebugParameters.Timestamp = timestamp;
            }

            DebugParameters.RawScript = HasRawScript ? RawScriptText.Text.HexToBytes() : null;

            return(true);
        }
Ejemplo n.º 6
0
        public override IEnumerable <PendingSwap> Update()
        {
            logger.Message($"Update NeoInterop.");
            var result = new List <PendingSwap>();

            int maxPages = 1;

            {
                var json = neoscanAPI.ExecuteRequest($"get_address_abstracts/{LocalAddress}/1");
                if (json == null)
                {
                    logger.Message($"maxPages {maxPages}, null result through request {LocalAddress}");
                    return(result); // it will try again later
                }

                var root = JSONReader.ReadFromString(json);
                maxPages = root.GetInt32("total_pages");
            }

            logger.Message($"maxPages {maxPages}, got result through request {LocalAddress}");

            for (int page = maxPages; page >= 1; page--)
            {
                logger.Message($"fetching page {page} now");

                var json = neoscanAPI.ExecuteRequest($"get_address_abstracts/{LocalAddress}/{page}");
                if (json == null)
                {
                    logger.Warning("failed to fetch address page");
                    break;
                }

                var root = JSONReader.ReadFromString(json);

                var entries = root.GetNode("entries");

                logger.Message($"entries: {entries.ChildCount}");
                for (int i = entries.ChildCount - 1; i >= 0; i--)
                {
                    var entry = entries.GetNodeByIndex(i);

                    var temp   = entry.GetString("block_height");
                    var height = BigInteger.Parse(temp);
                    logger.Message($"block_height: {_blockHeight.ToString()} height: {height}");

                    if (height >= _blockHeight)
                    {
                        try
                        {
                            ProcessTransaction(entry, result);
                            _blockHeight = height;
                        }
                        catch (Exception e)
                        {
                            logger.Error("error: " + e.ToString());
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 7
0
 public override DataNode ReadStore(string content)
 {
     return(JSONReader.ReadFromString(content));
 }
Ejemplo n.º 8
0
        public InteropTransaction ReadTransaction(Hash hash)
        {
            var hashText = hash.ToString();

            var apiCall = $"get_transaction/{hashText}";
            var json    = ExecuteRequest(apiCall);

            if (json == null)
            {
                throw new OracleException("Network read failure: " + apiCall);
            }

            string inputSource = null;

            try
            {
                var root = JSONReader.ReadFromString(json);

                var scripts = root.GetNode("scripts");
                Throw.IfNull(scripts, nameof(scripts));

                if (scripts.ChildCount != 1)
                {
                    throw new OracleException("Transactions with multiple sources not supported yet");
                }

                Address interopAddress = Address.Null;
                foreach (var scriptEntry in scripts.Children)
                {
                    var vs = scriptEntry.GetNode("verification");
                    if (vs == null)
                    {
                        continue;
                    }

                    var verificationScript = Base16.Decode(vs.Value);
                    var pubKey             = new byte[33];
                    Core.Utils.ByteArrayUtils.CopyBytes(verificationScript, 1, pubKey, 0, 33);

                    var signatureScript = NeoKeys.CreateSignatureScript(pubKey);
                    var signatureHash   = Neo.Utils.CryptoUtils.ToScriptHash(signatureScript);
                    inputSource = Neo.Utils.CryptoUtils.ToAddress(signatureHash);

                    pubKey         = Core.Utils.ByteArrayUtils.ConcatBytes((byte)AddressKind.User, pubKey);
                    interopAddress = Address.FromBytes(pubKey);
                    break;
                }

                if (interopAddress.IsNull)
                {
                    throw new OracleException("Could not fetch public key from transaction");
                }

                if (string.IsNullOrEmpty(inputSource))
                {
                    throw new OracleException("Could not fetch source address from transaction");
                }

                var attrNodes = root.GetNode("attributes");
                if (attrNodes != null)
                {
                    foreach (var entry in attrNodes.Children)
                    {
                        var kind = entry.GetString("usage");
                        if (kind == "Description")
                        {
                            var data  = entry.GetString("data");
                            var bytes = Base16.Decode(data);

                            var text = Encoding.UTF8.GetString(bytes);
                            if (Address.IsValidAddress(text))
                            {
                                interopAddress = Address.FromText(text);
                            }
                        }
                    }
                }

                return(FillTransaction(hashText, inputSource, interopAddress));
            }
            catch (Exception e)
            {
                throw new OracleException(e.Message);
            }
        }
Ejemplo n.º 9
0
        public void LoadFromFile(string path)
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException();
            }

            var json = File.ReadAllText(path);
            var root = JSONReader.ReadFromString(json);

            var avmInfo = root["avm"];

            if (avmInfo != null)
            {
                /*var curHash = bytes.MD5().ToLowerInvariant();
                 * var oldHash = avmInfo.GetString("hash").ToLowerInvariant();
                 *
                 * if (curHash != oldHash)
                 * {
                 *  throw new Exception("Hash mismatch, please recompile the code to get line number info");
                 * }*/

                this.contractName = avmInfo.GetString("name");
            }
            else
            {
                this.contractName = Path.GetFileNameWithoutExtension(path);
            }

            _fileNames.Clear();

            var files    = new Dictionary <int, string>();
            var fileNode = root["files"];

            foreach (var temp in fileNode.Children)
            {
                files[temp.GetInt32("id")] = temp.GetString("url");
            }

            _entries = new List <DebugMapEntry>();
            var mapNode = root["map"];

            foreach (var temp in mapNode.Children)
            {
                int fileID = temp.GetInt32("file");

                if (!files.ContainsKey(fileID))
                {
                    throw new Exception("Error loading map file, invalid file entry");
                }

                var entry = new DebugMapEntry();
                entry.startOfs = temp.GetInt32("start");
                entry.endOfs   = temp.GetInt32("end");
                entry.line     = temp.GetInt32("line");
                entry.url      = files[fileID];
                _entries.Add(entry);

                if (!string.IsNullOrEmpty(entry.url))
                {
                    _fileNames.Add(entry.url);
                }
            }
        }
Ejemplo n.º 10
0
        public void Start()
        {
            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];

            // Enter the listening loop.
            while (true)
            {
                try
                {
                    Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connected!");

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    var sb = new StringBuilder();
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        var str = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        sb.Append(str);
                    }

                    var json = sb.ToString();
                    var root = JSONReader.ReadFromString(json);

                    var method = root.GetString("method");

                    string result = null;

                    switch (method)
                    {
                    case "getaccountstate":
                    {
                        break;
                    }

                    case "getstorage":
                    {
                        break;
                    }

                    case "sendrawtransaction":
                    {
                        break;
                    }

                    case "invokescript":
                    {
                        break;
                    }

                    case "getrawtransaction":
                    {
                        break;
                    }

                    case "getblockcount":
                    {
                        break;
                    }

                    case "getblock":
                    {
                        break;
                    }
                    }

                    var output = Encoding.ASCII.GetBytes(result);
                    stream.Write(output, 0, output.Length);

                    client.Close();
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException: {0}", e);
                }
            }
            // Stop listening for new clients.
            server.Stop();
        }
Ejemplo n.º 11
0
        public static IEnumerator SendRequest(string url, string method, Action<EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback, 
                                            Action<DataNode> callback, params object[] parameters)
        {
            string contents;

            var paramData = DataNode.CreateArray("params");
            
            if (parameters!=null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);
            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);
            
            UnityWebRequest www;
            string json;

            try
            {
				json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }
            
            Debug.Log("www request json: " + json);

            www = UnityWebRequest.Post(url, json);
            yield return www.SendWebRequest();
            
            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
				if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, www.error);			
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
				var root = JSONReader.ReadFromString(www.downloadHandler.text);
				
				if (root == null)
				{
					if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
				}
				else 
				if (root.HasNode("error")) {
					var errorDesc = root["error"].GetString("message");
					if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
				}
				else
				if (root.HasNode("result"))
				{
					var result = root["result"];
					callback(result);
				}
				else {					
					if (errorHandlingCallback != null) errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
				}				
            }

			yield break;
        }		
Ejemplo n.º 12
0
        private bool InitInvoke()
        {
            var json = contractInputField.Text;

            if (string.IsNullOrEmpty(json))
            {
                MessageBox.Show("Invalid input!");
                return(false);
            }

            DataNode node;

            try
            {
                node = JSONReader.ReadFromString(json);
            }
            catch
            {
                MessageBox.Show("Error parsing input!");
                return(false);
            }

            var items = node.GetNode("params");

            debugger.ContractArgs.Clear();
            foreach (var item in items.Children)
            {
                // TODO - auto convert value to proper types, currently everything is assumed to be strings!

                var obj = ConvertArgument(item);
                debugger.ContractArgs.Add(obj);
            }

            debugger.ClearTransactions();
            if (assetListBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetListBox.SelectedItem.ToString())
                    {
                        BigInteger ammount;

                        BigInteger.TryParse(assetAmmount.Text, out ammount);

                        if (ammount > 0)
                        {
                            debugger.AddTransaction(entry.id, ammount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " ammount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 13
0
        private void RunForm_Shown(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.None;

            assetAmmount.Enabled = assetListBox.SelectedIndex > 0;

            if (Runtime.invokerKeys == null && File.Exists("last.key"))
            {
                var privKey = File.ReadAllBytes("last.key");
                if (privKey.Length == 32)
                {
                    Runtime.invokerKeys = new NeoLux.KeyPair(privKey);
                }
            }

            if (Runtime.invokerKeys != null)
            {
                addressLabel.Text = Runtime.invokerKeys.address;
            }
            else
            {
                addressLabel.Text = "(No key loaded)";
            }

            if (!string.IsNullOrEmpty(MainForm.targetAVMPath))
            {
                var fileName = MainForm.targetAVMPath.Replace(".avm", ".json");
                if (File.Exists(fileName))
                {
                    try
                    {
                        _paramMap = new Dictionary <string, DataNode>();

                        var contents = File.ReadAllText(fileName);

                        var contractInfo = JSONReader.ReadFromString(contents);

                        var contractNode = contractInfo["contract"];
                        var inputs       = contractNode["inputs"];

                        paramsList.Items.Clear();
                        foreach (var node in inputs.Children)
                        {
                            var name = node.GetString("name");
                            var data = node.GetNode("params");
                            _paramMap[name] = data;
                        }
                    }
                    finally
                    {
                    }
                }
            }

            button1.Enabled = _paramMap != null && _paramMap.Count > 0;
            paramsList.Items.Clear();

            if (_paramMap != null)
            {
                foreach (var entry in _paramMap)
                {
                    paramsList.Items.Add(entry.Key);

                    if (lastParams != null && entry.Key.Equals(lastParams))
                    {
                        paramsList.SelectedIndex = paramsList.Items.Count - 1;
                    }
                }

                if (paramsList.SelectedIndex < 0 && paramsList.Items.Count > 0)
                {
                    paramsList.SelectedIndex = 0;
                }
            }
        }
Ejemplo n.º 14
0
        public override void Execute(string[] args)
        {
            if (Shell.debugger == null)
            {
                Shell.Write("Smart contract not loaded yet.");
                return;
            }


            DataNode inputs;

            try
            {
                inputs = JSONReader.ReadFromString(args[1]);
            }
            catch
            {
                Shell.Write("Invalid arguments format. Must be valid JSON.");
                return;
            }

            if (args.Length >= 3)
            {
                bool valid = false;

                if (args[2].ToLower() == "with")
                {
                    if (args.Length >= 5)
                    {
                        BigInteger assetAmount = BigInteger.Parse(args[3]);
                        var        assetName   = args[4];

                        foreach (var entry in Asset.Entries)
                        {
                            if (entry.name == assetName)
                            {
                                Shell.Write($"Attaching {assetAmount} {assetName} to transaction");
                                Shell.debugger.SetTransaction(entry.id, assetAmount);
                                break;
                            }
                        }

                        valid = true;
                    }
                }

                if (!valid)
                {
                    Shell.Write("Invalid sintax.");
                    return;
                }

                Shell.Write("Executing transaction...");

                Shell.debugger.Reset(inputs);
                Shell.debugger.Run();

                var val = Shell.debugger.GetOutput();

                Shell.blockchain.Save(Shell.blockchainPath);

                Shell.Write("Result: " + FormattingUtils.StackItemAsString(val));
                Shell.Write("GAS used: " + Shell.debugger.GetUsedGas());
            }
        }
Ejemplo n.º 15
0
        public static decimal GetCoinRate(string ticker, string currrency)
        {
            string json;
            string baseticker;

            switch (ticker)
            {
            case "SOUL":
                baseticker = "phantasma";
                break;

            case "KCAL":
                baseticker = "phantasma-energy";
                break;

            case "NEO":
                baseticker = "neo";
                break;

            case "GAS":
                baseticker = "gas";
                break;

            case "USDT":
                baseticker = "tether";
                break;

            case "ETH":
                baseticker = "ethereum";
                break;

            case "DAI":
                baseticker = "dai";
                break;

            default:
                baseticker = "phantasma";
                break;
            }

            var url = $"https://api.coingecko.com/api/v3/simple/price?ids={baseticker}&vs_currencies={currrency}";

            try
            {
                using (var httpClient = new HttpClient())
                {
                    json = httpClient.GetStringAsync(new Uri(url)).Result;
                }
                var root = JSONReader.ReadFromString(json);

                // hack for goati price .10
                if (ticker == "GOATI")
                {
                    var price = 0.10m;
                    return(price);
                }
                else
                {
                    root = root[baseticker];
                    var price = root.GetDecimal(currrency.ToLower());
                    return(price);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception occurred: {ex}");
                return(0);
            }
        }
Ejemplo n.º 16
0
        private bool InitInvoke()
        {
            var key = paramsList.Text;
            var f   = abi.functions[key];

            var argList = "\"" + key + "\"";

            if (f.inputs != null)
            {
                argList += ", [";

                int index = 0;
                foreach (var p in f.inputs)
                {
                    var temp = (key + "_" + f.name).ToLower();
                    var val  = inputGrid.Rows[index].Cells[1].Value;

                    if (index > 0)
                    {
                        argList += ",";
                    }

                    switch (p.type.ToLower())
                    {
                    case "string": val = "\"" + val + "\""; break;
                    }

                    argList += val;
                    index++;
                }

                argList += "]";
            }
            else
            {
                argList += ", [null]";
            }

            string json = "{\"params\": [" + argList + "]}";

            if (string.IsNullOrEmpty(json))
            {
                MessageBox.Show("Invalid input!");
                return(false);
            }

            DataNode node;

            try
            {
                node = JSONReader.ReadFromString(json);
            }
            catch
            {
                MessageBox.Show("Error parsing input!");
                return(false);
            }

            var items = node.GetNode("params");

            if (assetListBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetListBox.SelectedItem.ToString())
                    {
                        BigInteger ammount;

                        BigInteger.TryParse(assetAmmount.Text, out ammount);

                        if (ammount > 0)
                        {
                            emulator.SetTransaction(entry.id, ammount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " ammount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            emulator.Reset(items);

            return(true);
        }
Ejemplo n.º 17
0
        public static IEnumerator RPCRequest(string url, string method, Action <EPHANTASMA_SDK_ERROR_TYPE, string> errorHandlingCallback,
                                             Action <DataNode> callback, params object[] parameters)
        {
            var paramData = DataNode.CreateArray("params");

            if (parameters != null && parameters.Length > 0)
            {
                foreach (var obj in parameters)
                {
                    paramData.AddField(null, obj);
                }
            }

            var jsonRpcData = DataNode.CreateObject(null);

            jsonRpcData.AddField("jsonrpc", "2.0");
            jsonRpcData.AddField("method", method);
            jsonRpcData.AddField("id", "1");
            jsonRpcData.AddNode(paramData);

            UnityWebRequest request;
            string          json;

            try
            {
                json = JSONWriter.WriteToString(jsonRpcData);
            }
            catch (Exception e)
            {
                throw e;
            }

            Debug.Log($"RPC request\nurl:{url}\njson: {json}");

            request = new UnityWebRequest(url, "POST");
            byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
            request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
            request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");

            yield return(request.SendWebRequest());

            if (request.isNetworkError || request.isHttpError)
            {
                Debug.Log(request.error);
                if (errorHandlingCallback != null)
                {
                    errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.WEB_REQUEST_ERROR, request.error);
                }
            }
            else
            {
                Debug.Log(request.downloadHandler.text);
                var root = JSONReader.ReadFromString(request.downloadHandler.text);

                if (root == null)
                {
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.FAILED_PARSING_JSON, "failed to parse JSON");
                    }
                }
                else
                if (root.HasNode("error"))
                {
                    var errorDesc = root["error"].GetString("message");
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.API_ERROR, errorDesc);
                    }
                }
                else
                if (root.HasNode("result"))
                {
                    var result = root["result"];
                    callback(result);
                }
                else
                {
                    if (errorHandlingCallback != null)
                    {
                        errorHandlingCallback(EPHANTASMA_SDK_ERROR_TYPE.MALFORMED_RESPONSE, "malformed response");
                    }
                }
            }

            yield break;
        }
Ejemplo n.º 18
0
        private bool InitInvoke()
        {
            var key = paramsList.Text;
            var f   = abi.functions[key];

            var ws = witnessComboBox.SelectedItem.ToString().Replace(" ", "");

            if (!Enum.TryParse <CheckWitnessMode>(ws, out emulator.checkWitnessMode))
            {
                return(false);
            }

            var ts = triggerComboBox.SelectedItem.ToString().Replace(" ", "");

            if (!Enum.TryParse <TriggerType>(ts, out emulator.currentTrigger))
            {
                return(false);
            }

            var argList = "";

            if (f.inputs != null)
            {
                int index = 0;
                foreach (var p in f.inputs)
                {
                    var temp = ($"{key}_{f.name}").ToLower();
                    var name = inputGrid.Rows[index].Cells[0].Value;

                    object val;

                    // detect placeholder
                    if (inputGrid.Rows[index].Cells[1].Style.ForeColor == Color.Gray)
                    {
                        val = "";
                    }
                    else
                    {
                        val = ReadCellVal(index, 1);
                    }

                    if (val == null)
                    {
                        val = ""; // temporary hack, necessary to avoid VM crash
                    }

                    if (val != null && !val.Equals(""))
                    {
                        var param_key = (currentContractName + "_" + f.name + "_" + p.name).ToLower();
                        mainForm.settings.lastParams[param_key] = val.ToString();
                    }

                    if (index > 0)
                    {
                        argList += ",";
                    }

                    if (p.type.Contains("Array"))
                    {
                        var s = val.ToString();

                        if (s.StartsWith("[") && s.EndsWith("]"))
                        {
                            val = s;
                        }
                        else
                        if (IsHex(s))
                        {
                            var bytes = s.HexToBytes();
                            s = BytesToString(bytes);
                        }
                        else
                        if (IsValidWallet(s))
                        {
                            var bytes      = s.Base58CheckDecode();
                            var scriptHash = Crypto.Default.ToScriptHash(bytes);
                            bytes = scriptHash.ToArray();
                            s     = BytesToString(bytes);
                        }
                        else
                        {
                            ShowArgumentError(f, index, val);
                            return(false);
                        }
                    }
                    else
                    {
                        switch (p.type.ToLower())
                        {
                        case "string":
                        {
                            var s = val.ToString();
                            if (!s.StartsWith("\"") || !s.EndsWith("\""))
                            {
                                ShowArgumentError(f, index, val);
                                return(false);
                            }

                            break;
                        }

                        case "integer":
                        {
                            BigInteger n;
                            var        s = val.ToString();
                            if (string.IsNullOrEmpty(s) || !BigInteger.TryParse(s, out n))
                            {
                                ShowArgumentError(f, index, val);
                                ResetTabs();
                                return(false);
                            }
                            break;
                        }

                        case "boolean":
                        {
                            switch (val.ToString().ToLower())
                            {
                            case "true": val = true; break;

                            case "false": val = false; break;

                            default:
                            {
                                ShowArgumentError(f, index, val);
                                ResetTabs();
                                return(false);
                            }
                            }
                            break;
                        }
                        }
                    }

                    argList += val;
                    index++;
                }
            }

            if (key != abi.entryPoint.name)
            {
                if (f.inputs == null || f.inputs.Length == 0)
                {
                    argList = "[null]";
                }
                var operation = Char.ToLowerInvariant(key[0]) + key.Substring(1);
                argList = $"\"{operation}\", {argList}";
            }

            string json = "{\"params\": [" + argList + "]}";

            if (string.IsNullOrEmpty(json))
            {
                MessageBox.Show("Invalid input!");
                return(false);
            }

            DataNode node;

            try
            {
                node = JSONReader.ReadFromString(json);
            }
            catch
            {
                MessageBox.Show("Error parsing input!");
                ResetTabs();
                return(false);
            }

            var items = node.GetNode("params");

            if (assetComboBox.SelectedIndex > 0)
            {
                foreach (var entry in Asset.Entries)
                {
                    if (entry.name == assetComboBox.SelectedItem.ToString())
                    {
                        BigInteger ammount;

                        BigInteger.TryParse(assetAmount.Text, out ammount);

                        if (ammount > 0)
                        {
                            emulator.SetTransaction(entry.id, ammount);
                        }
                        else
                        {
                            MessageBox.Show(entry.name + " amount must be greater than zero");
                            return(false);
                        }

                        break;
                    }
                }
            }

            emulator.Reset(items);

            mainForm.settings.Save();

            return(true);
        }