Exemple #1
0
        public void RegisterUserHooks()
        {
            var directory = PlatformUtils.CombineDataPath("scripts");

            Log.Information($"User script directory: {directory}");

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            var files = Directory.GetFiles(directory, "*.cs", SearchOption.TopDirectoryOnly);

            Log.Information($"ScriptManager: {files.Length} user script(s) found");

            foreach (var file in files.Where(x => x != null))
            {
                try
                {
                    var script = File.ReadAllText(file);
                    RegisterHook((IHook)CSScript.Evaluator.LoadCode(script));
                    Log.Debug($"ScriptManager: {Path.GetFileName(file)} hooked successfully");
                }
                catch (CompilerException ex)
                {
                    Log.Error($"[{Path.GetFileName(file)}]: Compiler error in user script : {ex.Message}");
                }
                catch (Exception ex)
                {
                    Log.Error($"[{Path.GetFileName(file)}]: Failed to hook user script: {ex.Message}");
                }
            }
        }
Exemple #2
0
        public PeerChainStateQuery(StandaloneContext standaloneContext)
        {
            Field <NonNullGraphType <ListGraphType <StringGraphType> > >(
                name: "state",
                resolve: context =>
            {
                var service = standaloneContext.NineChroniclesNodeService;

                if (service is null)
                {
                    Log.Error($"{nameof(NineChroniclesNodeService)} is null.");
                    return(null);
                }

                var swarm       = service.Swarm;
                var chain       = swarm.BlockChain;
                var chainStates = new List <string>
                {
                    $"{swarm.AsPeer.Address}, {chain.Tip.Index}, {chain.Tip.TotalDifficulty}"
                };

                var peerChainState = swarm.GetPeerChainStateAsync(
                    TimeSpan.FromSeconds(5), default)
                                     .Result
                                     .Select(
                    state => $"{state.Peer.Address}, {state.TipIndex}, {state.TotalDifficulty}");

                chainStates.AddRange(peerChainState);

                return(chainStates);
            }
                );
        }
Exemple #3
0
        public void Log(TraceLevel level, string message, Exception ex)
        {
            switch (level)
            {
            case TraceLevel.Debug:
                SerilogLog.Debug(message);
                break;

            case TraceLevel.Info:
                SerilogLog.Information(message);
                break;

            case TraceLevel.Warn:
                SerilogLog.Warning(message);
                break;

            case TraceLevel.Error:
                SerilogLog.Error(ex, message);
                break;

            case TraceLevel.Fatal:
                SerilogLog.Fatal(ex, message);
                break;
            }
        }
Exemple #4
0
        public ActivationStatusQuery(StandaloneContext standaloneContext)
        {
            Field <NonNullGraphType <BooleanGraphType> >(
                name: "activated",
                resolve: context =>
            {
                var service = standaloneContext.NineChroniclesNodeService;

                if (service is null)
                {
                    return(false);
                }

                try
                {
                    if (!(service.MinerPrivateKey is { } privateKey))
                    {
                        throw new InvalidOperationException($"{nameof(service.MinerPrivateKey)} is null.");
                    }

                    if (!(service.Swarm?.BlockChain is { } blockChain))
                    {
                        throw new InvalidOperationException($"{nameof(service.Swarm.BlockChain)} is null.");
                    }

                    Address userAddress      = privateKey.ToAddress();
                    Address activatedAddress = userAddress.Derive(ActivationKey.DeriveKey);

                    if (blockChain.GetState(activatedAddress) is Bencodex.Types.Boolean)
                    {
                        return(true);
                    }

                    // Preserve previous check code due to migration period.
                    // TODO: Remove this code after v100061+
                    IValue state = blockChain.GetState(ActivatedAccountsState.Address);

                    if (state is Bencodex.Types.Dictionary asDict)
                    {
                        var activatedAccountsState = new ActivatedAccountsState(asDict);
                        var activatedAccounts      = activatedAccountsState.Accounts;
                        return(activatedAccounts.Count == 0 ||
                               activatedAccounts.Contains(userAddress));
                    }

                    return(true);
                }
                catch (Exception e)
                {
                    var msg = "Unexpected exception occurred during ActivationStatusQuery: {e}";
                    context.Errors.Add(new ExecutionError(msg, e));
                    Log.Error(msg, e);
                    return(false);
                }
            }
                );
        }
Exemple #5
0
 public EventStoreService(
     IEventStoreConnection esConnection,
     Props subscriptionManager)
 {
     _esConnection        = esConnection;
     _subscriptionManager = subscriptionManager;
     _supervisor          = new ConnectionSupervisor(
         esConnection,
         () => Log.Fatal("Fatal failure with EventStore connection"));
 }
Exemple #6
0
 public void UnregisterHook(IHook hook)
 {
     try
     {
         Hooks.Remove(hook);
         hook.OnUnhooked();
     }
     catch (Exception ex)
     {
         Log.Error("ScriptManager.UnregisterHook: " + ex);
     }
 }
Exemple #7
0
        private void LaunchExperiment(ExperimentRequest e)
        {
            if (_activeExperiment != null)
            {
                Log.Warning($"ExperimentRuntime: Skipped. Another experiment (#{_activeExperiment?.Id}) is already running.");
                return;
            }

            if (string.IsNullOrEmpty(e.Script))
            {
                Log.Warning($"ExperimentRuntime: Experiment #{_activeExperiment?.Id} has an empty script.");
                return;
            }

            _activeExperiment = e;

            _experimentTimeLimit = new Timer
            {
                Interval  = (e.TimeConstraint ?? 60) * 1000,
                AutoReset = false
            };
            _experimentTimeLimit.Elapsed += (sender, args) =>
            {
                Log.Warning($"ExperimentRuntime: Experiment #{e.Id} cancelled. Time constraint of {_experimentTimeLimit.Interval / 1000} seconds exceeded");
                ReportResult(new ExperimentRuntimeResult(-2, string.Empty, $"TIMEOUT ({_experimentTimeLimit.Interval / 1000}s)"));
            };
            _experimentTimeLimit.Start();

            Log.Debug($"ExperimentRuntime: Launching experiment id #{e.Id} ({e.Name})");
            try
            {
                try
                {
                    _activeExperimentHook           = (IExperimentBase)CSScript.Evaluator.LoadCode(e.Script);
                    _activeExperimentHook.Finished += ReportResult;

                    Log.Debug($"ExperimentRuntime: Experiment #{e.Id} hooked");

                    ScriptManager.Instance.RegisterHook(_activeExperimentHook);
                }
                catch (CompilerException ex)
                {
                    Log.Error($"ScriptManager.RegisterHook: Compiler error: {ex.Message}");
                    ReportResult(new ExperimentRuntimeResult(-3, ex.Message, $"COMPILER_ERROR"));
                }
            }
            catch (Exception ex)
            {
                Log.Error($"ExperimentRuntime: Failed to execute #{e.Id}. Reason: {ex.Message}; Source: {ex.Source}; ({ex})");
                ReportResult(new ExperimentRuntimeResult(-1, $"{ex.Message} (Source: {ex.Source}; Type: {ex.GetType()})", $"GENERIC_LAUNCH_ERROR"));
            }
        }
Exemple #8
0
 public bool IsMarketHoliday()
 {
     try
     {
         var isHoliday = _context.MarketHolidays.Any(x => x.HolidayDate == DateTime.Today);
         return(isHoliday);
     }
     catch (Exception e)
     {
         Log.Fatal(e, $"{nameof(IsMarketHoliday)}");
         return(true);
     }
 }
Exemple #9
0
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            var view = inflater.Inflate(Resource.Layout.fragment_map, container, false);

            Log.Debug($"Create mapControl");
            mapControl = view.FindViewById <MapControl>(Resource.Id.mapcontrol);
            map        = new Mapsui.Map
            {
                CRS            = "EPSG:3857", //https://epsg.io/3857
                Transformation = new MinimalTransformation(),
            };
            mapControl.Map = map;

            Log.Debug($"Cache downloaded tiles");
            var tileSource = TileCache.GetOSMBasemap(MainActivity.rootPath + "/CacheDB.mbtiles");
            var tileLayer  = new TileLayer(tileSource)
            {
                Name = "OSM",
            };

            map.Layers.Add(tileLayer);

            Log.Debug($"Import all offline maps");
            OfflineMaps.LoadAllOfflineMaps();

            Log.Debug($"Add scalebar");
            map.Widgets.Add(new ScaleBarWidget(map)
            {
                MaxWidth    = 300,
                ShowEnvelop = true,
                Font        = new Font {
                    FontFamily = "sans serif", Size = 20
                },
                TickLength             = 15,
                TextColor              = new Color(0, 0, 0, 255),
                Halo                   = new Color(0, 0, 0, 0),
                HorizontalAlignment    = HorizontalAlignment.Left,
                VerticalAlignment      = VerticalAlignment.Bottom,
                TextAlignment          = Alignment.Left,
                ScaleBarMode           = ScaleBarMode.Both,
                UnitConverter          = MetricUnitConverter.Instance,
                SecondaryUnitConverter = NauticalUnitConverter.Instance,
                MarginX                = 10,
                MarginY                = 20,
            });

            Log.Debug($"Set Zoom");
            mapControl.Navigator.ZoomTo(PrefsActivity.MaxZoom);

            return(view);
        }
Exemple #10
0
        private async void ReportResult(ExperimentRuntimeResult runtimeResult)
        {
            _experimentTimeLimit?.Stop();

            try
            {
                ExperimentResult result;
                if (_activeExperiment != null)
                {
                    result = new ExperimentResult()
                    {
                        Environment      = CurrentEnvironment(),
                        ExperimentId     = _activeExperiment.Id,
                        Result           = runtimeResult.Result,
                        ResultCode       = runtimeResult.ResultCode,
                        ResultCodeString = runtimeResult.ResultCodeString ??
                                           (runtimeResult.ResultCode == 0 ? "PASS" : "FAIL")
                    };
                }
                else
                {
                    Log.Warning(
                        "ExperimentRuntime.ReportResult: ActiveExperiment is null. Cannot send report and exclude");
                    return;
                }

                Log.Debug($"ExperimentRuntime: Experiment finished with result code {runtimeResult.ResultCode}");

                if (_activeExperimentHook != null)
                {
                    _activeExperimentHook.Finished -= ReportResult;
                    ScriptManager.Instance.UnregisterHook(_activeExperimentHook);
                    Log.Debug("ExperimentRuntime: Experiment unhooked");
                }
                else
                {
                    Log.Warning("ExperimentRuntime: Experiment not unhooked; hook reference is already null");
                }

                await _client.PostResult(result);

                ExcludeExperiment(_activeExperiment.Id);
            }
            catch (Exception ex)
            {
                Log.Error("ExperimentManager: Error while posting results: " + ex);
                SentrySdk.CaptureException(ex);
            }

            NextExperiment();
        }
Exemple #11
0
 public static NMessage FromBytes(byte[] bytes)
 {
     try {
         using (MemoryStream m = new MemoryStream()) {
             m.Write(bytes, 0, bytes.Length);
             m.Seek(0, SeekOrigin.Begin);
             return((NMessage)bf.Deserialize(m));
         }
     }
     catch (Exception e) {
         Log.Warning("Saw invalid message: {e}", e.Message);
         return(null);
     }
 }
Exemple #12
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ModelState.IsValid)
            {
                return;
            }

            var modelStateEntries = filterContext.ModelState.Where(e => e.Value.Errors.Count > 0).ToArray();
            var errors            = new List <ValidationError>();

            var details = "See validation errors for details";

            if (modelStateEntries.Any())
            {
                if (modelStateEntries.Length == 1 &&
                    modelStateEntries[0].Value.Errors.Count == 1 &&
                    string.IsNullOrEmpty(modelStateEntries[0].Key))
                {
                    details = modelStateEntries[0].Value.Errors[0].ErrorMessage;
                }
                else
                {
                    foreach (var(key, value) in modelStateEntries)
                    {
                        foreach (var modelStateError in value.Errors)
                        {
                            errors.Add(new ValidationError(key, modelStateError.ErrorMessage));
                        }
                    }
                }
            }

            var problemDetails = new ProblemDetails()
            {
                Status     = StatusCodes.Status400BadRequest,
                Title      = "Request Validation Error",
                Instance   = $"urn:pygma:bad-request:{Guid.NewGuid()}",
                Detail     = details,
                Extensions =
                {
                    new KeyValuePair <string, object>("validationErrors", errors)
                }
            };

            Log.Warning(JsonSerializer.Serialize(problemDetails));

            filterContext.Result = new BadRequestObjectResult(problemDetails);
        }
Exemple #13
0
        private void OnRefreshOnBuy(object sender, MetaOrder e)
        {
            Log.Warning($"Begin cancel order: {e}");

            _container.Resolve <IBittrexExchange>().CancelOrder(e.OrderId).GetAwaiter().GetResult();

            Log.Warning($"Canceled. Push on sell");

            _container.Resolve <IBusControl>().Publish <BuyCurrency>(new
            {
                Id      = Guid.NewGuid(),
                Created = DateTime.Now,
                Amount  = e.Amount,
                Bid     = e.Rate
            }).GetAwaiter().GetResult();
        }
Exemple #14
0
        private GameController()
        {
            _px = PostOffice.Instance;
            _px.OnProposeGameMessageSeen += message => {
                if (!VisibleInvitations.Contains(message.Invitation))
                {
                    VisibleInvitations.Add(message.Invitation);
                }
                Log.Information("Added {game} to Visible Invitations",
                                message.Invitation.GameName);
                //Don't process announce game messages; we might want to be 'reminded' of them
                //px.ProcessMessage(message);
            };

            _px.OnProposeGameMessageWithdrawn += message => {
                Device.BeginInvokeOnMainThread(() =>
                                               VisibleInvitations.Remove(message.Invitation));
            };
        }
Exemple #15
0
        public ActivationStatusQuery(StandaloneContext standaloneContext)
        {
            Field <NonNullGraphType <BooleanGraphType> >(
                name: "activated",
                resolve: context =>
            {
                var service = standaloneContext.NineChroniclesNodeService;

                if (service is null)
                {
                    return(false);
                }

                try
                {
                    PrivateKey privateKey = service.PrivateKey;
                    Address address       = privateKey.ToAddress();
                    BlockChain <NineChroniclesActionType> blockChain = service.Swarm.BlockChain;
                    IValue state = blockChain.GetState(ActivatedAccountsState.Address);

                    if (state is Bencodex.Types.Dictionary asDict)
                    {
                        var activatedAccountsState = new ActivatedAccountsState(asDict);
                        var activatedAccounts      = activatedAccountsState.Accounts;
                        return(activatedAccounts.Count == 0 ||
                               activatedAccounts.Contains(address));
                    }

                    return(true);
                }
                catch (Exception e)
                {
                    var msg = "Unexpected exception occurred during ActivationStatusQuery: {e}";
                    context.Errors.Add(new ExecutionError(msg, e));
                    Log.Error(msg, e);
                    return(false);
                }
            }
                );
        }
Exemple #16
0
        public PeerChainStateQuery(StandaloneContext standaloneContext)
        {
            Field <NonNullGraphType <ListGraphType <StringGraphType> > >(
                name: "state",
                description: "Summary of other peers connected to this node. It consists of address, chain height, and total difficulty.",
                resolve: context =>
            {
                var service = standaloneContext.NineChroniclesNodeService;
                if (service is null)
                {
                    Log.Error($"{nameof(NineChroniclesNodeService)} is null.");
                    return(null);
                }

                var swarm = service.Swarm;
                if (!(swarm?.BlockChain is { } chain))
                {
                    throw new InvalidOperationException($"{nameof(swarm.BlockChain)} is null.");
                }

                var chainStates = new List <string>
                {
                    $"{swarm.AsPeer.Address}, {chain.Tip.Index}, {chain.Tip.TotalDifficulty}"
                };

                var peerChainState = swarm.GetPeerChainStateAsync(
                    TimeSpan.FromSeconds(5), default)
                                     .Result
                                     .Select(
                    state => $"{state.Peer.Address}, {state.TipIndex}, {state.TotalDifficulty}");

                chainStates.AddRange(peerChainState);

                return(chainStates);
            }
                );
        }
Exemple #17
0
 public void Error <T>(string template, T value) => SLog.Error(template, value);
Exemple #18
0
 public void Info <T>(string template, T value) => SLog.Information(template, value);
Exemple #19
0
 public void Warn <T>(string template, T value) => SLog.Warning(template, value);
Exemple #20
0
 /// <summary>
 /// Writes sensitive information to <see cref="Serilogger.Information(string)"/>
 /// </summary>
 protected override void LogSensitiveString(string message)
 {
     Serilogger.Information(message);
 }
Exemple #21
0
        public bool Start(HostControl hostControl)
        {
            #region print info
            Log.Information($"Service {Name} v.{Version} starting...");

            Log.Information($"Name: {Name}");
            Log.Information($"Title: {Title}");
            Log.Information($"Description: {Description}");
            Log.Information($"Version: {Version}");

            _settings = new ExchangeSettings();
            _settings.Load();

            Log.Information($"");
            Log.Information($"Settings: ");
            Log.Information($"BITTREX");
            Log.Information($"BITTREX KEY: {_settings.Bittrex.Key}");
            Log.Information($"BITTREX SECRET: {_settings.Bittrex.Secret}");
            Log.Information($"BITTREX MARKET: {_settings.Bittrex.Market}");

            Log.Information($"");
            Log.Information($"Risk manager");
            Log.Information($"Risk manager type: {_settings.Bittrex.RiskManager.Type}");
            Log.Information($"Risk manager balance min limit: {_settings.Bittrex.RiskManager.BalanceMinLimit}");
            Log.Information($"Risk manager percent: {_settings.Bittrex.RiskManager.Percent}");
            Log.Information($"Risk manager amount: {_settings.Bittrex.RiskManager.Amount}");
            Log.Information($"Risk manager currency: {_settings.Bittrex.RiskManager.BaseCurrency}");

            Log.Information($"");
            Log.Information($"MongoDB");
            Log.Information($"Db connection: {_settings.Db.DbConnectoin}");
            Log.Information($"Db name: {_settings.Db.DbName}");

            Log.Information($"");
            Log.Information($"RabbitMQ");
            Log.Information($"RabbitMQ host: {_settings.RabbitMQ.Host}");
            Log.Information($"RabbitMQ concurrency limit: {_settings.RabbitMQ.ConcurrencyLimit}");
            Log.Information($"");

            Log.Information($"");
            Log.Information($"Telegram");
            Log.Information($"Telegram enabled: {_settings.Telegram.Enabled}");
            Log.Information($"Telegram phone number: {_settings.Telegram.PhoneNumber}");
            Log.Information($"Telegram api key: {_settings.Telegram.ApiKey}");
            Log.Information($"Telegram api hash: {_settings.Telegram.ApiHash}");
            Log.Information($"");
            #endregion

            var mongoClient = new MongoClient(_settings.Db.DbConnectoin);
            var database    = mongoClient.GetDatabase(_settings.Db.DbName);

            var telegram = new TelegramIntegrations(_settings.Telegram);
//      var exchange = new BittrexExchange(_settings);

            var builder = new ContainerBuilder();

            builder.RegisterInstance(database).As <IMongoDatabase>().SingleInstance();
            builder.RegisterInstance(telegram).As <ITelegramIntegrations>().SingleInstance();
            builder.RegisterInstance(_settings).SingleInstance();
            builder.RegisterType <BittrexExchange>().As <IBittrexExchange>().SingleInstance();
            builder.RegisterType <ProtocolService>().As <IProtocolService>().SingleInstance();
            builder.RegisterType <BuySellCommandHandler>();

            builder.AddMassTransit(x =>
            {
                x.AddConsumer <BuySellCommandHandler>();
                x.AddConsumer <BuySellFaultHandler>();

                x.AddBus(context => Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host(_settings.RabbitMQ.Host, h => { });

                    x.AddConsumers(Assembly.GetExecutingAssembly());

                    cfg.ReceiveEndpoint(host, "farm_machine", ec =>
                    {
//            ec.ConfigureConsumers(context);
//            ec.ConfigureConsumer<BuySellCommandHandler>(context);
                    });

                    // or, configure the endpoints by convention
                    cfg.ConfigureEndpoints(context);
                }));
            });

            _container = builder.Build();

            _container.Resolve <ITelegramIntegrations>().Start(() =>
            {
                Log.Information("Write code for telegram: ");
                var code = Console.ReadLine();

                return(code);
            }).GetAwaiter().GetResult();

            var ex = _container.Resolve <IBittrexExchange>();
            ex.Init();
            ex.GetPlaceWorker().RefreshOnBuy  += OnRefreshOnBuy;
            ex.GetPlaceWorker().RefreshOnSell += OnRefreshOnSell;

            _container.Resolve <IBusControl>().Start();

            Log.Information($"Service {Name} v.{Version} started");

            return(true);
        }
Exemple #22
0
 /// <summary>
 /// Writes an error message to <see cref="Serilogger.Error(string)"/>
 /// </summary>
 protected override void LogErrorString(string message)
 {
     Serilogger.Error(message);
 }
Exemple #23
0
 /// <summary>
 /// Writes a fatal error message to <see cref="Serilogger.Fatal(string)"/>
 /// </summary>
 protected override void LogFatalErrorString(string message)
 {
     Serilogger.Fatal(message);
 }
Exemple #24
0
 /// <summary>
 /// Writes a warning message to <see cref="Serilogger.Warning(string)"/>
 /// </summary>
 protected override void LogWarningString(string message)
 {
     Serilogger.Warning(message);
 }
Exemple #25
0
 public void Trace <T>(string template, T value) => SLog.Verbose(template, value);
Exemple #26
0
 /// <summary>
 /// Writes logging progress information such as "Process X is 24% done" to <see cref="Serilogger.Information(string)"/>
 /// </summary>
 protected override void LogProgressString(string message)
 {
     Serilogger.Information(message);
 }
Exemple #27
0
 public void Debug <T>(string template, T value) => SLog.Debug(template, value);
Exemple #28
0
 public void Information(string message) => Logger.Information(message);
Exemple #29
0
 /// <summary>
 /// Writes a debugging message to <see cref="Serilogger.Verbose(string)"/>
 /// </summary>
 protected override void LogDebugString(string message)
 {
     Serilogger.Verbose(message);
 }
Exemple #30
0
 public void Error(Exception exception, string message) => Logger.Error(exception, message);