예제 #1
0
        static void Main(string[] args)
        {
            // initialize a logger
            var log = new SynkServer.Core.Logger();

            // either parse the settings from the program args or initialize them manually
            var settings = ServerSettings.Parse(args);

            var server = new HTTPServer(log, settings);

            // instantiate a new site, the second argument is the file path where the public site contents will be found
            var site = new Site(server, "public");

            site.Get("/", (request) =>
            {
                return(HTTPResponse.Redirect("/index.html"));
            });

            server.Run();
        }
예제 #2
0
        static void Main(string[] args)
        {
            // initialize a logger
            var log = new SynkServer.Core.Logger();

            // either parse the settings from the program args or initialize them manually
            var settings = ServerSettings.Parse(args);

            var server = new HTTPServer(log, settings);

            var templateEngine = new TemplateEngine(server, "../views");

            // instantiate a new site, the second argument is the file path where the public site contents will be found
            var site = new Site(server, "../public");

            var base_code = File.ReadAllText(settings.path + "/../DefaultContract.cs");

            site.Get("/", (request) =>
            {
                var context     = new Dictionary <string, object>();
                context["code"] = request.session.Get <string>("code", base_code);

                return(templateEngine.Render(site, context, new string[] { "index" }));
            });

            site.Post("/compile", (request) =>
            {
                var code = request.args["code"];
                request.session.Set("code", code);

                if (Compile(settings, code))
                {
                    return("OK");
                }

                return("FAIL");
            });

            server.Run();
        }
예제 #3
0
        private static void Main(string[] args)
        {
            var log = new SynkServer.Core.Logger();

            var settings = ServerSettings.Parse(args);

            var server = new HTTPServer(log, settings);
            var site   = new Site(server, "public");

            var keys  = new Dictionary <string, KeyPair>();
            var lines = File.ReadAllLines(rootPath + "keys.txt");

            log.Info("Loadking keys...");
            foreach (var line in lines)
            {
                var temp = line.Split(',');
                var mail = temp[0];
                var key  = temp[1];
                keys[mail] = new KeyPair(key.HexToBytes());
            }
            log.Info($"Loaded {keys.Count} keys!");

            log.Info("Initializing mailboxes...");

            var custom_mailboxes  = new ConcurrentDictionary <string, Mailbox>();
            var default_mailboxes = new ConcurrentDictionary <string, Mailbox>();

            foreach (var entry in keys)
            {
                var mailbox = new Mailbox(entry.Value);
                default_mailboxes[entry.Key] = mailbox;

                if (string.IsNullOrEmpty(mailbox.name))
                {
                    log.Info("Registering mail: " + entry.Key);
                    mailbox.RegisterName(entry.Key);
                }
            }

            if (File.Exists(rootPath + whitelistFileName))
            {
                var xml  = File.ReadAllText(rootPath + whitelistFileName);
                var root = XMLReader.ReadFromString(xml);

                try
                {
                    root = root["users"];

                    foreach (var node in root.Children)
                    {
                        if (node.Name.Equals("whitelistuser"))
                        {
                            var user = node.ToObject <WhitelistUser>();
                            if (user != null)
                            {
                                whitelist.Add(user);
                                whitelistEmailMap[user.email]   = user;
                                whitelistWalletMap[user.wallet] = user;
                            }
                        }
                    }
                }
                catch
                {
                    Console.WriteLine("Error loading whitelist!");
                }
            }

            Console.WriteLine("Initializing server...");

            var cache = new FileCache(log, rootPath);

            Console.CancelKeyPress += delegate {
                Console.WriteLine("Closing service.");
                server.Stop();
                Environment.Exit(0);
            };

            var templateEngine = new TemplateEngine("views");

            site.Get("/", (request) =>
            {
                return(HTTPResponse.FromString(File.ReadAllText(rootPath + "home.html")));
            });

            site.Get("/terms", (request) =>
            {
                return(File.ReadAllBytes(rootPath + "terms.html"));
            });

            site.Get("/demo", (request) =>
            {
                var currentMailbox = request.session.Get <Mailbox>("current", default_mailboxes.Values.FirstOrDefault());
                var context        = new Dictionary <string, object>();

                var mailboxList = default_mailboxes.Values.ToList();

                var customMailbox = request.session.Get <Mailbox>("custom");
                if (customMailbox != null)
                {
                    mailboxList.Add(customMailbox);
                }

                context["mailboxes"] = mailboxList;

                context["currentMailbox"] = currentMailbox.name;
                context["currentAddress"] = currentMailbox.address;

                var mails = new List <MailEntry>();

                lock (currentMailbox)
                {
                    foreach (Mail entry in currentMailbox.messages)
                    {
                        var mail = new MailEntry()
                        {
                            from    = entry.fromAddress.Split('@')[0],
                            subject = entry.subject,
                            body    = entry.body,
                            date    = "12:10 AM"
                        };

                        mails.Insert(0, mail);
                    }
                }

                context["mails"] = mails.ToArray();
                context["empty"] = mails.Count == 0;

                var flash = request.session.Get <string>("flash");
                if (flash != null)
                {
                    context["flash"] = flash;
                    request.session.Remove("flash");
                }

                return(templateEngine.Render(site, context, new string[] { "demo" }));
            });

            site.Get("/demo/inbox/{id}", (request) =>
            {
                var id = request.args["id"];
                if (default_mailboxes.ContainsKey(id))
                {
                    var mailbox = default_mailboxes[id];
                    request.session.Set("current", mailbox);
                }
                else
                if (custom_mailboxes.ContainsKey(id))
                {
                    var mailbox = custom_mailboxes[id];
                    request.session.Set("current", mailbox);
                }
                return(HTTPResponse.Redirect("/demo"));
            });

            site.Post("/demo/custom", (request) =>
            {
                var emailStr = request.args["email"];

                var privateStr = request.args["private"];
                var privateKey = privateStr.HexToBytes();

                if (privateKey.Length == 32)
                {
                    var customKeys = new KeyPair(privateKey);
                    var mailbox    = new Mailbox(customKeys);

                    if (string.IsNullOrEmpty(mailbox.name))
                    {
                        mailbox.RegisterName(emailStr);
                    }
                    else
                    if (mailbox.name != emailStr)
                    {
                        request.session.Set("flash", "Wrong mail for this address");
                        return(HTTPResponse.Redirect("/demo"));
                    }

                    request.session.Set("current", mailbox);
                    request.session.Set("custom", mailbox);

                    if (!custom_mailboxes.ContainsKey(emailStr))
                    {
                        custom_mailboxes[emailStr] = mailbox;
                        lock (mailbox)
                        {
                            mailbox.SyncMessages();
                        }
                    }
                }

                return(HTTPResponse.Redirect("/demo"));
            });

            site.Post("/demo/send", (request) =>
            {
                var to      = request.args["to"];
                var subject = request.args["subject"];
                var body    = request.args["body"];

                var script = NeoAPI.GenerateScript(Protocol.scriptHash, "getAddressFromMailbox", new object[] { to });
                var invoke = NeoAPI.TestInvokeScript(Protocol.net, script);

                var temp = (byte[])invoke.result;
                if (temp != null && temp.Length > 0)
                {
                    var currentMailbox = request.session.Get <Mailbox>("current");

                    if (currentMailbox == null || string.IsNullOrEmpty(currentMailbox.name))
                    {
                        request.session.Set("flash", "Invalid mailbox selected");
                    }
                    else
                    {
                        var msg = Mail.Create(currentMailbox, to, subject, body);

                        try
                        {
                            if (currentMailbox.SendMessage(msg))
                            {
                                request.session.Set("flash", "Your message was sent to " + to);
                            }
                        }

                        catch (Exception e)
                        {
                            request.session.Set("flash", e.Message);
                        }
                    }
                }
                else
                {
                    request.session.Set("flash", to + " is not a valid Phantasma mailbox address");
                }

                return(HTTPResponse.Redirect("/demo"));
            });


            site.Post("/signup", (request) =>
            {
                var fullName = request.GetVariable("whitelist_name");
                var email    = request.GetVariable("whitelist_email");
                var wallet   = request.GetVariable("whitelist_wallet");
                var country  = request.GetVariable("whitelist_country");

                var captcha   = request.GetVariable("whitelist_captcha");
                var signature = request.GetVariable("whitelist_signature");

                string error = null;

                if (string.IsNullOrEmpty(fullName) || fullName.Length <= 5)
                {
                    error = "Full name is invalid";
                }
                else
                if (string.IsNullOrEmpty(email) || !email.Contains("@") || !email.Contains("."))
                {
                    error = "Email is invalid";
                }
                else
                if (string.IsNullOrEmpty(wallet) || !wallet.ToLower().StartsWith("a") || !WalletHelper.IsValidWallet(wallet))
                {
                    error = "Wallet does not seems to be a valid NEO address";
                }
                else
                if (string.IsNullOrEmpty(country))
                {
                    error = "Country is invalid";
                }
                else
                if (string.IsNullOrEmpty(captcha) || !CaptchaUtils.VerifyCatcha(captcha, signature))
                {
                    error = "Captcha is invalid";
                }
                else
                if (PhantasmaSite.whitelistEmailMap.ContainsKey(email))
                {
                    error = "Email already registered";
                }
                else
                if (PhantasmaSite.whitelistWalletMap.ContainsKey(wallet))
                {
                    error = "Wallet already registered";
                }

                var root = DataNode.CreateObject("signup");
                root.AddField("result", error != null ? "fail" : "success");

                if (error != null)
                {
                    root.AddField("error", error);
                }
                else
                {
                    var user     = new WhitelistUser();
                    user.name    = fullName;
                    user.email   = email;
                    user.wallet  = wallet;
                    user.country = country;

                    PhantasmaSite.AddToWhitelist(user);
                }

                var json = JSONWriter.WriteToString(root);
                return(Encoding.UTF8.GetBytes(json));
            });

            site.Get("captcha/", (request) =>
            {
                var content = File.ReadAllText(rootPath + "captcha.html");

                string sign;
                string pic;
                CaptchaUtils.GenerateCaptcha(rootPath + "captcha.fnt", out sign, out pic);

                content = content.Replace("$SIGNATURE", sign).Replace("$CAPTCHA", pic);

                return(Encoding.UTF8.GetBytes(content));
            });

            #region EMAIL SYNC THREAD
            log.Info("Running email thread");

            var emailThread = new Thread(() =>
            {
                Thread.CurrentThread.IsBackground = true;

                do
                {
                    foreach (var mailbox in default_mailboxes.Values)
                    {
                        try
                        {
                            lock (mailbox)
                            {
                                mailbox.SyncMessages();
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    foreach (var mailbox in custom_mailboxes.Values)
                    {
                        try
                        {
                            lock (mailbox)
                            {
                                mailbox.SyncMessages();
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }

                    var delay = (int)(TimeSpan.FromSeconds(5).TotalMilliseconds);
                    Thread.Sleep(delay);
                } while (true);
            });

            emailThread.Start();
            #endregion

            server.Run();
        }
예제 #4
0
        public Backend(ServerSettings serverSettings)
        {
            var settings = new DebuggerSettings(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

            var curPath = Directory.GetCurrentDirectory();

            if (!settings.compilerPaths.ContainsKey(SourceLanguage.CSharp))
            {
                settings.compilerPaths[SourceLanguage.CSharp] = curPath + "/compilers";
            }

            if (!settings.compilerPaths.ContainsKey(SourceLanguage.Python))
            {
                settings.compilerPaths[SourceLanguage.Python] = curPath + "/compilers";
            }

            _debugger = new DebugManager(settings);
            _shell    = new DebuggerShell(_debugger);

            // initialize a logger
            var log = new SynkServer.Core.Logger();

            var server = new HTTPServer(log, serverSettings);

            var templateEngine = new TemplateEngine(server, "../views");

            // instantiate a new site, the second argument is the file path where the public site contents will be found
            var site = new Site(server, "../public");

            LoadContract(curPath + "/contracts/DefaultContract.cs");

            site.Get("/", (request) =>
            {
                var context = GetContext();

                return(templateEngine.Render(site, context, new string[] { "index" }));
            });

            site.Post("/switch", (request) =>
            {
                var code = request.args["code"];
                projectFiles[this.activeDocumentID].content = code;

                this.activeDocumentID = request.args["id"];

                var context = GetContext();

                return("ok");
            });

            site.Get("/content", (request) =>
            {
                var content = projectFiles[activeDocumentID].content;
                return(content);
            });

            site.Get("/breakpoint/list", (request) =>
            {
                var breakpoints = projectFiles[activeDocumentID].breakpoints;
                var node        = DataNode.CreateArray();
                foreach (var line in breakpoints)
                {
                    var item = DataNode.CreateValue(line);
                    node.AddNode(item);
                }
                return(node);
            });

            site.Post("/breakpoint/add", (request) =>
            {
                int line = int.Parse(request.args["line"]);

                var file = projectFiles[activeDocumentID];
                if (_debugger.AddBreakpoint(line, file.path))
                {
                    var breakpoints = file.breakpoints;
                    breakpoints.Add(line);

                    return("ok");
                }

                return("fail");
            });

            site.Post("/breakpoint/remove", (request) =>
            {
                int line = int.Parse(request.args["line"]);

                var file        = projectFiles[activeDocumentID];
                var breakpoints = file.breakpoints;

                breakpoints.Remove(line);

                _debugger.RemoveBreakpoint(line, file.path);

                return("ok");
            });

            site.Post("/compile", (request) =>
            {
                var code = request.args["code"];
                request.session.Set("code", code);

                if (Compile(serverSettings, code))
                {
                    return("OK");
                }

                return("FAIL");
            });

            site.Post("/shell", (request) =>
            {
                var input  = request.args["input"];
                var output = DataNode.CreateObject();

                var lines = DataNode.CreateArray("lines");
                output.AddNode(lines);

                if (!_shell.Execute(input, (type, text) =>
                {
                    lines.AddValue(text);
                }))
                {
                    output.AddValue("Invalid command");
                }

                string filePath;
                var curLine = _shell.Debugger.ResolveLine(_shell.Debugger.Info.offset, true, out filePath);

                output.AddField("state", _shell.Debugger.Info.state);
                output.AddField("offset", _shell.Debugger.Info.offset);
                output.AddField("line", curLine);
                output.AddField("path", filePath);

                if (_shell.Debugger.Info.state == Emulation.DebuggerState.State.Finished)
                {
                    var val = _debugger.Emulator.GetOutput();

                    _debugger.Blockchain.Save();

                    var methodName = _debugger.Emulator.currentMethod;
                    var hintType   = !string.IsNullOrEmpty(methodName) && _debugger.ABI != null && _debugger.ABI.functions.ContainsKey(methodName) ? _debugger.ABI.functions[methodName].returnType : Emulator.Type.Unknown;

                    var temp = FormattingUtils.StackItemAsString(val, false, hintType);
                    output.AddField("result", temp);
                    output.AddField("gas", _debugger.Emulator.usedGas);
                }

                var json = JSONWriter.WriteToString(output);
                return(json);
            });

            server.Run();
        }
예제 #5
0
        public Backend(ServerSettings serverSettings)
        {
            var settings = new DebuggerSettings(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

            var curPath = Directory.GetCurrentDirectory();

            if (!settings.compilerPaths.ContainsKey(SourceLanguage.CSharp))
            {
                settings.compilerPaths[SourceLanguage.CSharp] = curPath + "/compilers";
            }

            if (!settings.compilerPaths.ContainsKey(SourceLanguage.Python))
            {
                settings.compilerPaths[SourceLanguage.Python] = curPath + "/compilers";
            }

            _shell = new DebuggerShell(settings);

            // initialize a logger
            var log = new SynkServer.Core.Logger();

            var server = new HTTPServer(log, serverSettings);

            var templateEngine = new TemplateEngine(server, "../views");

            // instantiate a new site, the second argument is the file path where the public site contents will be found
            var site = new Site(server, "../public");

            LoadContract(curPath + "/contracts/DefaultContract.cs");

            site.Get("/", (request) =>
            {
                var context = GetContext();

                return(templateEngine.Render(site, context, new string[] { "index" }));
            });

            site.Post("/switch", (request) =>
            {
                var code = request.args["code"];
                projectFiles[this.activeDocumentID].content = code;

                this.activeDocumentID = request.args["id"];

                var context = GetContext();

                return("ok");
            });

            site.Get("/content", (request) =>
            {
                var content = projectFiles[activeDocumentID].content;
                return(content);
            });

            site.Get("/breakpoint/list", (request) =>
            {
                var breakpoints = projectFiles[activeDocumentID].breakpoints;
                var node        = DataNode.CreateArray();
                foreach (var line in breakpoints)
                {
                    var item = DataNode.CreateValue(line);
                    node.AddNode(item);
                }
                return(node);
            });

            site.Post("/breakpoint/add", (request) =>
            {
                int line = int.Parse(request.args["line"]);

                var breakpoints = projectFiles[activeDocumentID].breakpoints;
                breakpoints.Add(line);

                return("ok");
            });

            site.Post("/breakpoint/remove", (request) =>
            {
                int line = int.Parse(request.args["line"]);

                var breakpoints = projectFiles[activeDocumentID].breakpoints;
                breakpoints.Remove(line);

                return("ok");
            });

            site.Post("/compile", (request) =>
            {
                var code = request.args["code"];
                request.session.Set("code", code);

                if (Compile(serverSettings, code))
                {
                    return("OK");
                }

                return("FAIL");
            });

            site.Post("/shell", (request) =>
            {
                var input  = request.args["input"];
                var output = new StringBuilder();

                _shell.Execute(input, (type, text) =>
                {
                    output.AppendLine(text);
                });

                return(output.ToString());
            });

            server.Run();
        }