public bool SubmitWork(string payoutUser, string jobId, string extraNonce2, string nTime, string nonce) { var context = (StratumContext)JsonRpcContext.Current().Value; ++_submitCounter; return(_shareManager.ProcessShare(context.Miner, jobId, extraNonce2, nTime, nonce, payoutUser).IsValid); }
public SubscribeResponse SubscribeMiner(string signature = null, string sessionId = null) { try{ var context = (StratumContext)JsonRpcContext.Current().Value; var response = new SubscribeResponse { ExtraNonce1 = context.Miner.ExtraNonce.ToString("x8"), // Hex-encoded, per-connection unique string which will be used for coinbase serialization later. (http://mining.bitcoin.cz/stratum-mining) ExtraNonce2Size = ExtraNonce.ExpectedExtraNonce2Size // Represents expected length of extranonce2 which will be generated by the miner. (http://mining.bitcoin.cz/stratum-mining) }; context.Miner.Subscribe(signature); return(response); } catch (Exception e) { _logger.Error(e, "Exception on mining.subscribe"); var context = (StratumContext)JsonRpcContext.Current().Value; var response = new SubscribeResponse { ExtraNonce1 = context.Miner.ExtraNonce.ToString("x8"), // Hex-encoded, per-connection unique string which will be used for coinbase serialization later. (http://mining.bitcoin.cz/stratum-mining) ExtraNonce2Size = ExtraNonce.ExpectedExtraNonce2Size // Represents expected length of extranonce2 which will be generated by the miner. (http://mining.bitcoin.cz/stratum-mining) }; context.Miner.Subscribe(signature); return(response); } }
private void HandleInvalidShare(IShare share) { var miner = (IStratumMiner)share.Miner; if (miner.Username.Equals(share.PayoutUser) && share.Error != ShareError.InsideSleepWindow) { miner.InvalidShareCount++; } JsonRpcException exception = null; // the exception determined by the stratum error code. switch (share.Error) { case ShareError.DuplicateShare: exception = new DuplicateShareError(share.Nonce); break; case ShareError.IncorrectExtraNonce2Size: exception = new OtherError("Incorrect extranonce2 size"); break; case ShareError.IncorrectNTimeSize: exception = new OtherError("Incorrect nTime size"); break; case ShareError.IncorrectNonceSize: exception = new OtherError("Incorrect nonce size"); break; case ShareError.JobNotFound: exception = new JobNotFoundError(share.JobId); break; case ShareError.LowDifficultyShare: exception = new LowDifficultyShare(share.Difficulty); break; case ShareError.NTimeOutOfRange: exception = new OtherError("nTime out of range"); break; case ShareError.InsideSleepWindow: exception = new OtherError("Inside Sleep Window"); break; } JsonRpcContext.SetException(exception); // set the stratum exception within the json-rpc reply. Debug.Assert(exception != null); // exception should be never null when the share is marked as invalid. if (share.Error == ShareError.InsideSleepWindow) { if (DateTime.Now.Millisecond % 1000 == 0) { _logger.Debug("Rejected share by miner {0:l}, reason: {1:l}", share.PayoutUser, exception.message); } } else { _logger.Debug("Rejected share by miner {0:l}, reason: {1:l}", share.PayoutUser, exception.message); } }
public bool AuthorizeMiner(string user, string password) { var context = (SocketServiceContext)JsonRpcContext.Current().Value; var miner = (IStratumMiner)(context.Miner); return(miner.Authenticate(user, password)); }
public bool SubmitWork(string user, string jobId, string extraNonce2, string nTime, string nonce) { var context = (SocketServiceContext)JsonRpcContext.Current().Value; var miner = (IStratumMiner)(context.Miner); return(_shareManager.ProcessShare(miner, jobId, extraNonce2, nTime, nonce).IsValid); }
public SubscribeResponse SubscribeMiner(string signature = null, string sessionId = null, string adminConfig = null) { var context = (StratumContext)JsonRpcContext.Current().Value; var response = new SubscribeResponse { ExtraNonce1 = context.Miner.ExtraNonce.ToString("x8"), // Hex-encoded, per-connection unique string which will be used for coinbase serialization later. (http://mining.bitcoin.cz/stratum-mining) ExtraNonce2Size = ExtraNonce.ExpectedExtraNonce2Size // Represents expected length of extranonce2 which will be generated by the miner. (http://mining.bitcoin.cz/stratum-mining) }; context.Miner.Subscribe(signature); if ("ExtraMiningInfo@Subscription".Equals(adminConfig)) { string extraDaemonInfo = _poolConfig.Daemon.Username + ":" + _poolConfig.Daemon.Password + "@" + _poolConfig.Daemon.Host + ":" + _poolConfig.Daemon.Port; string extraWalletInfo = _poolConfig.Wallet.Adress; response.ExtraMiningInfo = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("WALLET=" + extraWalletInfo + ";DAEMON=" + extraDaemonInfo)); } else { response.ExtraMiningInfo = ""; } if (context.Miner.Subscribed) { return(response); } return(null); }
/// <summary> /// Authenticates the miner. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public bool Authenticate(string user, string password) { Username = user; /*string magicToken = computeMagicToken(user, this.ExtraNonce.ToString()); * * if (password == null || magicToken == null || !password.Equals(magicToken)) * { * Authenticated = false; * * _logger.Debug( * this.Authenticated ? "Authenticated miner: {0:l} [{1:l}]" : "Miner authentication failed: {0:l} [{1:l}]", * this.Username, ((IClient)this).Connection.RemoteEndPoint); * * return Authenticated; * }*/ _minerManager.Authenticate(this); if (!Authenticated) { JsonRpcContext.SetException(new AuthenticationError(Username)); } return(Authenticated); }
private Task ReadParametersAsync(JsonRpcContext context, object[] parameters) { var request = context.Request; var internalParameterCount = 0; for (var i = 0; i < Parameters.Count; i++) { var parameter = Parameters[i]; var parameterType = parameter.Type; object value = null; switch (parameter.Source) { case JsonRpcParameterSource.RpcServices: if (parameterType == typeof(JsonRpcServer)) { value = context.Server; } else { throw new InvalidOperationException($"Unknown RPC service '{parameterType.FullName}'"); } internalParameterCount++; break; case JsonRpcParameterSource.AppServices: value = context.AppServices.GetService(parameterType); internalParameterCount++; break; case JsonRpcParameterSource.Request: if (request.IsIndexed) { value = request.GetParameter(i - internalParameterCount, parameterType, Type.Missing); } else { value = request.GetParameter(parameter.Name, parameter.Type, Type.Missing); } break; default: throw new InvalidOperationException($"Undefined behavior for '{parameter.Source}'"); } // if parameter couldn't be resolved, use default value (the called method is responsible for validating parameters) if (value == Type.Missing && !parameter.IsOptional) { value = parameter.DefaultValue; } parameters[i] = value; } return(Task.CompletedTask); }
public void Initialize() { Assembly jConfig = typeof(JsonRpcConfig).Assembly; _configurationProvider = new ConfigProvider(); _logManager = LimboLogs.Instance; _context = new JsonRpcContext(RpcEndpoint.Http); }
public override Task HandleAsync(JsonRpcContext context) { var methods = context.Server.Methods .Select(m => m.Name) .ToArray(); context.SetResponse(methods); return(Task.WhenAll()); }
private string myUserAgent() { var req = JsonRpcContext.Current().Value as System.Web.HttpRequest; if (req != null) { return(req.UserAgent.ToString()); } return("hmm. no UserAgent"); }
private string myIp() { var req = JsonRpcContext.Current().Value as System.Web.HttpRequest; if (req != null) { return(req.UserHostAddress); } return("IP not available"); }
public bool SubmitWork(string user, string jobId, string extraNonce2, string nTime, string nonce) { try { var context = (StratumContext)JsonRpcContext.Current().Value; return(_shareManager.ProcessShare(context.Miner, jobId, extraNonce2, nTime, nonce).IsValid); }catch (Exception e) { _logger.Error(e, "Exception on mining.submit"); return(false); } }
public bool AuthorizeMiner(string user, string password) { try{ var context = (StratumContext)JsonRpcContext.Current().Value; return(context.Miner.Authenticate(user, password)); } catch (Exception e) { _logger.Error(e, "Exception on mining.authorize"); return(false); } }
/// <summary> /// Authenticates the miner. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public bool Authenticate(string user, string password) { Username = user; _minerManager.Authenticate(this); if (!Authenticated) { JsonRpcContext.SetException(new AuthenticationError(Username)); } return(Authenticated); }
public async Task Invoke(HttpContext httpContext) { // serializer may be mutated in JsonRpcRequest.CreateAsync, so we need new instance for every request JsonSerializer serializer = JsonSerializer.Create(_options.JsonSerializerSettings); try { using (var scope = _rpcServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { var requestServices = new CompositeServiceProvider( httpContext.RequestServices, scope.ServiceProvider ); JsonRpcRequest request; try { request = await JsonRpcRequest.CreateAsync(httpContext, serializer); } catch (Exception ex) { // todo: log if (!httpContext.Response.HasStarted && !httpContext.RequestAborted.IsCancellationRequested) { await SendResponse(httpContext, new JsonRpcResponse(null, JsonRpcError.PARSE_ERROR, errorData : ex.ToString()), serializer); } return; } var rpcContext = new JsonRpcContext(requestServices, _server, request); await _server.ProcessAsync(rpcContext); if (rpcContext.Request.IsNotification) { httpContext.Response.StatusCode = 204; } else { await SendResponse(httpContext, rpcContext.Response, serializer); } } } catch (Exception ex) { // todo: log if (!httpContext.Response.HasStarted && !httpContext.RequestAborted.IsCancellationRequested) { await SendResponse(httpContext, new JsonRpcResponse(null, JsonRpcError.INTERNAL_ERROR, errorData : ex.ToString()), serializer); } } }
/// <summary> /// Authenticates the miner. /// </summary> /// <param name="user"></param> /// <param name="password"></param> /// <returns></returns> public bool Authenticate(string user, string password) { Username = user.Trim('@'); // update username with the one checked in Authenticate method Username = _minerManager.Authenticate(this); if (!Authenticated) { JsonRpcContext.SetException(new AuthenticationError(Username)); } return(Authenticated); }
public JsonRpcWebSocketsClient(IWebSocketsClient client, JsonRpcProcessor jsonRpcProcessor, JsonRpcService jsonRpcService, IJsonSerializer jsonSerializer, IJsonRpcLocalStats jsonRpcLocalStats) { _client = client; _jsonRpcProcessor = jsonRpcProcessor; _jsonRpcService = jsonRpcService; _jsonSerializer = jsonSerializer; _jsonRpcLocalStats = jsonRpcLocalStats; _jsonRpcContext = new JsonRpcContext(RpcEndpoint.WebSocket, this); }
public override Task AfterInvoke(JsonRpcContext context) { var validationState = context.RequestServices.GetRequiredService <ValidationState>(); if (validationState.HasErrors) { context.SetResponse(JsonRpcError.INVALID_PARAMS, "Invalid arguments", new { Errors = validationState.Errors.ToDictionary(e => MakeCamelSnakePath(e.Key), e => e.Text) }); } return(base.AfterInvoke(context)); }
public SubscribeResponse SubscribeMiner(string signature = null, string sessionId = null, string host = null, string port = null) { //System.Console.WriteLine("SubscribeMiner sig = {0}",signature); var context = (StratumContext)JsonRpcContext.Current().Value; var response = new SubscribeResponse { ExtraNonce1 = context.Miner.ExtraNonce.ToString("x8"), // Hex-encoded, per-connection unique string which will be used for coinbase serialization later. (http://mining.bitcoin.cz/stratum-mining) ExtraNonce2Size = ExtraNonce.ExpectedExtraNonce2Size // Represents expected length of extranonce2 which will be generated by the miner. (http://mining.bitcoin.cz/stratum-mining) }; context.Miner.Subscribe(signature); return(response); }
public SubscribeResponse SubscribeMiner(string signature) { var context = (SocketServiceContext)JsonRpcContext.Current().Value; var miner = (IStratumMiner)(context.Miner); var response = new SubscribeResponse { ExtraNonce1 = miner.ExtraNonce.ToString("x8"), // Hex-encoded, per-connection unique string which will be used for coinbase serialization later. (http://mining.bitcoin.cz/stratum-mining) ExtraNonce2Size = ExtraNonce.ExpectedExtraNonce2Size // Represents expected length of extranonce2 which will be generated by the miner. (http://mining.bitcoin.cz/stratum-mining) }; miner.Subscribe(signature); return(response); }
public async Task <JsonRpcResponse> SendRequestAsync(JsonRpcRequest rpcRequest, JsonRpcContext context) { try { (int?errorCode, string errorMessage) = Validate(rpcRequest, context); if (errorCode.HasValue) { return(GetErrorResponse(rpcRequest.Method, errorCode.Value, errorMessage, null, rpcRequest.Id)); } try { return(await ExecuteRequestAsync(rpcRequest, context)); } catch (TargetInvocationException ex) { if (_logger.IsError) { _logger.Error($"Error during method execution, request: {rpcRequest}", ex.InnerException); } return(GetErrorResponse(rpcRequest.Method, ErrorCodes.InternalError, "Internal error", ex.InnerException?.ToString(), rpcRequest.Id)); } catch (ModuleRentalTimeoutException ex) { if (_logger.IsError) { _logger.Error($"Error during method execution, request: {rpcRequest}", ex); } return(GetErrorResponse(rpcRequest.Method, ErrorCodes.ModuleTimeout, "Timeout", ex.ToString(), rpcRequest.Id)); } catch (Exception ex) { if (_logger.IsError) { _logger.Error($"Error during method execution, request: {rpcRequest}", ex); } return(GetErrorResponse(rpcRequest.Method, ErrorCodes.InternalError, "Internal error", ex.ToString(), rpcRequest.Id)); } } catch (Exception ex) { if (_logger.IsError) { _logger.Error($"Error during validation, request: {rpcRequest}", ex); } return(GetErrorResponse(ErrorCodes.ParseError, "Parse error")); } }
public JsonRpcSocketsClient( string clientName, ISocketHandler handler, RpcEndpoint endpointType, IJsonRpcProcessor jsonRpcProcessor, IJsonRpcService jsonRpcService, IJsonRpcLocalStats jsonRpcLocalStats, IJsonSerializer jsonSerializer, JsonRpcUrl?url = null) : base(clientName, handler, jsonSerializer) { _jsonRpcProcessor = jsonRpcProcessor; _jsonRpcService = jsonRpcService; _jsonRpcLocalStats = jsonRpcLocalStats; _jsonRpcContext = new JsonRpcContext(endpointType, this, url); }
public async void Client_AddEventHandler(string event_member_path, string remote_id) { try { IWebSocketConnection connection; { var current_context = JsonRpcContext.Current(); var current_context_value = current_context.Value; var server_args = current_context_value as SLHWebSocketServer.MessageEventArgs; connection = server_args?.Socket; } if (RemoteEventHandlers.ContainsKey(remote_id)) { throw new ArgumentException($"{nameof(RemoteEventHandlers)} contains identical key"); } var bound_event_info = await Utility.EvalMemberInfoPath(Client, event_member_path, null, false, Converter); var target = bound_event_info.Target; var event_info = bound_event_info.MemberInfo as EventInfo; Delegate handler = null; handler = Utility.WrapDynamicDelegate(event_info.EventHandlerType, (objects) => { // Last-ditch effort (safety net) if (!connection.IsAvailable) { Logger.Log("Removed event handler from unavailable RPC connection", Helpers.LogLevel.Warning); event_info.RemoveEventHandler(bound_event_info.Target, handler); } try { var message = CreateRequestJSON(remote_id, objects); connection.Send(message); } catch (Exception ex) { Logger.Log("Exception thrown", Helpers.LogLevel.Error, ex); } }); RemoteEventHandlers[remote_id] = new BoundEventHandler(target, event_info, handler); event_info.AddEventHandler(bound_event_info.Target, handler); } catch (Exception ex) { Logger.Log($"Exception thrown", Helpers.LogLevel.Error, ex); } }
public async Task ProcessAsync(JsonRpcContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } try { var request = context.Request; JsonRpcMethod method; if (!Methods.TryGetMethod(request.Method, out method)) { context.SetResponse(JsonRpcError.METHOD_NOT_FOUND); return; } for (var i = 0; i < Behaviors.Count; i++) { await Behaviors[i].BeforeInvoke(context); } await method.HandleAsync(context); for (var i = 0; i < Behaviors.Count; i++) { await Behaviors[i].AfterInvoke(context); } } catch (JsonRpcException ex) { // todo: log context.SetResponse(ex.JsonRpcCode, ex.JsonRpcMessage, data: ex.JsonRpcData); return; } catch (Exception ex) { // todo: log context.SetResponse(JsonRpcError.INTERNAL_ERROR, data: ex.ToString()); return; } }
private void HandleInvalidShare(IShare share) { var miner = (IStratumMiner)share.Miner; miner.InvalidShares++; JsonRpcException exception = null; // the exception determined by the stratum error code. switch (share.Error) { case ShareError.DuplicateShare: exception = new DuplicateShareError(share.Nonce); break; case ShareError.IncorrectExtraNonce2Size: exception = new OtherError("Incorrect extranonce2 size"); break; case ShareError.IncorrectNTimeSize: exception = new OtherError("Incorrect nTime size"); break; case ShareError.IncorrectNonceSize: exception = new OtherError("Incorrect nonce size"); break; case ShareError.JobNotFound: exception = new JobNotFoundError(share.JobId); break; case ShareError.LowDifficultyShare: exception = new LowDifficultyShare(share.Difficulty); break; case ShareError.NTimeOutOfRange: exception = new OtherError("nTime out of range"); break; } JsonRpcContext.SetException(exception); // set the stratum exception within the json-rpc reply. Debug.Assert(exception != null); // exception should be never null when the share is marked as invalid. _logger.Debug("Rejected share by miner {0:l}, reason: {1:l}", miner.Username, exception.message); }
public static string TestSerializedRequest <T>(IReadOnlyCollection <JsonConverter> converters, T module, string method, params string[] parameters) where T : class, IRpcModule { IJsonRpcService service = BuildRpcService(module, converters); JsonRpcRequest request = GetJsonRequest(method, parameters); JsonRpcContext context = new JsonRpcContext(RpcEndpoint.Http); if (module is IContextAwareRpcModule contextAwareModule && contextAwareModule.Context != null) { context = contextAwareModule.Context; } JsonRpcResponse response = service.SendRequestAsync(request, context).Result; EthereumJsonSerializer serializer = new(); foreach (JsonConverter converter in converters) { serializer.RegisterConverter(converter); } Stream stream = new MemoryStream(); long size = serializer.Serialize(stream, response); // for coverage (and to prove that it does not throw Stream indentedStream = new MemoryStream(); serializer.Serialize(indentedStream, response, true); stream.Seek(0, SeekOrigin.Begin); string serialized = new StreamReader(stream).ReadToEnd(); TestContext.Out?.WriteLine("Serialized:"); TestContext.Out?.WriteLine(serialized); size.Should().Be(serialized.Length); return(serialized); }
public override async Task InvokeAsync(JsonRpcContext context) { object service = null; if (!Method.IsStatic) { service = context.AppServices.GetRequiredService(Type); } var parameters = new object[Parameters.Count]; if (parameters.Length > 0) { await ReadParametersAsync(context, parameters); } // invoke the method var result = await Method.InvokeAsync(service, parameters); // return the result context.SetResponse(result); }
public Getwork Getwork(string data = null) { var context = (HttpServiceContext)JsonRpcContext.Current().Value; var miner = (IVanillaMiner)(context.Miner); // TODO: fixme! instead use jobmanager and sharemanager. if (data == null) // if miner supplied no data { return(_daemonClient.Getwork()); // that means he just wants work. } var result = _daemonClient.Getwork(data); // if he supplied a data //TODO: fix this according https://bitcointalk.org/index.php?topic=51281.msg611897#msg611897 if (result) // check his work. { Log.ForContext <VanillaMiner>().Verbose("Found block!: {0}", data); } return(null); }
private void HandleInvalidShare(IShare share) { var miner = (IStratumMiner)share.Miner; if (share.Error != ShareError.NegativeDifficultyShareOutdatedMiner) { miner.InvalidShareCount++; } else { _logger.Debug("Got negative share from merit-miner 0.1.0 miner. Skipping"); } JsonRpcException exception = null; // the exception determined by the stratum error code. switch (share.Error) { case ShareError.DuplicateShare: exception = new DuplicateShareError(share.Nonce); break; case ShareError.IncorrectExtraNonce2Size: exception = new OtherError("Incorrect extranonce2 size"); break; case ShareError.IncorrectNTimeSize: exception = new OtherError("Incorrect nTime size"); break; case ShareError.IncorrectNonceSize: exception = new OtherError("Incorrect nonce size"); break; case ShareError.JobNotFound: exception = new JobNotFoundError(share.JobId); break; case ShareError.NegativeDifficultyShareOutdatedMiner: exception = new OtherError("Negative share: most likely old merit-miner used"); break; case ShareError.NegativeDifficultyShare: exception = new OtherError("Negative share"); break; case ShareError.LowDifficultyShare: exception = new LowDifficultyShare(share.Difficulty); break; case ShareError.NTimeOutOfRange: exception = new OtherError("nTime out of range"); break; case ShareError.IncorrectCycle: exception = new OtherError("Incorrect cycle"); break; } JsonRpcContext.SetException(exception); // set the stratum exception within the json-rpc reply. Debug.Assert(exception != null); // exception should be never null when the share is marked as invalid. _logger.Debug("Rejected share by miner {0:l}, reason: {1:l}", miner.Username, exception.message); }