public Miners GetMinerByAddress(string address) { MinersDac dac = new MinersDac(); Miners miner = dac.GetMinerByAddress(address); return(miner); }
private bool TryToGetVictories(out Miners victories) { var candidates = State.CandidatesField.Value; if (candidates == null) { victories = null; return(false); } var ticketsMap = new Dictionary <string, long>(); foreach (var candidatePublicKey in candidates.PublicKeys) { var tickets = State.TicketsMap[candidatePublicKey.ToStringValue()]; if (tickets != null) { ticketsMap.Add(candidatePublicKey, tickets.ObtainedTickets); } } if (ticketsMap.Keys.Count < GetProducerNumber()) { victories = null; return(false); } victories = ticketsMap.OrderByDescending(tm => tm.Value).Take(GetProducerNumber()) .Select(tm => tm.Key) .ToList().ToMiners(); return(true); }
public bool MinerLogin(string address, string sn) { /* 设计思路 * 1、根据address从数据库获取account,如果数据库没有记录直接抛错误 * 2、根据account和sn调接口,根据接口返回值提供返回值 * */ MinersDac dac = new MinersDac(); Miners miner = dac.GetMinerByAddress(address); if (miner == null) { throw new ApiCustomException(MiningPoolErrorCode.Miners.ADDRESS_NOT_EXIST, "address not exist"); } string url = MiningPoolSetting.POS_URL + "Api/Account/CheckAccount"; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("MerchantId", miner.Account); dic.Add("SN", sn); string response = ApiHelper.PostApi(url, dic); Dictionary <string, string> returnDic = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(response); return(returnDic["Data"] == "true" ? true : false); }
public Miners SelectById(long id) { const string SQL_STATEMENT = "SELECT Id, Address, Account, Type, SN, Status, Timstamp, LastLoginTime, UnpaidReward, PaidReward " + "FROM Miners WHERE Id=@Id;"; Miners miner = null; using (MySqlConnection conn = new MySqlConnection(CacheConnectionString)) using (MySqlCommand cmd = new MySqlCommand(SQL_STATEMENT, conn)) { cmd.Parameters.AddWithValue("@Id", id); cmd.Connection.Open(); cmd.CommandTimeout = 1200; using (MySqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { miner = new Miners(); miner.Id = GetDataValue <long>(dr, "Id"); miner.Address = GetDataValue <string>(dr, "Address"); miner.Account = GetDataValue <string>(dr, "Account"); miner.Type = GetDataValue <int>(dr, "Type"); miner.SN = GetDataValue <string>(dr, "SN"); miner.Status = GetDataValue <int>(dr, "Status"); miner.Timstamp = GetDataValue <long>(dr, "Timstamp"); miner.LastLoginTime = GetDataValue <long>(dr, "LastLoginTime"); miner.UnpaidReward = GetDataValue <long>(dr, "UnpaidReward"); miner.PaidReward = GetDataValue <long>(dr, "PaidReward"); } } } return(miner); }
public void ImportMiner(string minerFile) { var fileName = Path.GetFileName(minerFile)?.ToLower(); if (fileName == null) { return; } if (!Consts.Miners.Contains(fileName)) { throw new NotSupportedException("The specified file is not a supported miner"); } var miner = Miners.FirstOrDefault(m => m.Path.Equals(minerFile, StringComparison.InvariantCultureIgnoreCase)); if (miner != null) { return; } miner = new Miner { Path = minerFile }; Miners.Add(miner); }
/// <summary> /// Miner indítása /// </summary> /// <returns></returns> public bool StartMiner() { bool success = false; if (_pools != null && _pools.Count > 0) { if (MinerType == MinerType.GPU) { switch (Algorithm) { case (int)SupportedAlgos.CryptoNight: default: Stratum.Stratum mainPool = createStratumFromPoolSettings(_pools, (int)SupportedAlgos.CryptoNight); if (mainPool != null && mainPool is CryptoNightStratum) { foreach (var device in Devices.Where(x => x.IsEnabled)) { for (int i = 0; i < device.Threads; ++i) { OpenCLCryptoNightMiner miner = null; try { miner = new OpenCLCryptoNightMiner(device); miner.Start(mainPool as CryptoNightStratum, device.Intensity, device.WorkSize, true); Miners.Add(miner); } catch (Exception ex) { Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = $"Faild to start GPU miner on Device# {device.ADLAdapterIndex} Thread# {i+1}", Exception = ex, IsError = true }); } } } success = true; } break; } } else if (MinerType == MinerType.CPU) { exeMinerManager = new ExeManager(ApplicationPath, ExeFileName); string minerParameter = generateMinerCall(); MinerThread = new Thread(() => exeMinerManager.ExecuteResource(minerParameter)); MinerThread.Start(); success = true; } } else { Messenger.Default.Send <MinerOutputMessage>(new MinerOutputMessage() { OutputText = "WARNING: No main pool selected." }); } return(success); }
private async Task InitializeBlockProducer(Miners miners) { foreach (var bp in miners.Nodes) { ConsoleWriteLine(nameof(Initialize), $"Set Miner: {bp}"); } await _blockProducerField.SetAsync(miners); }
public AElfDPoSHelper(Hash chainId, Miners miners, Address contractAddressHash, IStateStore stateStore) { _chainId = chainId; _miners = miners; _contractAddressHash = contractAddressHash; _stateStore = stateStore; _logger = LogManager.GetLogger(nameof(AElfDPoSHelper)); }
private bool ValidateVictories(Miners miners) { if (TryToGetVictories(out var victories)) { return(victories.GetMinersHash() == miners.GetMinersHash()); } return(false); }
public EnableDisableItemsDialog() { InitializeComponent(); DataContext = this; Assemblers.AddRange(DataCache.Current.Assemblers.Values.OrderBy(x => x.FriendlyName)); Miners.AddRange(DataCache.Current.Miners.Values.OrderBy(x => x.FriendlyName)); Modules.AddRange(DataCache.Current.Modules.Values.OrderBy(x => x.FriendlyName)); Mods.AddRange(DataCache.Current.Mods.OrderBy(x => x.Name)); }
private bool SetMiners(Miners miners, bool gonnaReplaceSomeone = false) { // Miners for one specific term should only update once. var m = State.MinersMap[miners.TermNumber.ToInt64Value()]; if (gonnaReplaceSomeone || m == null) { State.MinersMap[miners.TermNumber.ToInt64Value()] = miners; return(true); } return(false); }
public override IValue Serialize() { #pragma warning disable LAA1002 var values = new Dictionary <IKey, IValue> { [(Text)nameof(Miners)] = new List(Miners.Select(m => m.Serialize())), [(Text)nameof(Interval)] = Interval.Serialize(), [(Text)nameof(ValidUntil)] = ValidUntil.Serialize(), }; return(new Dictionary(values.Union((Dictionary)base.Serialize()))); #pragma warning restore LAA1002 }
/// <summary> /// 解除SN和Address绑定 /// </summary> /// <param name="address"></param> /// <param name="account"></param> /// <param name="sn"></param> public void PosSNUnbind(string address, string account, string sn) { MinersDac dac = new MinersDac(); Miners miner = new Miners(); //验证address是否合法 //try //{ // bool isValid = AccountIdHelper.AddressVerify(address); // if (!isValid) // { // throw new ApiCustomException(MiningPoolErrorCode.Miners.ADDRESS_IS_INVALID, "address is invalid"); // } //} //catch //{ // throw new ApiCustomException(MiningPoolErrorCode.Miners.ADDRESS_IS_INVALID, "address is invalid"); //} //先判断SN和Account的合法性 string url = MiningPoolSetting.POS_URL + "Api/Account/CheckAccount"; Dictionary <string, string> dic = new Dictionary <string, string>(); dic.Add("MerchantId", account); dic.Add("SN", sn); string response = ApiHelper.PostApi(url, dic); Dictionary <string, string> returnDic = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(response); if (string.IsNullOrEmpty(returnDic["Data"])) { throw new ApiCustomException(int.Parse(returnDic["Code"]), returnDic["Message"]); } //判断数据库中address是否存在 if (dac.IsAddressExisted(address.Trim())) { Miners existMiner = dac.GetMinerByAddress(address.Trim()); if (existMiner.SN == sn) { //解除绑定 dac.UpdateStatus(existMiner.Id, 1, account); } else { throw new ApiCustomException(MiningPoolErrorCode.Miners.ACCOUNT_AND_SN_IS_NOT_MATCH, "address and sn is not match"); } } else { throw new ApiCustomException(MiningPoolErrorCode.Miners.ADDRESS_NOT_EXIST, "address not exist"); } }
/// <summary> /// Miner leállítása /// </summary> public void StopMiner() { if (MinerType == MinerType.GPU) { Messenger.Default.Send <StopMinerThreadsMessage>(new StopMinerThreadsMessage()); } if (MinerType == MinerType.CPU) { terminateProcess(); } Miners.Clear(); }
/// <summary> /// 保存矿工信息 /// </summary> /// <param name="address"></param> /// <param name="account"></param> /// <param name="sn"></param> /// <returns></returns> public static Miners SaveMiners(string address, string account, string sn) { try { MinersComponent component = new MinersComponent(); Miners entity = component.RegisterMiner(address, account, sn); return(entity); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); return(null); } }
public void SaveChanges(Miner miner) { SaveChanges <Miner>(miner); for (int i = 0; i < Miners.Count; i++) { if (Miners[i].Identifier == miner.Identifier) { Miners.RemoveAt(i); Miners.Insert(i, miner); return; } } Miners.Add(miner); }
/// <summary> /// Send an email if any of the miners were loaded. /// </summary> /// <param name="miners"></param> public async Task <Response> EmailLoadedMinersAsync() { var minersLoaded = string.Empty; var myMiner = Miners[MY_INDEX]; // Create a text list of miners that were loaded. var loadedMiners = Miners.Where(miner => miner.CloneCausedReload && miner.IsNewData && miner.Name != myMiner.Name).ToList(); if (loadedMiners.Any()) { loadedMiners.ForEach(miner => minersLoaded += $"{miner.Name}\r\n"); return(await _mailUtility.SendAsync(null, null , $"MVP: {loadedMiners.Count} Miner(s) Loaded", $"Hey,\r\n\r\nThe following miners were loaded:\r\n\r\n{minersLoaded}\r\nTHANKS!,\r\n{Constants.APPLICATION_NAME}.")); } return(null); }
private void MinerBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { bool?modified = false; using (var context = new Context()) { foreach (var miner in context.Miners) { if (!Miners.Any(c => c.Id == miner.Id)) { Miners.Add(miner); modified = true; } } } e.Result = modified; }
public CommonResponse GetMinerInfoByAddress([FromBody] string address) { try { MinersComponent component = new MinersComponent(); Miners entity = component.GetMinerByAddress(address); return(OK(entity)); } catch (ApiCustomException ce) { LogHelper.Error(ce.Message); return(Error(ce.ErrorCode, ce.ErrorMessage)); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); return(Error(ex.HResult, ex.Message)); } }
public CommonResponse SaveMiners([FromBody] Miners miners) { try { MinersComponent component = new MinersComponent(); Miners entity = component.RegisterMiner(miners.Address, miners.Account, miners.SN); return(OK(entity)); } catch (ApiCustomException ce) { LogHelper.Error(ce.Message); return(Error(ce.ErrorCode, ce.ErrorMessage)); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); return(Error(ex.HResult, ex.Message)); } }
public CommonResponse POSValidate([FromBody] Miners miners) { try { MinersComponent component = new MinersComponent(); bool result = component.MinerLogin(miners.Address, miners.SN); return(OK(result)); } catch (ApiCustomException ce) { LogHelper.Error(ce.Message); return(Error(ce.ErrorCode, ce.ErrorMessage)); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); return(Error(ex.HResult, ex.Message)); } }
public CommonResponse PosSNUnbind([FromBody] Miners miners) { try { MinersComponent component = new MinersComponent(); component.PosSNUnbind(miners.Address, miners.Account, miners.SN); return(OK()); } catch (ApiCustomException ce) { LogHelper.Error(ce.Message); return(Error(ce.ErrorCode, ce.ErrorMessage)); } catch (Exception ex) { LogHelper.Error(ex.Message, ex); return(Error(ex.HResult, ex.Message)); } }
// public static bool IsEmpty(this Round round) // { // return round.RoundId == 0; // } // // public static string GetLogs(this Round round, string publicKey, DPoSBehaviour behaviour) // { // var logs = new StringBuilder($"\n[Round {round.RoundNumber}](Round Id: {round.RoundId})[Term {round.TermNumber}]"); // foreach (var minerInRound in round.RealTimeMinersInformation.Values.OrderBy(m => m.Order)) // { // var minerInformation = new StringBuilder("\n"); // minerInformation.Append($"[{minerInRound.PublicKey.Substring(0, 10)}]"); // minerInformation.Append(minerInRound.IsExtraBlockProducer ? "(Current EBP)" : ""); // minerInformation.AppendLine(minerInRound.PublicKey == publicKey // ? "(This Node)" // : ""); // minerInformation.AppendLine($"Order:\t {minerInRound.Order}"); // minerInformation.AppendLine( // $"Expect:\t {minerInRound.ExpectedMiningTime?.ToDateTime().ToUniversalTime():yyyy-MM-dd HH.mm.ss,ffffff}"); // minerInformation.AppendLine( // $"Actual:\t {minerInRound.ActualMiningTime?.ToDateTime().ToUniversalTime():yyyy-MM-dd HH.mm.ss,ffffff}"); // minerInformation.AppendLine($"Out:\t {minerInRound.OutValue?.ToHex()}"); // if (round.RoundNumber != 1) // { // minerInformation.AppendLine($"PreIn:\t {minerInRound.PreviousInValue?.ToHex()}"); // } // // minerInformation.AppendLine($"Sig:\t {minerInRound.Signature?.ToHex()}"); // minerInformation.AppendLine($"Mine:\t {minerInRound.ProducedBlocks}"); // minerInformation.AppendLine($"Miss:\t {minerInRound.MissedTimeSlots}"); // minerInformation.AppendLine($"Proms:\t {minerInRound.PromisedTinyBlocks}"); // minerInformation.AppendLine($"NOrder:\t {minerInRound.FinalOrderOfNextRound}"); // // logs.Append(minerInformation); // } // // logs.AppendLine($"Recent behaviour: {behaviour.ToString()}"); // // return logs.ToString(); // } // // public static Hash CalculateInValue(this Round round, Hash randomHash) // { // return Hash.FromTwoHashes(Hash.FromMessage(new Int64Value {Value = round.RoundId}), randomHash); // } // // public static MinerInRound GetExtraBlockProducerInformation(this Round round) // { // return round.RealTimeMinersInformation.First(bp => bp.Value.IsExtraBlockProducer).Value; // } // // /// <summary> // /// Maybe tune other miners' supposed order of next round, // /// will record this purpose to their FinalOrderOfNextRound field. // /// </summary> // /// <param name="round"></param> // /// <param name="publicKey"></param> // /// <returns></returns> // public static ToUpdate ExtractInformationToUpdateConsensus(this Round round, string publicKey) // { // if (!round.RealTimeMinersInformation.ContainsKey(publicKey)) // { // return null; // } // // var tuneOrderInformation = round.RealTimeMinersInformation.Values // .Where(m => m.FinalOrderOfNextRound != m.SupposedOrderOfNextRound) // .ToDictionary(m => m.PublicKey, m => m.FinalOrderOfNextRound); // // var decryptedPreviousInValues = round.RealTimeMinersInformation.Values.Where(v => // v.PublicKey != publicKey && v.DecryptedPreviousInValues.ContainsKey(publicKey)) // .ToDictionary(info => info.PublicKey, info => info.DecryptedPreviousInValues[publicKey]); // // var minersPreviousInValues = // round.RealTimeMinersInformation.Values.Where(info => info.PreviousInValue != null).ToDictionary(info => info.PublicKey, // info => info.PreviousInValue); // // var minerInRound = round.RealTimeMinersInformation[publicKey]; // return new ToUpdate // { // OutValue = minerInRound.OutValue, // Signature = minerInRound.Signature, // PreviousInValue = minerInRound.PreviousInValue ?? Hash.Empty, // RoundId = round.RoundId, // PromiseTinyBlocks = minerInRound.PromisedTinyBlocks, // ProducedBlocks = minerInRound.ProducedBlocks, // ActualMiningTime = minerInRound.ActualMiningTime, // SupposedOrderOfNextRound = minerInRound.SupposedOrderOfNextRound, // TuneOrderInformation = {tuneOrderInformation}, // EncryptedInValues = {minerInRound.EncryptedInValues}, // DecryptedPreviousInValues = {decryptedPreviousInValues}, // MinersPreviousInValues = {minersPreviousInValues} // }; // } // // public static Round ApplyNormalConsensusData(this Round round, string publicKey, Hash previousInValue, // Hash outValue, Hash signature, DateTime dateTime) // { // if (!round.RealTimeMinersInformation.ContainsKey(publicKey)) // { // return round; // } // // round.RealTimeMinersInformation[publicKey].ActualMiningTime = dateTime.ToTimestamp(); // round.RealTimeMinersInformation[publicKey].OutValue = outValue; // round.RealTimeMinersInformation[publicKey].Signature = signature; // round.RealTimeMinersInformation[publicKey].ProducedBlocks += 1; // if (previousInValue != Hash.Empty) // { // round.RealTimeMinersInformation[publicKey].PreviousInValue = previousInValue; // } // // var minersCount = round.RealTimeMinersInformation.Count; // var sigNum = // BitConverter.ToInt64( // BitConverter.IsLittleEndian ? signature.Value.Reverse().ToArray() : signature.Value.ToArray(), // 0); // var supposedOrderOfNextRound = GetAbsModulus(sigNum, minersCount) + 1; // // // Check the existence of conflicts about OrderOfNextRound. // // If so, modify others'. // var conflicts = round.RealTimeMinersInformation.Values // .Where(i => i.FinalOrderOfNextRound == supposedOrderOfNextRound).ToList(); // // foreach (var orderConflictedMiner in conflicts) // { // // Though multiple conflicts should be wrong, we can still arrange their orders of next round. // // for (var i = supposedOrderOfNextRound + 1; i < minersCount * 2; i++) // { // var maybeNewOrder = i > minersCount ? i % minersCount : i; // if (round.RealTimeMinersInformation.Values.All(m => m.FinalOrderOfNextRound != maybeNewOrder)) // { // round.RealTimeMinersInformation[orderConflictedMiner.PublicKey].FinalOrderOfNextRound = // maybeNewOrder; // break; // } // } // } // // round.RealTimeMinersInformation[publicKey].SupposedOrderOfNextRound = supposedOrderOfNextRound; // // Initialize FinalOrderOfNextRound as the value of SupposedOrderOfNextRound // round.RealTimeMinersInformation[publicKey].FinalOrderOfNextRound = supposedOrderOfNextRound; // // return round; // } // // public static List<MinerInRound> GetMinedMiners(this Round round) // { // // For now only this implementation can support test cases. // return round.RealTimeMinersInformation.Values.Where(m => m.SupposedOrderOfNextRound != 0).ToList(); // } // // public static List<MinerInRound> GetNotMinedMiners(this Round round) // { // // For now only this implementation can support test cases. // return round.RealTimeMinersInformation.Values.Where(m => m.SupposedOrderOfNextRound == 0).ToList(); // } // // public static bool GenerateNextRoundInformation(this Round currentRound, DateTime dateTime, // Timestamp blockchainStartTimestamp, out Round nextRound) // { // nextRound = new Round(); // // var minersMinedCurrentRound = currentRound.GetMinedMiners(); // var minersNotMinedCurrentRound = currentRound.GetNotMinedMiners(); // var minersCount = currentRound.RealTimeMinersInformation.Count; // // var miningInterval = currentRound.GetMiningInterval(); // nextRound.RoundNumber = currentRound.RoundNumber + 1; // nextRound.TermNumber = currentRound.TermNumber; // if (currentRound.RoundNumber == 1) // { // nextRound.BlockchainAge = 1; // } // else // { // nextRound.BlockchainAge = // (long) (dateTime - blockchainStartTimestamp.ToDateTime()) // .TotalMinutes; // TODO: Change to TotalDays after testing. // } // // // Set next round miners' information of miners who successfully mined during this round. // foreach (var minerInRound in minersMinedCurrentRound.OrderBy(m => m.FinalOrderOfNextRound)) // { // var order = minerInRound.FinalOrderOfNextRound; // nextRound.RealTimeMinersInformation[minerInRound.PublicKey] = new MinerInRound // { // PublicKey = minerInRound.PublicKey, // Order = order, // ExpectedMiningTime = dateTime.ToTimestamp().GetArrangedTimestamp(order, miningInterval), // PromisedTinyBlocks = minerInRound.PromisedTinyBlocks, // ProducedBlocks = minerInRound.ProducedBlocks, // MissedTimeSlots = minerInRound.MissedTimeSlots // }; // } // // // Set miners' information of miners missed their time slot in current round. // var occupiedOrders = minersMinedCurrentRound.Select(m => m.FinalOrderOfNextRound).ToList(); // var ableOrders = Enumerable.Range(1, minersCount).Where(i => !occupiedOrders.Contains(i)).ToList(); // for (var i = 0; i < minersNotMinedCurrentRound.Count; i++) // { // var order = ableOrders[i]; // var minerInRound = minersNotMinedCurrentRound[i]; // nextRound.RealTimeMinersInformation[minerInRound.PublicKey] = new MinerInRound // { // PublicKey = minersNotMinedCurrentRound[i].PublicKey, // Order = order, // ExpectedMiningTime = dateTime.ToTimestamp().GetArrangedTimestamp(order, miningInterval), // PromisedTinyBlocks = minerInRound.PromisedTinyBlocks, // ProducedBlocks = minerInRound.ProducedBlocks, // MissedTimeSlots = minerInRound.MissedTimeSlots + 1 // }; // } // // // Calculate extra block producer order and set the producer. // var extraBlockProducerOrder = currentRound.CalculateNextExtraBlockProducerOrder(); // var expectedExtraBlockProducer = // nextRound.RealTimeMinersInformation.Values.FirstOrDefault(m => m.Order == extraBlockProducerOrder); // if (expectedExtraBlockProducer == null) // { // nextRound.RealTimeMinersInformation.Values.First().IsExtraBlockProducer = true; // } // else // { // expectedExtraBlockProducer.IsExtraBlockProducer = true; // } // // return true; // } // // private static int CalculateNextExtraBlockProducerOrder(this Round round) // { // var firstPlaceInfo = round.GetFirstPlaceMinerInformation(); // if (firstPlaceInfo == null) // { // // If no miner produce block during this round, just appoint the first miner to be the extra block producer of next round. // return 1; // } // // var signature = firstPlaceInfo.Signature; // var sigNum = BitConverter.ToInt64( // BitConverter.IsLittleEndian ? signature.Value.Reverse().ToArray() : signature.Value.ToArray(), 0); // var blockProducerCount = round.RealTimeMinersInformation.Count; // var order = GetAbsModulus(sigNum, blockProducerCount) + 1; // return order; // } // // /// <summary> // /// Get the first valid (mined) miner's information, which means this miner's signature shouldn't be empty. // /// </summary> // /// <param name="round"></param> // /// <returns></returns> // public static MinerInRound GetFirstPlaceMinerInformation(this Round round) // { // return round.RealTimeMinersInformation.Values.OrderBy(m => m.Order) // .FirstOrDefault(m => m.Signature != null); // } // // public static Hash CalculateSignature(this Round previousRound, Hash inValue) // { // // Check the signatures // foreach (var minerInRound in previousRound.RealTimeMinersInformation) // { // if (minerInRound.Value.Signature == null) // { // minerInRound.Value.Signature = Hash.FromString(minerInRound.Key); // } // } // // return Hash.FromTwoHashes(inValue, // previousRound.RealTimeMinersInformation.Values.Aggregate(Hash.Empty, // (current, minerInRound) => Hash.FromTwoHashes(current, minerInRound.Signature))); // } // // public static Int64Value ToInt64Value(this long value) // { // return new Int64Value {Value = value}; // } // // public static StringValue ToStringValue(this string value) // { // return new StringValue {Value = value}; // } // // /// <summary> // /// Include both min and max value. // /// </summary> // /// <param name="value"></param> // /// <param name="min"></param> // /// <param name="max"></param> // /// <returns></returns> // public static bool InRange(this int value, int min, int max) // { // return value >= min && value <= max; // } // public static Round GenerateFirstRoundOfNewTerm(this Miners miners, int miningInterval, DateTime currentBlockTime, long currentRoundNumber = 0, long currentTermNumber = 0) { var dict = new Dictionary <string, int>(); foreach (var miner in miners.PublicKeys) { dict.Add(miner, miner[0]); } var sortedMiners = (from obj in dict orderby obj.Value descending select obj.Key).ToList(); var round = new Round(); for (var i = 0; i < sortedMiners.Count; i++) { var minerInRound = new MinerInRound(); // The first miner will be the extra block producer of first round of each term. if (i == 0) { minerInRound.IsExtraBlockProducer = true; } minerInRound.PublicKey = sortedMiners[i]; minerInRound.Order = i + 1; minerInRound.ExpectedMiningTime = currentBlockTime.AddMilliseconds((i * miningInterval) + miningInterval).ToTimestamp(); minerInRound.PromisedTinyBlocks = 1; // Should be careful during validation. minerInRound.PreviousInValue = Hash.Empty; round.RealTimeMinersInformation.Add(sortedMiners[i], minerInRound); } round.RoundNumber = currentRoundNumber + 1; round.TermNumber = currentTermNumber + 1; return(round); }
public void GenerateUsersAndTransactions() { Random rnd = new Random(); //Generates Users for (var i = 0; i < 1000; i++) { var name = $"user{i}"; var userHash = HashFunction.GetHash(name); var balance = rnd.Next(100, 1000); Users.Add(new User(name, userHash, balance)); } //Generates Miners for (var i = 0; i < 10; i++) { var name = $"miner{i}"; var userHash = HashFunction.GetHash(name); var balance = 0; Miners.Add(new User(name, userHash, balance)); } //Generates random x number transactions for (var i = 0; i < 10000; i++) { var senderIndex = rnd.Next(Users.Count); var receiverIndex = rnd.Next(Users.Count); //If receiver is same as sender while (receiverIndex == senderIndex) { receiverIndex = rnd.Next(Users.Count); } var amount = rnd.Next(10, 250); var sender = Users[senderIndex]; var receiver = Users[receiverIndex]; CreateTransaction(new Transaction(sender, receiver, amount)); } }
public string GetFMLNerdLink(IMiner miner) { string url = "http://analyzer.fmlnerd.com/lineups/?ests="; string movieList = null; var nerdList = Miners.First(); foreach (var movie in nerdList.Movies) { var minerMovie = miner.Movies.FirstOrDefault(item => item.Name == movie.Name); if (movieList != null) { movieList += ","; } movieList += minerMovie == null ? "0" : minerMovie.Earnings.ToString(); } return(url + movieList); }
public string WeightListForMiner(IMiner minerToCheck) { var builder = new StringBuilder(); bool first = true; builder.Append("wl="); foreach (var miner in Miners.Skip(1)) { if (!first) { builder.Append(","); } first = false; builder.Append(minerToCheck == miner ? "1" : "0"); } return(builder.ToString()); }
public bool RemoveMiner(IMiner miner) { bool toSave = false; List <int> removeIds = new List <int>(); int i = 0; foreach (MinerData item in Miners) { if (item.Id == miner.Id) { removeIds.Add(i); toSave = true; } i++; } foreach (int j in removeIds) { Miners.RemoveAt(j); } return(toSave); }
public List <Miners> SelectAll() { const string SQL_STATEMENT = "SELECT Id, Address, Account, Type, SN, Status, Timstamp, LastLoginTime, UnpaidReward, PaidReward " + "FROM Miners WHERE Status = 0;"; List <Miners> result = null; //LogHelper.Info("CacheConnectionString" + CacheConnectionString); using (MySqlConnection conn = new MySqlConnection(CacheConnectionString)) using (MySqlCommand cmd = new MySqlCommand(SQL_STATEMENT, conn)) { cmd.Connection.Open(); cmd.CommandTimeout = 1200; using (MySqlDataReader dr = cmd.ExecuteReader()) { result = new List <Miners>(); while (dr.Read()) { Miners miner = new Miners(); miner.Id = GetDataValue <long>(dr, "Id"); miner.Address = GetDataValue <string>(dr, "Address"); miner.Account = GetDataValue <string>(dr, "Account"); miner.Type = GetDataValue <int>(dr, "Type"); miner.SN = GetDataValue <string>(dr, "SN"); miner.Status = GetDataValue <int>(dr, "Status"); miner.Timstamp = GetDataValue <long>(dr, "Timstamp"); miner.LastLoginTime = GetDataValue <long>(dr, "LastLoginTime"); miner.UnpaidReward = GetDataValue <long>(dr, "UnpaidReward"); miner.PaidReward = GetDataValue <long>(dr, "PaidReward"); result.Add(miner); } } } return(result); }
private bool RemoveMiner(Miner miner) { var removeItem = Context.Miners.FirstOrDefault(c => c.Id == miner.Id); if (removeItem != null) { try { Context.Miners.Remove(removeItem); Context.SaveChanges(); lock (NodeLock) { Miners.Remove(miner); var node = Nodes.FirstOrDefault(c => c.Key == TreeNode.RootNodes.Miners); if (node != null) { var item = node.Children.FirstOrDefault(c => c.Key == miner.Id.ToString()); if (item != null) { node.Children.Remove(item); } } } } catch (Exception) { return(false); } return(true); } return(false); }
public void Insert(Miners miner) { const string SQL_STATEMENT = "INSERT INTO Miners " + "(Address, Account, Type, SN, Status, Timstamp, LastLoginTime, UnpaidReward, PaidReward) " + "VALUES (@Address, @Account, @Type, @SN, @Status, @Timstamp, @LastLoginTime, 0, 0);"; using (MySqlConnection conn = new MySqlConnection(CacheConnectionString)) using (MySqlCommand cmd = new MySqlCommand(SQL_STATEMENT, conn)) { cmd.Parameters.AddWithValue("@Address", miner.Address); cmd.Parameters.AddWithValue("@Account", miner.Account); cmd.Parameters.AddWithValue("@Type", miner.Type); cmd.Parameters.AddWithValue("@SN", miner.SN); cmd.Parameters.AddWithValue("@Status", miner.Status); cmd.Parameters.AddWithValue("@Timstamp", miner.Timstamp); cmd.Parameters.AddWithValue("@LastLoginTime", miner.LastLoginTime); cmd.Connection.Open(); cmd.CommandTimeout = 1200; cmd.ExecuteNonQuery(); } }