private void HandleValidShare(IShare share) { var miner = (IStratumMiner)share.Miner; miner.ValidShares++; _storageLayer.AddShare(share); // commit the share. _logger.Debug("Share accepted at {0:0.00}/{1} by miner {2:l}", share.Difficulty, miner.Difficulty, miner.Username); // check if share is a block candidate if (!share.IsBlockCandidate) { return; } // submit block candidate to daemon. var accepted = SubmitBlock(share); // log about the acceptance status of the block. _logger.Information( accepted ? "Found block [{0}] with hash: {1:l}" : "Submit block [{0}] failed with hash: {1:l}", share.Height, share.BlockHash.ToHexString()); if (!accepted) // if block wasn't accepted { return; // just return as we don't need to notify about it and store it. } OnBlockFound(EventArgs.Empty); // notify the listeners about the new block. _storageLayer.AddBlock(share); // commit the block details to storage. _storageLayer.MoveShares(share); // move associated shares. }
public void AddBlock(IShare share) { try { if (!IsEnabled) return; using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString)) { connection.Execute( @"INSERT INTO Block(Height, BlockHash, TxHash, Amount, CreatedAt) VALUES (@height, @blockHash, @txHash, @amount, @createdAt)", new { height = share.Block.Height, blockHash = share.BlockHash.ToHexString(), txHash = share.Block.Tx.First(), amount = (decimal)share.GenerationTransaction.TotalAmount, createdAt = share.Block.Time.UnixTimestampToDateTime() }); } } catch (Exception e) { _logger.Error("An exception occured while adding block; {0:l}", e.Message); } }
public void AddBlock(IShare share) { try { if (!IsEnabled) { return; } using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString)) { connection.Execute( @"insert blocks(height, blockHash, txHash, amount, time) values (@height, @blockHash, @txHash, @amount, @time)", new { height = share.Block.Height, blockHash = share.BlockHash.ToHexString(), txHash = share.Block.Tx.First(), amount = share.GenerationTransaction.TotalAmount, time = share.Block.Time.UnixTimeToDateTime() }); } } catch (Exception e) { _logger.Error("An exception occured while adding block; {0:l}", e.Message); } }
public void AddBlock(IShare share) { try { if (!IsEnabled) { return; } using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString)) { connection.Execute( @"INSERT INTO Block(Height, BlockHash, TxHash, Amount, CreatedAt) VALUES (@height, @blockHash, @txHash, @amount, @createdAt)", new { height = share.Block.Height, blockHash = share.BlockHash.ToHexString(), txHash = share.Block.Tx.First(), amount = (decimal)share.GenerationTransaction.TotalAmount, createdAt = share.Block.Time.UnixTimestampToDateTime() }); } } catch (Exception e) { _logger.Error("An exception occured while adding block; {0:l}", e.Message); } }
public PdfBoardController( IPdfBoardRepository pdfBoardRepository, IShare share, IUserRepository userRepository, IShoppingCartRepository shoppingCartRepository, IProductRepository productRepository, IRepositoryV2 <Order> orderDataRepository, IRepositoryV2 <PdfBoard> pdfBoardDataRepository, IRepositoryV2 <User> userDataRepository, IRepositoryV2 <Product> productDataRepository, IRepositoryV2 <PackagingList> packagingListDataRepository, IRepositoryV2 <HeadInformation> headInformationDataRepository) { this.pdfBoardRepository = pdfBoardRepository; this.share = share; this.userRepository = userRepository; this.shoppingCartRepository = shoppingCartRepository; this.productRepository = productRepository; _orderDataRepository = orderDataRepository; _pdfBoardDataRepository = pdfBoardDataRepository; _userDataRepository = userDataRepository; _productDataRepository = productDataRepository; _packagingListDataRepository = packagingListDataRepository; _headInformationDataRepository = headInformationDataRepository; }
private void HandleValidShare(IShare share) { var miner = (IStratumMiner)share.Miner; miner.ValidShareCount++; _storageLayer.AddShare(share); // commit the share. _logger.Debug("Share accepted at {0:0.00}/{1} by miner {2:l}", share.Difficulty, miner.Difficulty, miner.Username); // check if share is a block candidate if (!share.IsBlockCandidate) { return; } // submit block candidate to daemon. var accepted = SubmitBlock(share); if (!accepted) // if block wasn't accepted { return; // just return as we don't need to notify about it and store it. } OnBlockFound(EventArgs.Empty); // notify the listeners about the new block. _storageLayer.AddBlock(share); // commit the block details to storage. _storageLayer.MoveCurrentShares(share.Height); // move associated shares to new key. }
public FilelistMyList(IShare share) : base(share) { systemPath = ""; if (share != null) fileName = share.Name; }
public void AddBlock(IShare share) { try { if (!IsEnabled || !IsConnected) { return; } //_client.StartPipe(); // batch the commands. if (share.IsBlockAccepted) { // rename round. var currentKey = string.Format("{0}:shares:round:current", _coin); var roundKey = string.Format("{0}:shares:round:{1}", _coin, share.Height); _client.Rename(currentKey, roundKey); // add block to pending. var pendingKey = string.Format("{0}:blocks:pending", _coin); var entry = string.Format("{0}:{1}:{2}", share.BlockHash.ToHexString(), share.Block.Tx.First(), share.GenerationTransaction.TotalAmount); // entry format: blockHash:txHash:Amount _client.ZAdd(pendingKey, Tuple.Create(share.Block.Height, entry)); } // increment block stats. var statsKey = string.Format("{0}:stats", _coin); _client.HIncrBy(statsKey, share.IsBlockAccepted ? "validBlocks" : "invalidBlocks", 1); //_client.EndPipe(); // execute the batch commands. } catch (Exception e) { _logger.Error("An exception occured while adding block: {0:l}", e.Message); } }
/// <summary> /// Adds/Update common filelists to this share and saves them in directory specified /// Filelist included are: /// BZList, XmlBzList (UTF-8 and ASCII) /// </summary> /// <param name="share">Share you want to update/add filelist to</param> /// <param name="directory">Directory where you want to save filelists in</param> public static void AddCommonFilelistsToShare(IShare share, string directory) { // Xml Utf-8 (Current DC++) FlowLib.Utils.FileLists.FilelistXmlBz2 xml = new FlowLib.Utils.FileLists.FilelistXmlBz2(share); xml.SystemPath = directory; xml.Encoding = System.Text.Encoding.UTF8; xml.CreateFilelist(); share.RemoveFile(xml.ContentInfo); share.AddFile(xml.ContentInfo); // Xml Ascii (Early DC++) xml.Encoding = System.Text.Encoding.ASCII; xml.CreateFilelist(); share.RemoveFile(xml.ContentInfo); share.AddFile(xml.ContentInfo); // Xml Utf-8 (Adc Standard list) xml.Bz2 = false; xml.SystemPath = directory; xml.Encoding = System.Text.Encoding.UTF8; xml.CreateFilelist(); share.RemoveFile(xml.ContentInfo); share.AddFile(xml.ContentInfo); // BzList FlowLib.Utils.FileLists.FilelistMyList dclst = new FlowLib.Utils.FileLists.FilelistMyList(share); dclst.SystemPath = directory; dclst.CreateFilelist(); share.RemoveFile(dclst.ContentInfo); share.AddFile(dclst.ContentInfo); }
public void AddShare(IShare share) { try { if (!IsEnabled || !_redisProvider.IsConnected) return; //_client.StartPipe(); // batch the commands. // add the share to round var currentKey = string.Format("{0}:shares:round:current", _coin); _redisProvider.Client.HIncrByFloat(currentKey, share.Miner.Username, share.Difficulty); // increment shares stats. var statsKey = string.Format("{0}:stats", _coin); _redisProvider.Client.HIncrBy(statsKey, share.IsValid ? "validShares" : "invalidShares", 1); // add to hashrate if (share.IsValid) { var hashrateKey = string.Format("{0}:hashrate", _coin); var entry = string.Format("{0}:{1}", share.Difficulty, share.Miner.Username); _redisProvider.Client.ZAdd(hashrateKey, Tuple.Create(TimeHelpers.NowInUnixTimestamp(), entry)); } //_client.EndPipe(); // execute the batch commands. } catch (Exception e) { _logger.Error("An exception occured while comitting share: {0:l}", e.Message); } }
public void Ensures_GivenValidLine_ResultsInValidIShare() { var lineParser = new CsvLineParser(); IShare share = lineParser.ParseLine("04.03.2013;7.654,67;7.708,88;7.637,32;7.691,68;2.148.781.568"); Assert.That(share.Datum, Is.EqualTo(new DateTime(2013, 3, 4))); }
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 void AddShare(IShare share) { try { if (!IsEnabled || !_redisProvider.IsConnected) { return; } //_client.StartPipe(); // batch the commands. // add the share to round var currentKey = string.Format("{0}:shares:round:current", _coin); _redisProvider.Client.HIncrByFloat(currentKey, share.Miner.Username, share.Difficulty); // increment shares stats. var statsKey = string.Format("{0}:stats", _coin); _redisProvider.Client.HIncrBy(statsKey, share.IsValid ? "validShares" : "invalidShares", 1); // add to hashrate if (share.IsValid) { var hashrateKey = string.Format("{0}:hashrate", _coin); var entry = string.Format("{0}:{1}", share.Difficulty, share.Miner.Username); _redisProvider.Client.ZAdd(hashrateKey, Tuple.Create(TimeHelpers.NowInUnixTime(), entry)); } //_client.EndPipe(); // execute the batch commands. } catch (Exception e) { _logger.Error("An exception occured while comitting share: {0:l}", e.Message); } }
public WalletInfoViewModel(ChaincaseWalletManager walletManager, Config config, UiConfig uiConfig, IShare share, IDataDirProvider dataDirProvider) { _walletManager = walletManager; _config = config; _uiConfig = uiConfig; _share = share; _dataDirProvider = dataDirProvider; }
public FilelistMyList(IShare share, string systemPath) : base(share) { this.systemPath = systemPath; if (share != null) { fileName = share.Name; } }
public Storage(ApiHelper apiHelper , IShare share) { _apiHelper = apiHelper; _log = apiHelper.Log; _highTailApi = apiHelper.HighTailApi; _maxTryCount = apiHelper.MaxTryCount; _share = share; }
public FilelistMyList(IShare share) : base(share) { systemPath = ""; if (share != null) { fileName = share.Name; } }
public ShareController(IShare ishare, IBady ibady, ILog ilog, ISetting isetting, IUser iuser, IMoney imoney, ITask itask) { this.ishare = ishare; this.ibady = ibady; this.imoney = imoney; this.ilog = ilog; this.isetting = isetting; this.iuser = iuser; this.itask = itask; }
public Files(ApiHelper apiHelper , IShare share) { _apiHelper = apiHelper; _log = apiHelper.Log; _highTailApi = apiHelper.HighTailApi; _maxTryCount = apiHelper.MaxTryCount; _share = share; _fileExpirationDays = Convert.ToInt32(ConfigurationManager.AppSettings["FileExpirationDays"]); }
public static ShareModel Load(IShare share) { ShareModel model = new ShareModel(); model.AssetId = share.AssetId; model.Message = share.Message; model.ToUserId = share.ToUserId; return(model); }
/// <summary> /// Adding share to manager /// </summary> /// <param name="s">Share we want to add</param> /// <returns>Returns true if share name is not already existing (and is added)</returns> public bool AddShare(IShare s) { if (!s.Name.Contains("|") && !shares.ContainsKey(s.Name)) { shares.Add(s.Name, s); Save(); return(true); } return(false); }
/// <summary> /// Adding share to manager /// </summary> /// <param name="s">Share we want to add</param> /// <returns>Returns true if share name is not already existing (and is added)</returns> public bool AddShare(IShare s) { if (!s.Name.Contains("|") && !shares.ContainsKey(s.Name)) { shares.Add(s.Name, s); Save(); return true; } return false; }
public bool RegisterShare(IShare share) { var submissionId = (UInt64)(share.ExtraNonce1 + share.ExtraNonce2 + share.NTime + share.Nonce); // simply hash the share by summing them.. if (_shares.Contains(submissionId)) // if our list already contain the share { return(false); // it basically means we hit a duplicate share. } _shares.Add(submissionId); // if the code flows here, that basically means we just recieved a new share. return(true); }
public static ContentItem?SearchByTth(this IShare share, string tth) { var results = share.Search(new SearchQuery { Query = tth, SearchType = SearchType.TTH }); if (results.Count > 0) { return(results[0]); } return(null); }
public UserController( IUserRepository userRepository, IOptions <AppSettings> appSettings, IShare share, IRepositoryV2 <User> userDataRepository) { _userRepository = userRepository; this.appSettings = appSettings; _share = share; _userDataRepository = userDataRepository; _appSettings = appSettings.Value; }
private bool SubmitBlock(IShare share) { // TODO: we should try different submission techniques and probably more then once: https://github.com/ahmedbodi/stratum-mining/blob/master/lib/bitcoin_rpc.py#L65-123 try { _daemonClient.SubmitBlock(share.BlockHex.ToHexString()); var block = _blockProcessor.GetBlock(share.BlockHash.ToHexString()); // query the block. if (block == null) // make sure the block exists { return(false); } if (block.Confirmations == -1) // make sure the block is accepted. { _logger.Debug("Submitted block {0:l} is orphaned", block.Hash); return(false); } var expectedTxHash = share.CoinbaseHash.Bytes.ReverseBuffer().ToHexString(); // calculate our expected generation transactions's hash var genTxHash = block.Tx.First(); // read the hash of very first (generation transaction) of the block if (expectedTxHash != genTxHash) // make sure our calculated generated transaction and one reported by coin daemon matches. { _logger.Debug("Submitted block {0:l} doesn't seem to belong us as reported generation transaction hash [{1:l}] doesn't match our expected one [{2:l}]", block.Hash, genTxHash, expectedTxHash); return(false); } var genTx = _blockProcessor.GetGenerationTransaction(block); // get the generation transaction. var poolOutput = _blockProcessor.GetPoolOutput(genTx); // get the output that targets pool's central address. // make sure the blocks generation transaction contains our central pool wallet address if (poolOutput == null) { _logger.Debug("Submitted block doesn't seem to belong us as generation transaction doesn't contain an output for pool's central wallet address: {0:}", _poolConfig.Wallet.Adress); return(false); } // if the code flows here, then it means the block was succesfully submitted and belongs to us. share.SetFoundBlock(block, genTx); // assign the block to share. return(true); } catch (Exception e) { _logger.Error("Submit block failed - height: {0}, hash: {1:l} - {2:l}", share.Height, share.BlockHash.ToHexString(), e.Message); return(false); } }
protected ArticleViewModelBase(INavigationService navigation, IShare share, IDataStore dataStore, IAnalytics analytics, IMessagingService messagingService) : base(navigation, analytics, messagingService) { this.share = share; this.dataStore = dataStore; ShareCommand = new AsyncCommand <Article>(ExecuteShareCommand); ToggleBookmarkCommand = new Command <Article>(ExecuteToggleBookmarkArticle); }
public ArticlesListViewModel(INavigationService navigation, IDataStore dataStore, IBrowser browser, IAnalytics analytics, IPreferences preferences, IShare share) : base(navigation, analytics) { Title = "Articles"; LoadArticlesCommand = new AsyncCommand <bool>(ExecuteLoadArticlesCommand, CanRefresh); OpenArticleCommand = new AsyncCommand <Article>(OpenArticle); ToggleBookmarkCommand = new Command <Article>(ExecuteToggleBookmarkArticle); ShareCommand = new AsyncCommand <Article>(ExecuteShareCommand); NavigateBackCommand = new AsyncCommand(ExecuteNavigateBackCommand); this.dataStore = dataStore; this.browser = browser; this.preferences = preferences; this.share = share; }
public ArticlesListViewModel(INavigationService navigation, IAnalytics analytics, IDataStore dataStore, IBrowser browser, IPreferences preferences, IShare share, IMessagingService messagingService) : base(navigation, analytics, dataStore, browser, preferences, share, messagingService) { Title = "Articles"; LoadArticlesCommand = new AsyncCommand(ExecuteLoadArticlesCommand); ToggleBookmarkCommand = new Command <Article>(ExecuteToggleBookmarkArticle); NavigateBackCommand = new AsyncCommand(ExecuteNavigateBackCommand); }
public bool RegisterShare(IShare share) { var submissionId = (UInt64)(share.ExtraNonce1 + share.ExtraNonce2 + share.NTime + share.Nonce); // simply hash the share by summing them.. if (_shares.Contains(submissionId)) { // if our list already contain the share //return false; // it basically means we hit a duplicate share. _logger.Debug("Share is duplicated, but we accept it anyway: {0}", share.Nonce); } _shares.Add(submissionId); // if the code flows here, that basically means we just recieved a new share. _logger.Debug("Share list length: {0}", _shares.Count); return(true); }
static MainPageViewModel GetSut( IClock clock = null, IShare share = null, IAuthorizer authorizer = null, INavigationService navService = null, IActionPresenter actionPresenter = null, ISettingsStore settings = null, IFileManager fileManager = null, IHealthStore healthStore = null) { clock ??= SystemClock.Instance; var logger = new LoggerConfiguration().CreateLogger(); var mockAuthorizer = new Mock <IAuthorizer>(); var mockSettings = new Mock <ISettingsStore>(); var mockAnalytics = new Mock <IAnalytics>(); var mockActionPresenter = new Mock <IActionPresenter>(); var mockNavService = new Mock <INavigationService>(); var mockFileManager = new Mock <IFileManager>(); mockFileManager .Setup(x => x.GetNewFileName()) .Returns(new FileInfo("arbitrary-filename-for-testing.xlsx")); var authCommand = new AuthorizeHealthCommand( authorizer ?? mockAuthorizer.Object, clock, actionPresenter ?? mockActionPresenter.Object, mockAnalytics.Object, logger, settings ?? mockSettings.Object); var exporter = new ExportSpreadsheetCommand( fileManager ?? mockFileManager.Object, actionPresenter ?? mockActionPresenter.Object, settings ?? mockSettings.Object, clock, mockAnalytics.Object, healthStore ?? new Mock <IHealthStore>().Object, share ?? new Mock <IShare>().Object, new Configuration(), logger); return(new MainPageViewModel( authCommand, exporter, settings ?? mockSettings.Object, navService ?? mockNavService.Object, mockAnalytics.Object)); }
public ArticleListViewModelBase(INavigationService navigation, IAnalytics analytics, IDataStore dataStore, IBrowser browser, IPreferences preferences, IShare share, IMessagingService messagingService) : base(navigation, share, dataStore, analytics, messagingService) { OpenArticleCommand = new AsyncCommand <Article>(OpenArticle); SearchCategoryCommand = new Command <Article>(ExecuteCategorySearch); this.browser = browser; this.preferences = preferences; messagingService.Subscribe <Article>(this, "BOOKMARKED", BookMarkChanged); }
public SuperAssertController(ITask itask, IBady ibady, ILike ilike, IShare ishare, IGroup igroup, IUserStore iuserstore, IFirstPageArg ifirstpagearg, ILog ilog, ISetting isetting, IUserSetting iusersetting, IUser iuser, IMoney imoney) { this.itask = itask; this.ibady = ibady; this.iuser = iuser; this.ilike = ilike; this.ishare = ishare; this.igroup = igroup; this.iuserstore = iuserstore; this.ifirstpagearg = ifirstpagearg; this.ilog = ilog; this.isetting = isetting; this.iusersetting = iusersetting; this.imoney = imoney; }
public OrderRepository( IUserRepository userRepository, IShoppingCartRepository shoppingCartRepository, IShare share, IRepositoryV2 <Order> orderDataRepository, IRepositoryV2 <ShoppingCart> shoppingCartDataRepository, IRepositoryV2 <ShoppingItem> shoppingItemDataRepository ) { this.userRepository = userRepository; this.shoppingCartRepository = shoppingCartRepository; this.share = share; _orderDataRepository = orderDataRepository; _shoppingCartDataRepository = shoppingCartDataRepository; _shoppingItemDataRepository = shoppingItemDataRepository; }
public void AddShare(IShare share) { try { if (!IsEnabled) return; var ourResult = share.IsValid ? 'Y' : 'N'; var upstreamResult = share.IsBlockCandidate ? 'Y' : 'N'; object errorReason; if (share.Error != ShareError.None) errorReason = share.Error; else errorReason = null; using (var connection = new MySqlConnection(_mySqlProvider.ConnectionString)) { connection.Execute( @"INSERT INTO shares(rem_host, username, our_result, upstream_result, reason, solution, difficulty,time) VALUES (@rem_host, @username, @our_result, @upstream_result, @reason, @solution, @difficulty, @time)", new { rem_host = ((IClient) share.Miner).Connection.RemoteEndPoint.Address.ToString(), username = share.Miner.Username, our_result = ourResult, upstream_result = upstreamResult, reason = errorReason, solution = share.BlockHash.ToHexString(), difficulty = share.Difficulty, // should we consider mpos difficulty multiplier here? time = DateTime.Now }); } } catch (Exception e) { _logger.Error("An exception occured while comitting share; {0:l}", e.Message); } }
private void HandleValidShare(IShare share) { var miner = (IStratumMiner) share.Miner; miner.ValidShareCount++; _storageLayer.AddShare(share); // commit the share. _logger.Debug("Share accepted at {0:0.00}/{1} by miner {2:l}", share.Difficulty, miner.Difficulty, miner.Username); // check if share is a block candidate if (!share.IsBlockCandidate) return; // submit block candidate to daemon. var accepted = SubmitBlock(share); if (!accepted) // if block wasn't accepted return; // just return as we don't need to notify about it and store it. OnBlockFound(EventArgs.Empty); // notify the listeners about the new block. _storageLayer.AddBlock(share); // commit the block details to storage. _storageLayer.MoveCurrentShares(share.Height); // move associated shares to new key. }
public FilelistMyList(IShare share, string systemPath) : base(share) { this.systemPath = systemPath; if (share != null) fileName = share.Name; }
public override void Dispose() { if (!disposed) { if (baseUpdater != null) baseUpdater.UpdateBase -= OnUpdateBase; base.Dispose(); Hub.RegModeUpdated -= Hub_RegModeUpdated; UnknownProtocolId -= OnUnknownProtocolId; ProtocolChange -= Hub_ProtocolChange; if (updateInfoTimer != null) { updateInfoTimer.Dispose(); updateInfoTimer = null; } if (keepAliveTimer != null) { keepAliveTimer.Dispose(); keepAliveTimer = null; } if (worker != null) { worker.Abort(); worker = null; } lock (userlist) { if (userlist != null) { userlist.Clear(); userlist = null; } } this.me = null; if (share != null) { share.LastModifiedChanged -= share_LastModifiedChanged; this.share = null; } this.fav = null; } }
public void AddBlock(IShare share) { if (!IsEnabled || !IsConnected) return; var coin = _poolConfig.Coin.Name.ToLower(); // the coin we are working on. var batch = _database.CreateBatch(); // batch the commands. if (share.IsBlockAccepted) { // rename round. var currentKey = string.Format("{0}:shares:round:current", coin); var roundKey = string.Format("{0}:shares:round:{1}", coin, share.Height); batch.KeyRenameAsync(currentKey, roundKey, When.Always, CommandFlags.HighPriority); // add block to pending. var pendingKey = string.Format("{0}:blocks:pending", coin); var entry = string.Format("{0}:{1}", share.BlockHash.ToHexString(), share.Block.Tx.First()); batch.SortedSetAddAsync(pendingKey, entry, share.Block.Height, CommandFlags.FireAndForget); } // increment block stats. var statsKey = string.Format("{0}:stats", coin); batch.HashIncrementAsync(statsKey, share.IsBlockAccepted ? "validBlocks" : "invalidBlocks", 1, CommandFlags.FireAndForget); batch.Execute(); // execute the batch commands. }
private void HandleInvalidShare(IShare share) { var miner = (IStratumMiner)share.Miner; 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; } 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); }
protected BaseFilelist(IShare share) { this.share = share; }
private bool CheckIfBlockAccepted(IShare share) { try { var block = _daemonClient.GetBlock(share.BlockHash.ToHexString()); // query the block. share.SetFoundBlock(block); // assign the block to share. return true; } catch (Exception e) { _logger.Error(e, "Get block failed - height: {0}, hash: {1:l}", share.Height, share.BlockHash); return false; } }
public void AddBlock(IShare share) { return; }
public void AddBlock(IShare share) { // this function is not supported as this functionality is handled by mpos itself. }
public void CommitBlock(IShare share) { var coin = share.Miner.Pool.Config.Coin.Name.ToLower(); // rename round:current to round:height. var currentKey = string.Format("{0}:shares:round:current", coin); var newKey = string.Format("{0}:shares:round:{1}", coin, share.Height); _database.KeyRenameAsync(currentKey, newKey, When.Always, CommandFlags.HighPriority); }
public FilelistXmlBz2(IShare share) : base(share) { systemPath = ""; }
private bool SubmitBlock(IShare share) { // TODO: we should try different submission techniques and probably more then once: https://github.com/ahmedbodi/stratum-mining/blob/master/lib/bitcoin_rpc.py#L65-123 try { if (_poolConfig.Coin.Options.SubmitBlockSupported) // see if submitblock() is available. _daemonClient.SubmitBlock(share.BlockHex.ToHexString()); // submit the block. else _daemonClient.GetBlockTemplate(share.BlockHex.ToHexString()); // use getblocktemplate() if submitblock() is not supported. var block = _daemonClient.GetBlock(share.BlockHash.ToHexString()); // query the block. if (block == null) // make sure the block exists return false; if (block.Confirmations == -1) // make sure the block is accepted. { _logger.Debug("Submitted block [{0}] is orphaned; [{1:l}]", block.Height, block.Hash); return false; } var expectedTxHash = share.CoinbaseHash.Bytes.ReverseBuffer().ToHexString(); // calculate our expected generation transactions's hash var genTxHash = block.Tx.First(); // read the hash of very first (generation transaction) of the block if (expectedTxHash != genTxHash) // make sure our calculated generated transaction and one reported by coin daemon matches. { _logger.Debug("Submitted block [{0}] doesn't seem to belong us as reported generation transaction hash [{1:l}] doesn't match our expected one [{2:l}]", block.Height, genTxHash, expectedTxHash); return false; } var genTx = _daemonClient.GetTransaction(block.Tx.First()); // get the generation transaction. // make sure we were able to read the generation transaction if (genTx == null) { _logger.Debug("Submitted block [{0}] doesn't seem to belong us as we can't read the generation transaction on our records [{1:l}]", block.Height, block.Tx.First()); return false; } var poolOutput = genTx.GetPoolOutput(_poolConfig.Wallet.Adress, _poolAccount); // get the output that targets pool's central address. // make sure the blocks generation transaction contains our central pool wallet address if (poolOutput == null) { _logger.Debug("Submitted block [{0}] doesn't seem to belong us as generation transaction doesn't contain an output for pool's central wallet address: {0:}", block.Height, _poolConfig.Wallet.Adress); return false; } // if the code flows here, then it means the block was succesfully submitted and belongs to us. share.SetFoundBlock(block, genTx); // assign the block to share. _logger.Information("Found block [{0}] with hash [{1:l}]", share.Height, share.BlockHash.ToHexString()); return true; } catch (RpcException e) { // unlike BlockProcessor's detailed exception handling and decision making based on the error, // here in share-manager we only one-shot submissions. If we get an error, basically we just don't care about the rest // and flag the submission as failed. _logger.Debug("We thought a block was found but it was rejected by the coin daemon; [{0:l}] - reason; {1:l}", share.BlockHash.ToHexString(), e.Message); return false; } }
public bool RegisterShare(IShare share) { var submissionId = (UInt64) (share.ExtraNonce1 + share.ExtraNonce2 + share.NTime + share.Nonce); // simply hash the share by summing them.. if(_shares.Contains(submissionId)) // if our list already contain the share return false; // it basically means we hit a duplicate share. _shares.Add(submissionId); // if the code flows here, that basically means we just recieved a new share. return true; }
public FilelistXmlBz2(IShare share, Encoding xmlEncoding, string systemPath) : this(share, xmlEncoding) { this.systemPath = systemPath; }
private void HandleInvalidShare(IShare share) { var miner = (IStratumMiner)share.Miner; miner.InvalidShares++; switch (share.Error) { case ShareError.DuplicateShare: JsonRpcContext.SetException(new DuplicateShareError(share.Nonce)); break; case ShareError.IncorrectExtraNonce2Size: JsonRpcContext.SetException(new OtherError("Incorrect extranonce2 size")); break; case ShareError.IncorrectNTimeSize: JsonRpcContext.SetException(new OtherError("Incorrect nTime size")); break; case ShareError.IncorrectNonceSize: JsonRpcContext.SetException(new OtherError("Incorrect nonce size")); break; case ShareError.JobNotFound: JsonRpcContext.SetException(new JobNotFoundError(share.JobId)); break; case ShareError.LowDifficultyShare: JsonRpcContext.SetException(new LowDifficultyShare(share.Difficulty)); break; case ShareError.NTimeOutOfRange: JsonRpcContext.SetException(new OtherError("nTime out of range")); break; } _logger.Debug("Share rejected at {0:0.00}/{1} by miner {2:l}", share.Difficulty, miner.Difficulty, miner.Username); }
public void AddShare(IShare share) { return; }
private void HandleValidShare(IShare share) { var miner = (IStratumMiner) share.Miner; miner.ValidShares++; _storage.AddShare(share); // commit the share. if (!share.IsBlockCandidate) { _logger.Debug("Share accepted at {0:0.00}/{1} by miner {2:l}", share.Difficulty, miner.Difficulty, miner.Username); return; } // if share contains a block candicate _logger.Debug("Share with block candidate [{0}] accepted at {1:0.00}/{2} by miner {3:l}", share.Height, share.Difficulty, miner.Difficulty, miner.Username); var accepted = SubmitBlock(share); // submit block to daemon. if (!accepted) return; OnBlockFound(EventArgs.Empty); // notify the listeners about the new block. _storage.AddBlock(share); // commit the block. }
public FilelistXmlBz2(IShare share, Encoding xmlEncoding) : this(share) { this.encoding = xmlEncoding; }
private bool SubmitBlock(IShare share) { try { _daemonClient.SubmitBlock(share.BlockHex.ToHexString()); var isAccepted = CheckIfBlockAccepted(share); _logger.Information( isAccepted ? "Found block [{0}] with hash: {1:l}" : "Submitted block [{0}] but got denied: {1:l}", share.Height, share.BlockHash.ToHexString()); return isAccepted; } catch (Exception e) { _logger.Error(e, "Submit block failed - height: {0}, hash: {1:l}", share.Height, share.BlockHash); return false; } }
public FilelistXmlBz2(IShare share, string systemPath) : base(share) { this.systemPath = systemPath; }
public void AddShare(IShare share) { if (!IsEnabled || !IsConnected) return; var coin = _poolConfig.Coin.Name.ToLower(); // the coin we are working on. var batch = _database.CreateBatch(); // batch the commands. // add the share to round var currentKey = string.Format("{0}:shares:round:current", coin); batch.HashIncrementAsync(currentKey, share.Miner.Username, share.Difficulty, CommandFlags.FireAndForget); // increment shares stats. var statsKey = string.Format("{0}:stats", coin); batch.HashIncrementAsync(statsKey, share.IsValid ? "validShares" : "invalidShares", 1, CommandFlags.FireAndForget); // add to hashrate if (share.IsValid) { var hashrateKey = string.Format("{0}:hashrate", coin); var entry = string.Format("{0}:{1}", share.Difficulty, share.Miner.Username); batch.SortedSetAddAsync(hashrateKey, entry, TimeHelpers.NowInUnixTime(), CommandFlags.FireAndForget); } batch.Execute(); // execute the batch commands. }
public void CommitShare(IShare share) { if (!IsEnabled || !IsConnected) return; var coin = share.Miner.Pool.Config.Coin.Name.ToLower(); // add the share to round. var roundKey = string.Format("{0}:shares:round:current", coin); _database.HashIncrement(roundKey, share.Miner.Username, share.Difficulty ,CommandFlags.FireAndForget); // increment the valid shares. var statsKey = string.Format("{0}:stats", coin); _database.HashIncrement(statsKey, share.IsValid ? "validShares" : "invalidShares", 1 , CommandFlags.FireAndForget); // add to hashrate. if (share.IsValid) { var hashrateKey = string.Format("{0}:hashrate", coin); var entry = string.Format("{0}:{1}", share.Difficulty, share.Miner.Username); _database.SortedSetAdd(hashrateKey, entry, TimeHelpers.NowInUnixTime(), CommandFlags.FireAndForget); } }
/// <summary> /// Returns share with the specified id /// </summary> /// <param name="id">id we want to get share of</param> /// <param name="s">Returning share if matching id</param> /// <returns>Returns true if id match a share</returns> public bool GetShare(string id, out IShare s) { return shares.TryGetValue(id, out s); }