Example #1
0
        /// <summary>
        /// Add a command definition to the manager so that the manager can invoke those commands against parsed input
        /// </summary>
        public void AddCommandDefinition(CliCommandDefinition cmdDefinition)
        {
            List <string> commandNames = new List <string>();

            commandNames.AddRange(_CommandCollection.Select(x => x.Name));
            commandNames.AddRange(_CommandCollection.SelectMany(x => x.Aliases));

            if (!commandNames.Contains(cmdDefinition.Name.ToLower()))
            {
                cmdDefinition.Name = cmdDefinition.Name.ToLower();

                List <string> paramNames = new List <string>();
                paramNames.AddRange(cmdDefinition.Parameters.Select(x => x.Name));
                paramNames.AddRange(cmdDefinition.Parameters.SelectMany(x => x.Aliases));

                foreach (string pn in paramNames)
                {
                    if (paramNames.Where(x => x == pn).Count() > 1)
                    {
                        throw new Exception($"Command definition '{cmdDefinition.Name}' has duplicate parameter name '{pn}'.");
                    }
                }

                _CommandCollection.Add(cmdDefinition);
            }
            else
            {
                throw new Exception($"Duplicate command definition '{cmdDefinition.Name.ToLower()}'.");
            }
        }
Example #2
0
        public void StartRepl()
        {
            _screenManager.PrintHeader();
            _screenManager.PrintUsage();
            _screenManager.PrintLine();

            ReadLine.AutoCompletionHandler = new AutoCompleteWithRegisteredCommand(_commands.Select(c => c.Name).ToList());

            while (true)
            {
                //string command = _screenManager.GetCommand();
                string command = ReadLine.Read("aelf> ");


                if (string.IsNullOrWhiteSpace(command))
                {
                    continue;
                }

                ReadLine.AddHistory(command);

                // stop the repl if "quit", "Quit", "QuiT", ... is encountered
                if (command.Equals(ExitReplCommand, StringComparison.OrdinalIgnoreCase))
                {
                    Stop();
                    break;
                }

                if (command.StartsWith("sub events"))
                {
                    string[] splitOnSpaces = command.Split(' ');

                    if (splitOnSpaces.Length == 3)
                    {
                        EventMonitor mon = new EventMonitor(_port, splitOnSpaces[2]);
                        mon.Start().GetResult();
                        Console.ReadKey();
                    }
                    else
                    {
                        Console.WriteLine("Sub events - incorrect arguments");
                    }
                }

                CmdParseResult       parsedCmd = _cmdParser.Parse(command);
                CliCommandDefinition def       = GetCommandDefinition(parsedCmd.Command);

                if (def == null)
                {
                    _screenManager.PrintCommandNotFound(command);
                }
                else
                {
                    ProcessCommand(parsedCmd, def);
                }
            }
        }
Example #3
0
        CliCommand Build(ParseResult parseResult)
        {
            if (parseResult.CommandName == "help")
            {
                return(GenerateHelpCommand());
            }

            CliCommandDefinition cmdDef = _CommandCollection.Where(c => c.Name == parseResult.CommandName.ToLower() || c.Aliases.Contains(parseResult.CommandName.ToLower())).SingleOrDefault();

            if (parseResult.Help)
            {
                return(GenerateHelpCommand(cmdDef));
            }

            Dictionary <string, string> rawParams  = parseResult.RawParameters;
            Dictionary <string, object> realParams = new Dictionary <string, object>();

            if (cmdDef != null)
            {
                foreach (string k in rawParams.Keys)
                {
                    CliParameter cliParam = cmdDef.Parameters.Where(d => d.Name.ToLower() == k.ToLower() || d.Aliases.Contains(k.ToLower()) || d.Ordinal.ToString() == k).FirstOrDefault();
                    if (cliParam != null)
                    {
                        if (!cliParam.Validator(rawParams[k]))
                        {
                            return(GenerateErrorCommand(cliParam.ValidatorErrorMessage));
                        }
                        realParams[cliParam.Name] = rawParams[k];
                    }
                    else
                    {
                        int i = 0;
                        return(GenerateErrorCommand($"Command '{cmdDef.Name}' has no parameter defined {(int.TryParse(k, out i) ? $"at postion {i}" : $"'{k}'")}."));
                    }
                }
                return(new CliCommand {
                    Invoke = cmdDef.Command, Parameters = realParams
                });
            }
Example #4
0
 public void RegisterCommand(CliCommandDefinition cmd)
 {
     _commands.Add(cmd);
 }
Example #5
0
        private void ProcessCommand(CmdParseResult parsedCmd, CliCommandDefinition def)
        {
            string error = def.Validate(parsedCmd);

            if (!string.IsNullOrEmpty(error))
            {
                _screenManager.PrintError(error);
            }
            else
            {
                if (def is GetDeserializedResultCmd g)
                {
                    try
                    {
                        var str = g.Validate(parsedCmd);
                        if (str != null)
                        {
                            _screenManager.PrintError(str);
                            return;
                        }

                        // RPC
                        var t    = parsedCmd.Args.ElementAt(0);
                        var data = parsedCmd.Args.ElementAt(1);

                        byte[] sd;
                        try
                        {
                            sd = ByteArrayHelpers.FromHexString(data);
                        }
                        catch (Exception e)
                        {
                            _screenManager.PrintError("Wrong data formant.");
                            return;
                        }

                        object dd;
                        try
                        {
                            dd = Deserializer.Deserialize(t, sd);
                        }
                        catch (Exception e)
                        {
                            _screenManager.PrintError("Invalid data format");
                            return;
                        }
                        if (dd == null)
                        {
                            _screenManager.PrintError("Not supported type.");
                            return;
                        }
                        _screenManager.PrintLine(dd.ToString());
                        return;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        return;
                    }
                }

                if (def is LoadContractAbiCmd l)
                {
                    error = l.Validate(parsedCmd);

                    if (!string.IsNullOrEmpty(error))
                    {
                        _screenManager.PrintError(error);
                    }
                    try
                    {
                        // RPC
                        HttpRequestor reqhttp = new HttpRequestor(_rpcAddress);
                        if (!parsedCmd.Args.Any())
                        {
                            if (_genesisAddress == null)
                            {
                                _screenManager.PrintError(ConnectionNeeded);
                                return;
                            }
                            parsedCmd.Args.Add(_genesisAddress);
                            //parsedCmd.Args.Add(Globals.GenesisBasicContract);
                        }

                        var    addr = parsedCmd.Args.ElementAt(0);
                        Module m    = null;
                        if (!_loadedModules.TryGetValue(addr, out m))
                        {
                            string resp = reqhttp.DoRequest(def.BuildRequest(parsedCmd).ToString());

                            if (resp == null)
                            {
                                _screenManager.PrintError(ServerConnError);
                                return;
                            }

                            if (resp.IsEmpty())
                            {
                                _screenManager.PrintError(NoReplyContentError);
                                return;
                            }
                            JObject jObj = JObject.Parse(resp);
                            var     res  = JObject.FromObject(jObj["result"]);

                            JToken ss = res["abi"];
                            byte[] aa = ByteArrayHelpers.FromHexString(ss.ToString());

                            MemoryStream ms = new MemoryStream(aa);
                            m = Serializer.Deserialize <Module>(ms);
                            _loadedModules.Add(addr, m);
                        }

                        var obj = JObject.FromObject(m);
                        _screenManager.PrintLine(obj.ToString());
                    }
                    catch (Exception e)
                    {
                        if (e is JsonReaderException)
                        {
                            _screenManager.PrintError(WrongInputFormat);
                            return;
                        }
                        return;
                    }

                    return;
                }
                if (def is DeployContractCommand dcc)
                {
                    if (_genesisAddress == null)
                    {
                        _screenManager.PrintError(NotConnected);
                        return;
                    }

                    try
                    {
                        string err = dcc.Validate(parsedCmd);
                        if (!string.IsNullOrEmpty(err))
                        {
                            _screenManager.PrintLine(err);
                            return;
                        }

                        //string cat = parsedCmd.Args.ElementAt(0);
                        string filename = parsedCmd.Args.ElementAt(0);

                        // Read sc bytes
                        SmartContractReader screader = new SmartContractReader();
                        byte[] sc  = screader.Read(filename);
                        string hex = sc.ToHex();

                        var    name = GlobalConfig.GenesisBasicContract;
                        Module m    = _loadedModules.Values.FirstOrDefault(ld => ld.Name.Equals(name));

                        if (m == null)
                        {
                            _screenManager.PrintError(AbiNotLoaded);
                            return;
                        }

                        Method meth = m.Methods.FirstOrDefault(mt => mt.Name.Equals(DeploySmartContract));

                        if (meth == null)
                        {
                            _screenManager.PrintError(MethodNotFound);
                            return;
                        }

                        byte[] serializedParams = meth.SerializeParams(new List <string> {
                            "1", hex
                        });

                        Transaction t = new Transaction();
                        t = CreateTransaction(parsedCmd.Args.ElementAt(2), _genesisAddress,
                                              DeploySmartContract, serializedParams, TransactionType.ContractTransaction);

                        t = t.AddBlockReference(_rpcAddress);

                        MemoryStream ms = new MemoryStream();
                        Serializer.Serialize(ms, t);
                        byte[]      b      = ms.ToArray();
                        byte[]      toSig  = SHA256.Create().ComputeHash(b);
                        ECSigner    signer = new ECSigner();
                        ECSignature signature;
                        ECKeyPair   kp = _accountManager.GetKeyPair(parsedCmd.Args.ElementAt(2));
                        if (kp == null)
                        {
                            throw new AccountLockedException(parsedCmd.Args.ElementAt(2));
                        }
                        signature = signer.Sign(kp, toSig);

                        // Update the signature
                        t.Sig = new Signature {
                            R = signature.R, S = signature.S, P = kp.PublicKey.Q.GetEncoded()
                        };

                        var resp = SignAndSendTransaction(t);

                        if (resp == null)
                        {
                            _screenManager.PrintError(ServerConnError);
                            return;
                        }
                        if (resp.IsEmpty())
                        {
                            _screenManager.PrintError(NoReplyContentError);
                            return;
                        }
                        JObject jObj = JObject.Parse(resp);

                        string toPrint = def.GetPrintString(JObject.FromObject(jObj["result"]));
                        _screenManager.PrintLine(toPrint);
                        return;
                    }
                    catch (Exception e)
                    {
                        if (e is ContractLoadedException || e is AccountLockedException)
                        {
                            _screenManager.PrintError(e.Message);
                            return;
                        }

                        if (e is InvalidTransactionException)
                        {
                            _screenManager.PrintError(InvalidTransaction);
                            return;
                        }
                        if (e is JsonReaderException)
                        {
                            _screenManager.PrintError(WrongInputFormat);
                            return;
                        }
                        return;
                    }
                }

                // Execute
                // 2 cases : RPC command, Local command (like account management)
                if (def.IsLocal)
                {
                    if (def is SendTransactionCmd c)
                    {
                        try
                        {
                            JObject j = JObject.Parse(parsedCmd.Args.ElementAt(0));

                            Transaction tr;

                            tr = ConvertFromJson(j);
                            string hex = tr.To.Value.ToHex();

                            Module m = null;
                            if (!_loadedModules.TryGetValue(hex.Replace("0x", ""), out m))
                            {
                                if (!_loadedModules.TryGetValue("0x" + hex.Replace("0x", ""), out m))
                                {
                                    _screenManager.PrintError(AbiNotLoaded);
                                    return;
                                }
                            }

                            Method method = m.Methods?.FirstOrDefault(mt => mt.Name.Equals(tr.MethodName));

                            if (method == null)
                            {
                                _screenManager.PrintError(MethodNotFound);
                                return;
                            }

                            JArray p = j["params"] == null ? null : JArray.Parse(j["params"].ToString());
                            tr.Params = j["params"] == null ? null : method.SerializeParams(p.ToObject <string[]>());
                            tr.type   = TransactionType.ContractTransaction;

                            tr = tr.AddBlockReference(_rpcAddress);

                            _accountManager.SignTransaction(tr);
                            var resp = SignAndSendTransaction(tr);

                            if (resp == null)
                            {
                                _screenManager.PrintError(ServerConnError);
                                return;
                            }
                            if (resp.IsEmpty())
                            {
                                _screenManager.PrintError(NoReplyContentError);
                                return;
                            }
                            JObject jObj = JObject.Parse(resp);

                            string toPrint = def.GetPrintString(JObject.FromObject(jObj["result"]));
                            _screenManager.PrintLine(toPrint);
                        }
                        catch (Exception e)
                        {
                            if (e is AccountLockedException || e is InvalidTransactionException ||
                                e is InvalidInputException)
                            {
                                _screenManager.PrintError(e.Message);
                            }
                            if (e is JsonReaderException || e is FormatException)
                            {
                                _screenManager.PrintError(WrongInputFormat);
                                return;
                            }
                        }
                    }
                    else if (def is CallReadOnlyCmd)
                    {
                        JObject j = JObject.Parse(parsedCmd.Args.ElementAt(0));

                        Transaction tr;

                        tr = ConvertFromJson(j);
                        string hex = tr.To.Value.ToHex();

                        Module m = null;
                        if (!_loadedModules.TryGetValue(hex.Replace("0x", ""), out m))
                        {
                            if (!_loadedModules.TryGetValue("0x" + hex.Replace("0x", ""), out m))
                            {
                                _screenManager.PrintError(AbiNotLoaded);
                                return;
                            }
                        }

                        Method method = m.Methods?.FirstOrDefault(mt => mt.Name.Equals(tr.MethodName));

                        if (method == null)
                        {
                            _screenManager.PrintError(MethodNotFound);
                            return;
                        }

                        JArray p = j["params"] == null ? null : JArray.Parse(j["params"].ToString());
                        tr.Params = j["params"] == null ? null : method.SerializeParams(p.ToObject <string[]>());

                        var resp = CallTransaction(tr);

                        if (resp == null)
                        {
                            _screenManager.PrintError(ServerConnError);
                            return;
                        }
                        if (resp.IsEmpty())
                        {
                            _screenManager.PrintError(NoReplyContentError);
                            return;
                        }
                        JObject jObj = JObject.Parse(resp);

                        string toPrint = def.GetPrintString(JObject.FromObject(jObj["result"]));
                        _screenManager.PrintLine(toPrint);
                    }
                    else if (def is AccountCmd)
                    {
                        _accountManager.ProcessCommand(parsedCmd);
                    }
                    else if (def is CertificateCmd)
                    {
                        _certificatManager.ProcCmd(parsedCmd);
                    }
                }
                else
                {
                    try
                    {
                        // RPC
                        HttpRequestor reqhttp = new HttpRequestor(_rpcAddress);
                        string        resp    = reqhttp.DoRequest(def.BuildRequest(parsedCmd).ToString(), def.GetUrl());

                        if (resp == null)
                        {
                            _screenManager.PrintError(ServerConnError);
                            return;
                        }

                        if (resp.IsEmpty())
                        {
                            _screenManager.PrintError(NoReplyContentError);
                            return;
                        }

                        JObject jObj = JObject.Parse(resp);

                        var j = jObj["result"];

                        if (j["error"] != null)
                        {
                            _screenManager.PrintLine(j["error"].ToString());
                            return;
                        }

                        if (j["result"]?["BasicContractZero"] != null)
                        {
                            _genesisAddress = j["result"]["BasicContractZero"].ToString();
                        }

                        string toPrint = def.GetPrintString(JObject.FromObject(j));

                        _screenManager.PrintLine(toPrint);
                    }
                    catch (Exception e)
                    {
                        if (e is UriFormatException)
                        {
                            _screenManager.PrintError(UriFormatEroor);
                            return;
                        }

                        if (e is JsonReaderException)
                        {
                            _screenManager.PrintError(WrongInputFormat);
                            return;
                        }
                    }
                }
            }
        }