private async Task BtnClickTask() { try { using (var client = new HttpClient()) { var resp = await client.GetAsync($"https://api2.nicehash.com/api/v2/organization/nhmqr/{_uuid}"); if (resp.IsSuccessStatusCode) { var contentString = await resp.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(contentString)) { var btcResp = JsonConvert.DeserializeObject <BtcResponse>(contentString); if (btcResp.btc != null) { if (CredentialValidators.ValidateBitcoinAddress(btcResp.btc)) { CredentialsSettings.Instance.SetBitcoinAddress(btcResp.btc); Close(); } } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void SetCredentials(string btc, string worker, string group) { if (CredentialValidators.ValidateBitcoinAddress(btc) && CredentialValidators.ValidateWorkerName(worker)) { // Send as task since SetCredentials is called from UI threads Task.Factory.StartNew(() => { SendMinerStatus(false); _socket?.StartConnection(btc, worker, group); }); } }
private void ButtonOK_Click(object sender, EventArgs e) { var loginForm = new LoginForm(); SetChildFormCenter(loginForm); loginForm.ShowDialog(); if (CredentialValidators.ValidateBitcoinAddress(loginForm.Btc)) { ConfigManager.GeneralConfig.BitcoinAddress = loginForm.Btc; ConfigManager.GeneralConfigFileCommit(); Close(); } }
private async Task ProcessQRCode() { var rigID = ApplicationStateManager.RigID(); var requestBody = "{\"qrId\":\"" + _uuid + "\", \"rigId\":\"" + rigID + "\"}"; var content = new StringContent(requestBody, Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { var response = await client.PostAsync("https://api2.nicehash.com/api/v2/organization/nhmqr", content); } // create qr code rect_qrCode.Fill = QrCodeHelpers.GetQRCode(_uuid); //if all ok start timer to poll while (true) { await Task.Delay(2000); try { using (var client = new HttpClient()) { var resp = await client.GetAsync($"https://api2.nicehash.com/api/v2/organization/nhmqr/{_uuid}"); if (resp.IsSuccessStatusCode) { var contentString = await resp.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(contentString)) { var btcResp = JsonConvert.DeserializeObject <BtcResponse>(contentString); if (btcResp.btc != null) { if (CredentialValidators.ValidateBitcoinAddress(btcResp.btc)) { CredentialsSettings.Instance.SetBitcoinAddress(btcResp.btc); Close(); } } } } } } catch (Exception e) { Console.WriteLine(e.Message); } } }
// Don't call SendData on UI threads, since it will block the thread for a bit if a reconnect is needed public bool SendData(string data, bool recurs = false) { // skip sending if no btc set send only login if (CredentialValidators.ValidateBitcoinAddress(_login.btc) == false && data.Contains("{\"method\":\"login\"") == false) { NHM.Common.Logger.Info("SOCKET", "Skipping SendData no BTC address"); return(false); } try { // Make sure connection is open if (_webSocket != null && IsAlive) { NHM.Common.Logger.Info("SOCKET", $"Sending data: {data}"); _webSocket.Send(data); return(true); } else if (_webSocket != null) { if (AttemptReconnect() && !recurs) { // Reconnect was successful, send data again (safety to prevent recursion overload) SendData(data, true); } else { NHM.Common.Logger.Info("SOCKET", "Socket connection unsuccessfull, will try again on next device update (1min)"); } } else { if (!_connectionAttempted) { NHM.Common.Logger.Info("SOCKET", "Data sending attempted before socket initialization"); } else { NHM.Common.Logger.Info("SOCKET", "webSocket not created, retrying"); StartConnection(); } } } catch (Exception e) { NHM.Common.Logger.Info("NiceHashSocket", $"Error occured while sending data: {e.Message}"); } return(false); }
private void ValidateBTCAddr() { var trimmedBtcText = textBoxBTCAddress.Text.Trim(); var btcOK = CredentialValidators.ValidateBitcoinAddress(trimmedBtcText); if (btcOK) { textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxGood") as Style; textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("NastyGreenBrush"); } else { textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxBad") as Style; textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("RedDangerColorBrush"); } }
public static void SetCredentials(string btc, string worker, string group = "UNUSED STUB ONLY TO BE SAME AS TESTNET") { var data = new NicehashCredentials { btc = btc, worker = worker }; if (CredentialValidators.ValidateBitcoinAddress(data.btc) && CredentialValidators.ValidateWorkerName(worker)) { var sendData = JsonConvert.SerializeObject(data); // Send as task since SetCredentials is called from UI threads Task.Factory.StartNew(() => _socket?.SendData(sendData)); } }
public static CredentialsValidState GetCredentialsValidState() { // assume it is valid var ret = CredentialsValidState.VALID; if (!CredentialValidators.ValidateBitcoinAddress(ConfigManager.GeneralConfig.BitcoinAddress)) { ret |= CredentialsValidState.INVALID_BTC; } if (!CredentialValidators.ValidateWorkerName(ConfigManager.GeneralConfig.WorkerName)) { ret |= CredentialsValidState.INVALID_WORKER; } return(ret); }
private void ValidateWorkername() { var trimmedWorkername = textBoxWorkerName.Text.Trim(); var btcOK = CredentialValidators.ValidateWorkerName(trimmedWorkername); if (btcOK) { textBoxWorkerName.Style = Application.Current.FindResource("InputBoxGood") as Style; textBoxWorkerName.BorderBrush = (Brush)Application.Current.FindResource("NastyGreenBrush"); } else { textBoxWorkerName.Style = Application.Current.FindResource("InputBoxBad") as Style; textBoxWorkerName.BorderBrush = (Brush)Application.Current.FindResource("RedDangerColorBrush"); } }
private async Task Confirm_Scan_ClickTask() { if (!_gotQRCode) { await InitQRCode(); return; } var btc = await GetBTCForUUID(_uuid); if (CredentialValidators.ValidateBitcoinAddress(btc)) { Logger.Info("LoginWindow.Confirm_Scan_ClickTask", $"Got valid btc address: {btc}"); CredentialsSettings.Instance.SetBitcoinAddress(btc); Close(); } }
private void SaveButtonClicked(object sender, RoutedEventArgs e) { var trimmedBtcText = textBoxBTCAddress.Text.Trim(); if (CredentialValidators.ValidateBitcoinAddress(trimmedBtcText)) { textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxGood") as Style; textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("NastyGreenBrush"); CredentialsSettings.Instance.SetBitcoinAddress(trimmedBtcText); Close(); } else { textBoxBTCAddress.Style = Application.Current.FindResource("InputBoxBad") as Style; textBoxBTCAddress.BorderBrush = (Brush)Application.Current.FindResource("RedDangerColorBrush"); } }
private void WorkernameValidation() { var trimmedBtcText = textBoxWorkername.Text.Trim(); var isOK = CredentialValidators.ValidateWorkerName(trimmedBtcText); SaveButton.IsEnabled = isOK; if (isOK) { textBoxWorkername.Style = Application.Current.FindResource("InputBoxGood") as Style; textBoxWorkername.BorderBrush = (Brush)Application.Current.FindResource("NastyGreenBrush"); } else { textBoxWorkername.Style = Application.Current.FindResource("InputBoxBad") as Style; textBoxWorkername.BorderBrush = (Brush)Application.Current.FindResource("RedDangerColorBrush"); } }
// make sure to pass in trimmedBtc public static SetResult SetBTCIfValidOrDifferent(string btc, bool skipCredentialsSet = false) { if (btc == ConfigManager.GeneralConfig.BitcoinAddress && btc != "") { return(SetResult.NOTHING_TO_CHANGE); } if (!CredentialValidators.ValidateBitcoinAddress(btc)) { ConfigManager.GeneralConfig.BitcoinAddress = btc; return(SetResult.INVALID); } SetBTC(btc); if (!skipCredentialsSet) { _resetNiceHashStatsCredentialsDelayed.ExecuteDelayed(CancellationToken.None); } return(SetResult.CHANGED); }
// make sure to pass in trimmed workerName // skipCredentialsSet when calling from RPC, workaround so RPC will work public static SetResult SetWorkerIfValidOrDifferent(string workerName, bool skipCredentialsSet = false) { if (workerName == CredentialsSettings.Instance.WorkerName) { return(SetResult.NOTHING_TO_CHANGE); } if (!CredentialValidators.ValidateWorkerName(workerName)) { return(SetResult.INVALID); } SetWorker(workerName); if (!skipCredentialsSet) { _resetNiceHashStatsCredentialsDelayed.ExecuteDelayed(CancellationToken.None); } return(SetResult.CHANGED); }
// make sure to pass in trimmed workerName // skipCredentialsSet when calling from RPC, workaround so RPC will work public static async Task <SetResult> SetWorkerIfValidOrDifferent(string workerName, bool skipCredentialsSet = false) { if (workerName == ConfigManager.GeneralConfig.WorkerName) { return(SetResult.NOTHING_TO_CHANGE); } if (!CredentialValidators.ValidateWorkerName(workerName)) { return(SetResult.INVALID); } await SetWorker(workerName); if (!skipCredentialsSet) { _resetNiceHashStatsCredentialsDelayed.ExecuteDelayed(CancellationToken.None); } return(SetResult.CHANGED); }
// make sure to pass in trimmedBtc public static async Task <SetResult> SetBTCIfValidOrDifferent(string btc, bool skipCredentialsSet = false) { if (btc == CredentialsSettings.Instance.BitcoinAddress && btc != "") { return(SetResult.NOTHING_TO_CHANGE); } if (!CredentialValidators.ValidateBitcoinAddress(btc)) { // TODO if RPC set only if valid if local then just set it //CredentialsSettings.Instance.BitcoinAddress = btc; return(SetResult.INVALID); } await SetBTC(btc); if (!skipCredentialsSet) { _resetNiceHashStatsCredentialsDelayed.ExecuteDelayed(CancellationToken.None); } return(SetResult.CHANGED); }
static private void Login(object sender, EventArgs e) { NHLog.Info("NHWebSocket", "Connected"); try { // always send login var loginJson = JsonConvert.SerializeObject(_login); var sendMessages = new List <NHSendMessage> { new NHSendMessage(MessageType.SEND_MESSAGE, loginJson) }; if (CredentialValidators.ValidateBitcoinAddress(_login.btc)) { var minerStatusJsonStr = CreateMinerStatusMessage(true); sendMessages.Add(new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr)); } _sendQueue.Enqueue(sendMessages); } catch (Exception er) { NHLog.Info("NHWebSocket", er.Message); } }
// this one is bulletproof, takes 2s for 1MB string public static string FindBtcInText2(string text) { // 2 is for testnet btc others are 1, 3 and bc1 const string btcStartAlphabet = "123bc"; const int min = 26; const int max = 35; if (string.IsNullOrEmpty(text) || text.Length < min) { return(""); // nope } for (int i = 0; i < text.Length - min; i++) { char startC = text[i]; if (!btcStartAlphabet.Contains(startC)) { continue; } var left = text.Length - i; var subText = text.Substring(i, left > max ? max : left); var btc = ""; foreach (char c in subText) { if (!btcAlphabet.Contains(c) || btc.Length > max) { break; } btc += c; if (btc.Length > min && CredentialValidators.ValidateBitcoinAddress(btc)) { return(btc); } } } return(""); }
// TODO add cancelation token static private async Task NewConnection(CancellationToken stop) { NHLog.Info("NHWebSocket", "STARTING nhmws SESSION"); try { // TODO if we fill the Queue before this we should start fresh afterwards // TODO think if we might want to dump prev data???? // on each new connection clear the ConcurrentQueues, _recieveQueue = new ConcurrentQueue <MessageEventArgs>(); _sendQueue = new ConcurrentQueue <IEnumerable <NHSendMessage> >(); _isNhmwsRestart = false; _notifyMinerStatusAfter.Value = null; NHLog.Info("NHWebSocket", "Creating socket"); using (_webSocket = new WebSocket(_address, true)) { //stop.Register(() => _webSocket.Close(CloseStatusCode.Normal, "Closing CancellationToken")); _webSocket.OnOpen += Login; _webSocket.OnMessage += (s, eMsg) => _recieveQueue.Enqueue(eMsg); _webSocket.OnError += (s, e) => NHLog.Info("NHWebSocket", $"Error occured: {e.Message}"); _webSocket.OnClose += (s, e) => NHLog.Info("NHWebSocket", $"Connection closed code {e.Code}: {e.Reason}");; _webSocket.Log.Level = LogLevel.Debug; _webSocket.Log.Output = (data, s) => NHLog.Info("NHWebSocket", data.ToString()); _webSocket.EnableRedirection = true; NHLog.Info("NHWebSocket", "Connecting"); _webSocket.Connect(); const int minerStatusTickSeconds = 45; var checkWaitTime = TimeSpan.FromMilliseconds(50); var skipMinerStatus = !CredentialValidators.ValidateBitcoinAddress(_login.btc); NHLog.Info("NHWebSocket", "Starting Loop"); while (IsWsAlive && !stop.IsCancellationRequested) { if (IsWsAlive) { HandleSendMessage(); } if (IsWsAlive) { await HandleReceiveMessage(); } // TODO add here the last miner status send check if (IsWsAlive) { await Task.Delay(checkWaitTime); // TODO add cancelation token here } if (skipMinerStatus) { continue; } var elapsedTime = DateTime.UtcNow - _lastSendMinerStatusTimestamp.Value; if (elapsedTime.TotalSeconds > minerStatusTickSeconds) { var minerStatusJsonStr = CreateMinerStatusMessage(); var minerStatus = new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr); _sendQueue.Enqueue(new NHSendMessage[1] { minerStatus }); } if (_notifyMinerStatusAfter.Value.HasValue && DateTime.UtcNow >= _notifyMinerStatusAfter.Value.Value) { _notifyMinerStatusAfter.Value = null; var minerStatusJsonStr = CreateMinerStatusMessage(); var minerStatus = new NHSendMessage(MessageType.SEND_MESSAGE_STATUS, minerStatusJsonStr); _sendQueue.Enqueue(new NHSendMessage[1] { minerStatus }); } } // Ws closed NHLog.Info("NHWebSocket", "Exited Loop"); } } finally { NHLog.Info("NHWebSocket", "ENDING nhmws SESSION"); } }
private async Task ProcessQRCode() { stopWatch = new Stopwatch(); stopWatch.Start(); var rigID = ApplicationStateManager.RigID(); var requestBody = "{\"qrId\":\"" + _uuid + "\", \"rigId\":\"" + rigID + "\"}"; var content = new StringContent(requestBody, Encoding.UTF8, "application/json"); using (var client = new HttpClient()) { var response = await client.PostAsync("https://api2.nicehash.com/api/v2/organization/nhmqr", content); } // create qr code rect_qrCode.Fill = QrCodeHelpers.GetQRCode(_uuid, GUISettings.Instance.DisplayTheme == "Light"); //if all ok start timer to poll while (true) { await Task.Delay(2000); try { using (var client = new HttpClient()) { var resp = await client.GetAsync($"https://api2.nicehash.com/api/v2/organization/nhmqr/{_uuid}"); if (resp.IsSuccessStatusCode) { var contentString = await resp.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(contentString)) { var btcResp = JsonConvert.DeserializeObject <BtcResponse>(contentString); if (btcResp.btc != null) { if (CredentialValidators.ValidateBitcoinAddress(btcResp.btc)) { var ret = await ApplicationStateManager.SetBTCIfValidOrDifferent(btcResp.btc); if (ret == ApplicationStateManager.SetResult.CHANGED) { lbl_qr_status.Visibility = Visibility.Visible; btn_gen_qr.Visibility = Visibility.Visible; lbl_qr_status.Content = "BTC Address was changed - this code is already used."; } return; } } } } } } catch (Exception e) { Console.WriteLine(e.Message); } if (stopWatch.ElapsedMilliseconds >= (1000 * 60 * 10)) { lbl_qr_status.Visibility = Visibility.Visible; btn_gen_qr.Visibility = Visibility.Visible; lbl_qr_status.Content = "QR Code timeout. Please generate new one."; return; } } }
public ApiSettings(TwitchAPI api) { Validators = new CredentialValidators(); _api = api; }