static void Main(string[] args) { Console.WriteLine("Initializing dapp server"); // either parse the settings from the program args or initialize them manually var settings = ServerSettings.Parse(args); var server = new HTTPServer(settings, ConsoleLogger.Write); Console.WriteLine("Starting Phantasma Dapp samples at port " + settings.Port); server.Get("/", (request) => { return(HTTPResponse.FromString("Hello world!")); }); Console.CancelKeyPress += delegate { server.Stop(); }; // uncomment this line to enable sample connector, comment if you want to use Poltergeist or Phantom new Thread(() => RunConnector()).Start(); server.Run(); }
private object HandleRPCRequest(string id, string method, DataNode paramNode) { object result = null; if (_handlers.ContainsKey(method)) { if (paramNode == null) { return(GenerateRPCError("Invalid params", -32602)); } try { var handler = _handlers[method]; result = handler(paramNode); } catch (RPCException e) { return(GenerateRPCError(e.Message, -32603)); } catch { return(GenerateRPCError("Internal error", -32603)); } } else { return(GenerateRPCError("Method not found", -32601)); } if (result == null) { return(GenerateRPCError("Missing result", -32603)); } string content; if (result is DataNode) { content = JSONWriter.WriteToString((DataNode)result); } else if (result is string) { content = (string)result; } else { return(GenerateRPCError("Not implemented", -32603)); } return(HTTPResponse.FromString("{\"jsonrpc\": \"2.0\", \"result\": " + content + ", \"id\": " + id + "}", HTTPCode.OK, Server.Settings.Compression, "application/json")); }
private HTTPResponse GenerateRPCError(string msg, int code = -32000, int id = 0) { return(HTTPResponse.FromString("{\"jsonrpc\": \"2.0\", \"error\": {\"code\": " + code + ", \"message\": \"" + msg + "\"}, \"id\": " + id + "}", HTTPCode.OK, Server.Settings.Compression, "application/json")); }
static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; if (args.Length == 0) { args = new string[] { "--path=" + Path.GetFullPath("../Frontend"), "--api=http://localhost:7077/rpc", }; } string apiHost = null; var apiTag = "--api"; foreach (var arg in args) { if (arg.StartsWith(apiTag)) { apiHost = arg.Substring(apiTag.Length + 1); } } if (string.IsNullOrEmpty(apiHost)) { Console.WriteLine("Please insert a valid --api argument, should be URL pointing to a valid Phantasma RPC node"); Environment.Exit(-1); } var settings = ServerSettings.Parse(args); var server = new HTTPServer(settings, ConsoleLogger.Write); var templateEngine = new TemplateEngine(server, "views"); Console.WriteLine("Frontend path: " + settings.Path); Console.WriteLine("Phantasma RPC: " + apiHost); /*var locFiles = Directory.GetFiles("Localization", "*.csv"); * foreach (var fileName in locFiles) * { * var language = Path.GetFileNameWithoutExtension(fileName).Split("_")[1]; * LocalizationManager.LoadLocalization(language, fileName); * }*/ phantasmaAPI = new SDK.API(apiHost); GetAllOTC(); Func <HTTPRequest, Dictionary <string, object> > GetContext = (request) => { var context = new Dictionary <string, object>(); context["available_languages"] = LocalizationManager.Languages; var langCode = request.session.GetString("language", "auto"); if (langCode == "auto") { langCode = DetectLanguage(request); request.session.SetString("language", langCode); } context["current_language"] = LocalizationManager.GetLanguage(langCode); context["offers"] = offers; var userAddr = request.session.GetString("userAddr", "empty"); if (userAddr == "empty") { userAddr = request.GetVariable("userAddr"); request.session.SetString("userAddr", userAddr); } context["userAddr"] = userAddr; var provider = request.session.GetString("provider", "none"); if (provider == "none") { provider = request.GetVariable("provider"); request.session.SetString("provider", provider); } context["provider"] = provider; var connector = request.session.GetString("connector", "none"); if (connector == "none") { connector = request.GetVariable("connector"); request.session.SetString("connector", connector); } context["connector"] = connector; var logged = request.session.GetBool("logged", false); context["logged"] = logged; return(context); }; server.Get("/language/{code}", (request) => { var code = request.GetVariable("code"); if (LocalizationManager.GetLanguage(code) != null) { request.session.SetString("language", code); } return(HTTPResponse.Redirect("/")); }); server.Get("/", (request) => { var context = GetContext(request); return(templateEngine.Render(context, "main")); }); server.Post("/login", (request) => { var userAddr = request.GetVariable("address"); var provider = request.GetVariable("provider"); var connector = request.GetVariable("connector"); if (userAddr != null && provider != null && connector != null) { request.session.SetString("userAddr", userAddr); request.session.SetString("provider", provider); request.session.SetString("connector", connector); request.session.SetBool("logged", true); } return(HTTPResponse.FromString("{login:true}")); }); server.Post("/logout", (request) => { var logged = request.session.GetBool("logged", false); if (logged) { request.session.Remove("userAddr"); request.session.Remove("provider"); request.session.Remove("connector"); request.session.Remove("logged"); } return(HTTPResponse.FromString("{logout:true}")); }); server.Get("/offers", (request) => { GetAllOTC(); var context = GetContext(request); return(templateEngine.Render(context, "offer")); }); server.Get("/offers/json", (request) => { GetAllOTC(); var js = new JsonSerializerOptions(); js.WriteIndented = true; js.IgnoreReadOnlyProperties = false; js.IgnoreNullValues = false; var json = JsonSerializer.Serialize(offers, js); string output = "["; offers.ForEach((offer) => { output += "{"; output += $"id:'{offer.ID}',"; output += $"seller:'{offer.seller}',"; output += $"sellSymbol:'{offer.sellSymbol}',"; output += $"sellAmount:{offer.sellAmount},"; output += $"buySymbol:'{offer.buySymbol}',"; output += $"buyAmount:{offer.buyAmount}"; output += "},"; }); output.Remove(output.Length - 1); output += "]"; return(HTTPResponse.FromString(output)); }); server.Run(); bool running = true; Console.CancelKeyPress += delegate { server.Stop(); running = false; }; while (running) { Thread.Sleep(500); } }
static void Main(string[] args) { Console.WriteLine("Initializing Phantasma Block Explorer...."); menus = new List <MenuContext>(); menus.Add(new MenuContext() { Text = "Blocks", Url = "/chain/main", Active = true }); //menus.Add(new MenuContext() { Text = "Transactions", Url = "/transactions", Active = true }); // menus.Add(new MenuContext() { Text = "Chains", Url = "/chains", Active = false }); //menus.Add(new MenuContext() { Text = "Blocks", Url = "/blocks", Active = false }); // menus.Add(new MenuContext() { Text = "Tokens", Url = "/tokens", Active = false }); //menus.Add(new MenuContext() { Text = "Addresses", Url = "/addresses", Active = false }); // TODO this should be updated every 5 minutes or so //soulRate = CoinUtils.GetCoinRate(2827); var defaultCachePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "/Cache"; var explorerArgs = new Arguments(args); var restURL = explorerArgs.GetString("phantasma.rest", "http://localhost:7078/api"); var cachePath = explorerArgs.GetString("cache.path", defaultCachePath); nexus = new NexusData(restURL, cachePath); if (!string.IsNullOrEmpty(cachePath)) { Console.WriteLine("Explorer cache path: " + cachePath); if (!Directory.Exists(cachePath)) { Directory.CreateDirectory(cachePath); } } else { Console.WriteLine("Explorer cache not set"); } Console.WriteLine("Connecting explorer via REST: " + restURL); bool initialized = false; string nexusError = null; new Thread(() => { if (!nexus.Update()) { nexusError = "Initialization failed!"; } initialized = true; Console.WriteLine("Explorer is now ready"); }).Start(); var curPath = Directory.GetCurrentDirectory(); Console.WriteLine("Current path: " + curPath); // initialize a logger // either parse the settings from the program args or initialize them manually var settings = ServerSettings.Parse(args); var server = new HTTPServer(settings, ConsoleLogger.Write); var templateEngine = new TemplateEngine(server, "views"); templateEngine.Compiler.RegisterTag("value", (doc, val) => new ValueTag(doc, val)); templateEngine.Compiler.RegisterTag("number", (doc, val) => new NumberTag(doc, val)); templateEngine.Compiler.RegisterTag("hex", (doc, val) => new HexTag(doc, val)); templateEngine.Compiler.RegisterTag("timeago", (doc, val) => new TimeAgoTag(doc, val)); templateEngine.Compiler.RegisterTag("async", (doc, val) => new AsyncTag(doc, val)); templateEngine.Compiler.RegisterTag("link-chain", (doc, val) => new LinkChainTag(doc, val)); templateEngine.Compiler.RegisterTag("link-tx", (doc, val) => new LinkTransactionTag(doc, val)); templateEngine.Compiler.RegisterTag("link-address", (doc, val) => new LinkAddressTag(nexus, doc, val)); templateEngine.Compiler.RegisterTag("link-block", (doc, val) => new LinkBlockTag(doc, val)); templateEngine.Compiler.RegisterTag("link-org", (doc, val) => new LinkOrganizationTag(doc, val)); templateEngine.Compiler.RegisterTag("description", (doc, val) => new DescriptionTag(doc, val)); templateEngine.Compiler.RegisterTag("externalLink", (doc, val) => new LinkExternalTag(doc, val)); server.Get("/", (request) => { return(HTTPResponse.Redirect("/nexus")); }); server.Get("/progress", (request) => { var progress = "{\"status\": \"" + nexus.UpdateStatus + "\", \"percent\": " + nexus.UpdateProgress + "}"; return(HTTPResponse.FromString(progress, HTTPCode.OK, false, "application/json")); }); server.Get("/nexus", (request) => { var context = CreateContext(); if (!initialized) { context["progress"] = nexus.UpdateProgress; context["status"] = nexusError != null ? nexusError : nexus.UpdateStatus; return(templateEngine.Render(context, "layout", "init")); } context["nexus"] = nexus; return(templateEngine.Render(context, "layout", "nexus")); }); server.Get("/chain/{input}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var chainName = request.GetVariable("input"); var chain = nexus.FindChainByName(chainName); if (chain != null) { var context = CreateContext(); context["chain"] = chain; return(templateEngine.Render(context, "layout", "chain")); } return(Error(templateEngine, "Could not find chain: " + chainName)); }); server.Get("/chains", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var context = CreateContext(); context["chains"] = nexus.Chains; return(templateEngine.Render(context, "layout", "chains")); }); server.Get("/tokens", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var context = CreateContext(); context["tokens"] = nexus.Tokens; return(templateEngine.Render(context, "layout", "tokens")); }); server.Get("/block/{chain}/{hash}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var chainName = request.GetVariable("chain"); var chain = nexus.FindChainByName(chainName); if (chain != null) { var hash = Hash.Parse(request.GetVariable("hash")); var block = nexus.FindBlockByHash(chain, hash); if (block != null) { var context = CreateContext(); context["block"] = block; return(templateEngine.Render(context, "layout", "block")); } else { return(Error(templateEngine, "Could not find block with hash: " + hash)); } } else { return(Error(templateEngine, "Could not find chain with name: " + chainName)); } }); server.Get("/height/{chain}/{index}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var chainName = request.GetVariable("chain"); var chain = nexus.FindChainByName(chainName); if (chain != null) { var height = int.Parse(request.GetVariable("index")); var block = height > 0 && height <= chain.BlockList.Count ? chain.BlockList[height - 1] : null; if (block != null) { var context = CreateContext(); context["block"] = block; return(templateEngine.Render(context, "layout", "block")); } else { return(Error(templateEngine, "Could not find block with height: " + height)); } } else { return(Error(templateEngine, "Could not find chain with name: " + chainName)); } }); server.Get("/tx/{input}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var hash = Hash.Parse(request.GetVariable("input")); var tx = nexus.FindTransaction(nexus.RootChain, hash); if (tx != null) { var context = CreateContext(); context["transaction"] = tx; return(templateEngine.Render(context, "layout", "transaction")); } return(Error(templateEngine, "Could not find transaction with hash: " + hash)); }); server.Get("/dao/{input}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var id = request.GetVariable("input"); var org = nexus.FindOrganization(id); if (org != null) { var context = CreateContext(); context["dao"] = org; return(templateEngine.Render(context, "layout", "dao")); } return(Error(templateEngine, "Could not find organization with id: " + id)); }); server.Get("/token/{input}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var symbol = request.GetVariable("input"); var token = nexus.FindTokenBySymbol(symbol); if (token != null) { var context = CreateContext(); context["token"] = token; return(templateEngine.Render(context, "layout", "token")); } return(Error(templateEngine, "Could not find token with symbol: " + symbol)); }); server.Get("/address/{input}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var address = Address.FromText(request.GetVariable("input")); var account = nexus.FindAccount(address, true); if (account != null) { var context = CreateContext(); context["account"] = account; return(templateEngine.Render(context, "layout", "account")); } return(Error(templateEngine, "Could not find address: " + address)); }); server.Get("/leaderboard/{input}", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var input = request.GetVariable("input"); var leaderboard = nexus.FindLeaderboard(input); if (leaderboard != null) { var context = CreateContext(); context["board"] = leaderboard; return(templateEngine.Render(context, "layout", "leaderboard")); } return(Error(templateEngine, "Could not find season: " + input)); }); server.Post("/nexus", (request) => { if (!initialized) { return(HTTPResponse.Redirect("/nexus")); } var input = request.GetVariable("searchInput"); var results = nexus.SearchItem(input).Select(x => new SearchResultWithURL() { Kind = x.Kind, Text = x.Text, URL = GetURLForSearch(x.Kind, x.Data) }).ToList(); var context = CreateContext(); context["results"] = results; return(templateEngine.Render(context, "layout", "search")); //return Error(templateEngine, "Could not find anything..."); }); bool running = true; new Thread(() => { while (running) { Thread.Sleep(1000 * 30); if (initialized) { nexus.Update(); } } }).Start(); Console.CancelKeyPress += delegate { Console.WriteLine("Terminating explorer..."); running = false; try { server.Stop(); } catch (Exception e) { Console.WriteLine(e.ToString()); } Environment.Exit(0); }; Console.WriteLine($"Explorer running at port {settings.Port}"); server.Run(); }
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(); }
static void Main(string[] args) { var api = new LocalRPCNode(10332, "http://neoscan.io"); //var api = new RemoteRPCNode(10332, "http://neoscan.io"); // initialize a logger var log = new Logger(); var settings = new ServerSettings() { environment = ServerEnvironment.Prod, host = "phantasma.io", path = ".", port = 7733 }; var server = new HTTPServer(log, settings); /*var ips = DNSUtils.LookUp("gmail.com", DNSUtils.DNSKind.MX); * foreach (var ip in ips) * { * Console.WriteLine(ip); * }*/ // 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"); Console.WriteLine("Initializing Phantasma bridge..."); var tx = api.GetTransaction("d56d553f38234d73d04deacd9fd5f110d572898e8bd9c62333bbf7c31e1d1658"); var bridge = new ChainListener(api, tx, /*2313808*/ 2350860, log); var bridgeThread = new Thread(() => { Console.WriteLine("Running Phantasma bridge..."); bridge.Run(); }); bridgeThread.IsBackground = true; bridgeThread.Start(); site.Get("/", (request) => { return(HTTPResponse.FromString("Phantasma Bridge API")); }); site.Get("/api/mailboxes", (request) => { var root = DataNode.CreateArray("mailboxes"); foreach (var mailbox in bridge.Mailboxes) { var node = DataNode.CreateObject("box"); node.AddField("address", mailbox.address); node.AddField("name", mailbox.name); root.AddNode(node); } return(root); }); Console.CancelKeyPress += delegate { Console.WriteLine("Stopping Phantasma bridge..."); server.Stop(); bridge.Stop(); Environment.Exit(0); }; server.Run(); }