Ejemplo n.º 1
0
        // Returns the list of Tokens on given page (id), from db
        public object Tokens(int page, int limit)
        {
            if (limit < 10 || limit > 100)
            {
                limit = 25;
            }
            if (page <= 0)
            {
                page = 1;            // Page
            }
            using (var db = CsmonDbContext.Create())
            {
                var tokensCount = db.Tokens.Count();
                var lastPage    = ConvUtils.GetNumPages(tokensCount, limit);

                var tokens = db.Tokens.Skip((page - 1) * limit).Take(limit).ToList();
                // Prepare all data for page and return
                var result = new
                {
                    Tokens       = tokens,
                    Page         = page,
                    HaveNextPage = page < lastPage,
                    LastPage     = lastPage,
                    NumStr       = tokensCount > 0 ? $"{(page - 1) * limit + 1} - {(page - 1) * limit + tokens.Count} of {tokensCount}" : "-"
                };

                for (var i = 1; i <= result.Tokens.Count; i++)
                {
                    result.Tokens[i - 1].Index = i + (page - 1) * limit;
                }

                return(result);
            }
        }
Ejemplo n.º 2
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                // Create states for each network
                foreach (var net in Network.Networks)
                {
                    _states.Add(net.Id, new TpsServiceState());
                }

                // Check DB availability
                using (var db = CsmonDbContext.Create())
                {
                    var unused = db.Tps.Count();
                }

                // Create timers
                _putTimer = new Timer(OnPutTimer, null, _periodPut, 0);
                _getTimer = new Timer(OnGetTimer, null, _periodGet, 0);
            }
            catch (Exception e)
            {
                // Log exception
                _logger.LogError(e, "");
            }
            return(Task.CompletedTask);
        }
Ejemplo n.º 3
0
        private void OnGetTimer(object state)
        {
            using (var db = CsmonDbContext.Create())
            {
                // Delete all points older than a month
                var endDate = DateTime.Now.AddDays(-30);
                var unused  = db.Database.ExecuteSqlCommand($"DELETE Tps WHERE Time < {endDate}");
            }

            // Schedule next time
            _getTimer.Change(_periodGet, 0);
        }
Ejemplo n.º 4
0
        // Points within a month, with 1 day interval
        public TpsInfo GetPointsMonth(string net)
        {
            using (var db = CsmonDbContext.Create())
            {
                // Need data for last month
                var startDate = DateTime.Now.AddDays(-30);
                var endDate   = DateTime.Now;
                // Query points from db
                var points = db.Points.FromSql(
                    $"SELECT dateadd(day, datediff(day, 0, [Time]), 0) as X, Sum(Value) / Count(Value) as Y\r\nFROM Tps\r\nWHERE Time >= {startDate} AND Time <= {endDate} AND Network = {net}\r\nGROUP BY dateadd(day, datediff(day, 0, [Time]), 0)\r\nORDER BY X")
                             .ToArray();

                // Prepare and return result
                return(new TpsInfo {
                    Points = points
                });
            }
        }
Ejemplo n.º 5
0
 // Deletes all points from db, when network restart detected
 public static void Reset(string net)
 {
     Task.Factory.StartNew(() =>
     {
         try
         {
             using (var db = CsmonDbContext.Create())
             {
                 db.Database.ExecuteSqlCommand($"DELETE Tps WHERE Network='{net}'", net);
             }
             NLog.LogManager.GetCurrentClassLogger().Info($"TpsService Reseted network={net}");
         }
         catch (Exception e)
         {
             NLog.LogManager.GetCurrentClassLogger().Error(e);
         }
     });
 }
Ejemplo n.º 6
0
        // Returns Token data by id, from db
        public TokenInfo Token(string id)
        {
            using (var db = CsmonDbContext.Create())
            {
                var token = db.Tokens.FirstOrDefault(t => t.Address == id);
                if (token == null)
                {
                    return(new TokenInfo());
                }

                // Prepare all data for page and return
                var result = new TokenInfo
                {
                    Found        = true,
                    Token        = token,
                    Properties   = db.TokensProperties.Where(tp => tp.TokenAddress == id).ToList(),
                    Transactions = new List <TransactionInfo>()
                };

                return(result);
            }
        }
Ejemplo n.º 7
0
        private void OnPutTimer(object state)
        {
            try
            {
                using (var db = CsmonDbContext.Create())
                {
                    foreach (var network in Network.Networks)
                    {
                        // Get new Tps points from index service and put them in the db
                        var st        = _states[network.Id];
                        var tpsInfo   = _indexService.GetTpsInfo(network.Id);
                        var newPoints = tpsInfo.Points.Where(p => p.X > st.LastTime).ToArray();
                        if (!newPoints.Any())
                        {
                            continue;
                        }
                        st.LastTime = newPoints.Max(p => p.X);
                        db.Tps.AddRange(newPoints.Select(p => new Tp
                        {
                            Network = network.Id,
                            Time    = p.X,
                            Value   = p.Y
                        }));
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception e)
            {
                // Log exception
                _logger.LogError(e, "");
            }

            // Schedule next time
            _putTimer.Change(_periodPut, 0);
        }
Ejemplo n.º 8
0
        // Updates the list of nodes, from signal server
        private async Task UpdateNetworkNodes(Network network)
        {
            // Create a connection to the signal server API
            using (var client = ApiFab.CreateSignalApi(network.SignalIp, network.SignalPort))
            {
                // Get the list of nodes from API
                var result = client.GetActiveNodes();

                // Convert nodes to nodeInfos
                var nodes = result.Nodes.Select(n => new NodeInfo(n)).ToList();

                // Try to get country and geo-location for all nodes
                try
                {
                    // Connect to DB
                    using (var db = CsmonDbContext.Create())
                    {
                        // Get nodes, stored in db
                        var dbNodes = db.Nodes.Where(n => n.Network == network.Id).ToList();

                        // Add new nodes into db and update existing
                        foreach (var node in nodes)
                        {
                            var dbNode = dbNodes.FirstOrDefault(n => n.PublicKey.Equals(node.PublicKey));
                            if (dbNode == null)
                            {
                                db.Nodes.Add(new Node(node, network.Id));
                            }
                            else if (!node.EqualsDbNode(dbNode))
                            {
                                db.Nodes.Update(node.UpdateDbNode(dbNode));
                            }
                        }
                        db.SaveChanges();

                        // Get Non-Active nodes from db
                        foreach (var node in dbNodes.Where(n => !nodes.Any(d => d.PublicKey.Equals(n.PublicKey))))
                        {
                            nodes.Add(new NodeInfo(node));
                        }

                        // Find geo data for nodes
                        foreach (var ip in nodes.Select(n => n.Ip).Distinct())
                        {
                            // Try to find node in db by ip address
                            var location = db.Locations.FirstOrDefault(l => l.Ip.Equals(ip));

                            // If not found, try to get info by ip using ipapi.co web service
                            if (location == null)
                            {
                                try
                                {
                                    var uri     = new Uri("https://ipapi.co/" + $"{ip}/json/");
                                    var nodeStr = await GetAsync(uri);

                                    nodeStr     = nodeStr.Replace("\"latitude\": null,", "");
                                    nodeStr     = nodeStr.Replace("\"longitude\": null,", "");
                                    location    = JsonConvert.DeserializeObject <Location>(nodeStr);
                                    location.Ip = ip;
                                    if (location.Org.Length > 64)
                                    {
                                        location.Org = location.Org.Substring(0, 64);
                                    }
                                    // Store data in db
                                    db.Locations.Add(location);
                                    db.SaveChanges();
                                }
                                catch (Exception e)
                                {
                                    _logger.LogError(e, "");
                                    continue;
                                }
                            }

                            // Set location data to nodes
                            foreach (var nodeInfo in nodes.Where(n => n.Ip.Equals(ip)))
                            {
                                nodeInfo.SetLocation(location);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "");
                }

                // Collect additional info about nodes from the network
                try
                {
                    using (var cnt = ApiFab.CreateReleaseApi(network.Ip))
                    {
                        var page = 0;
                        while (true)
                        {
                            var writers = cnt.WritersGet(page++);
                            if (!writers.Writers.Any())
                            {
                                break;
                            }
                            foreach (var writer in writers.Writers)
                            {
                                var key  = Base58Encoding.Encode(writer.Address);
                                var node = nodes.FirstOrDefault(n => n.PublicKey == key);
                                if (node == null)
                                {
                                    continue;
                                }
                                node.TotalFee    = ConvUtils.FormatAmount(writer.FeeCollected);
                                node.TimesWriter = writer.TimesWriter;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(e, "");
                }

                // Hide Ip addresses before output
                foreach (var nodeInfo in nodes)
                {
                    nodeInfo.HideIp();
                }

                // Put the ordered list into the storage
                _states[network.Id].Nodes = nodes.OrderByDescending(n => n.Active).ThenBy(n => n.Ip).ToList();
            }
        }