public GenericResponse GetBlocks(int fromIndex, int toIndex) { try { if (toIndex < fromIndex) { return(new GenericResponse(null, ResponseCodes.ViewBlocksInvalidIndex, ResponseMessages.ViewBlocksInvalidIndex)); } if ((toIndex - fromIndex) > 100) { return(new GenericResponse(null, ResponseCodes.ViewBlocksTooMany, ResponseMessages.ViewBlocksTooMany)); } ViewerServices viewerService = new ViewerServices(); var blocks = viewerService.GetBlocks(fromIndex, toIndex); return(new GenericResponse(blocks, ResponseCodes.Success, ResponseMessages.Success)); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse StartConsensus(string walletAddress, string signature) { try { if (ApplicationState.ServerState != ServerStates.Active) { return(new GenericResponse(null, ResponseCodes.ServerNotStarted, ResponseMessages.ServerNotStarted)); } if (ApplicationState.ConsensusState != null && ApplicationState.ConsensusState != ConsensusStates.Inactive) { return(new GenericResponse(null, ResponseCodes.ConsensusAlreadyActive, ResponseMessages.ConsensusAlreadyActive)); } ApplicationState.ConsensusState = ConsensusStates.Started; ApplicationState.LiveEpochCount = 0; ConsensusServices consensusService = new ConsensusServices(); consensusService.RetrieveNetworkNodes(); consensusService.RegisterSelfOnNetwork(walletAddress, signature, true); consensusService.NextEpoch(); return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse GetConnectedNodes() { try { ApplicationLog.Info("Retrieving connected nodes."); var nodes = ApplicationState.ConnectedNodes; //Filter out nodes flagged as disconnected foreach (var disconnectedNode in ApplicationState.DisconnectedNodes) { if (disconnectedNode.ServerAddress != ApplicationState.Node.ServerAddress) { var removeNode = nodes.Where(x => x.ServerAddress == disconnectedNode.ServerAddress).FirstOrDefault(); if (removeNode != null) { nodes.Remove(removeNode); } } } return(new GenericResponse(nodes, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse AddOrderMarket(TransactionOrderMarketRequest value) { try { VerifySignature(value.Body, value.Signature, value.Body.Owner); if (!ApplicationState.IsChainUpToDate) { return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.NodeNotConsensusReady)); } //Perform transaction TransactionServices transactionService = new TransactionServices(); List <string> txIds = transactionService.AddMarketOrder( value.Body.Nonce, Convert.ToDecimal(value.Body.Fee), value.Body.PairSymbol, value.Body.Side, Convert.ToDecimal(value.Body.Amount), value.Body.Owner); ApplicationLog.Info("Transaction added to queue for next block."); return(new GenericResponse(txIds, ResponseCodes.Success, "Transaction added to queue for next block.")); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse CreateNewChain(string ownerAddress) { try { DataServices dataService = new DataServices(); if (dataService.HasLocalChainData()) { throw new Exception("Chain folder is not empty. Please delete the existing chain folder first before creating a new chain."); } ApplicationLog.Info("Creating new chain..."); dataService.CreateGenesisBlock( ownerAddress, Settings.NewChainSetup.NativeTokenName, Settings.NewChainSetup.NativeTokenSymbol, Settings.NewChainSetup.InitialSupply, Settings.NewChainSetup.Decimals); ApplicationLog.Info("Chain created successfully."); return(new GenericResponse("Chain created successfully.", ResponseCodes.Success, ResponseMessages.Success)); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse DeleteLocalChain() { try { DataServices dataService = new DataServices(); if (dataService.HasLocalChainData()) { dataService.DeleteLocalChain(); } ApplicationLog.Info("Local chain data deleted successfully."); return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public string SendGetRequest(string endpoint) { string jsonResponse = string.Empty; string result = null; try { using (WebClient client = new WebClient()) { client.Headers[HttpRequestHeader.Accept] = "application/json"; client.Headers["sender"] = JsonConvert.SerializeObject(ApplicationState.Node); //TODO: Future enhancement: sign sender to prevent impersonation from other nodes jsonResponse = client.DownloadString(new Uri(endpoint)); } var response = JsonConvert.DeserializeObject <GenericResponse>(jsonResponse); if (response.Code != ResponseCodes.Success) { throw new Exception(response.Code + ":" + response.Message); } else { if (response.Data != null) { result = response.Data.ToString(); } } return(result); } catch (Exception ex) { ApplicationLog.Exception(ex); throw; } }
public GenericResponse Transfer(TransactionTransferRequest value) { try { VerifySignature(value.Body, value.Signature, value.Body.Sender); if (!ApplicationState.IsChainUpToDate) { return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.NodeNotConsensusReady)); } //Perform transaction TransactionServices transactionService = new TransactionServices(); string txId = transactionService.AddTransfer( value.Body.Nonce, Convert.ToDecimal(value.Body.Fee), value.Body.TokenSymbol, value.Body.Sender, value.Body.ToAddress, Convert.ToDecimal(value.Body.Amount)); ApplicationLog.Info("Transaction added to queue for next block. TxId: " + txId); return(new GenericResponse(txId, ResponseCodes.Success, "Transaction added to queue for next block.")); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse GetOrders(string tradingPair) { try { IndexServices indexServices = new IndexServices(); var orders = indexServices.OrderIndex.GetByTradingPair(tradingPair); if (orders != null) { orders = orders.OrderByDescending(x => x.Price).ToList(); return(new GenericResponse(orders, ResponseCodes.Success, ResponseMessages.Success)); } else { return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
private static void Echo(HttpRequest request) { try { //If request is already an echo, don't re-echo if (request.Headers.ContainsKey("echo")) { return; } //Set header to identity that this message is an echo Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("echo", "1"); //Echo to all other nodes in network var nodes = ApplicationState.ConnectedNodesExceptSelf; Parallel.ForEach(nodes, new ParallelOptions { MaxDegreeOfParallelism = ConstantConfig.BroadcastThreadCount }, networkNode => { ApiClient api = new ApiClient(networkNode.ServerAddress); api.SendPostRequest(request.Url, request.Content, headers); }); } catch (Exception ex) { ApplicationLog.Exception(ex); } }
public GenericResponse GetWelcome() { try { return(new GenericResponse(null, ResponseCodes.Success, "Welcome to DEXR. Please view documentation for API usage.")); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse Sign(string privateKey, string content) { try { string signature = KeySignature.Sign(privateKey, content); return(new GenericResponse(signature, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse GetAllTokens() { try { IndexServices indexService = new IndexServices(); var index = indexService.TokenIndex.GetAll(); return(new GenericResponse(index, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse GenerateWalletAddress() { try { DataServices dataService = new DataServices(); var result = dataService.GenerateWalletAddress(); return(new GenericResponse(result, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse RebuildIndex() { try { IndexServices indexServices = new IndexServices(); indexServices.DeleteIndexForAllBlocks(); indexServices.UpdateIndexForAllBlocks(); return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public string SendPostRequest(string endpoint, string data, Dictionary <string, string> additionalHeaders = null) { string jsonResponse = string.Empty; string result = null; try { using (WebClient client = new WebClient()) { //Create headers client.Headers[HttpRequestHeader.Accept] = "application/json"; client.Headers["sender"] = JsonConvert.SerializeObject(ApplicationState.Node); //TODO: Future enhancement: sign sender to prevent impersonation from other nodes if (additionalHeaders != null) { foreach (var item in additionalHeaders) { client.Headers[item.Key] = item.Value; } } //Post Request jsonResponse = client.UploadString(new Uri(endpoint), data); } var response = JsonConvert.DeserializeObject <GenericResponse>(jsonResponse); if (response.Code != ResponseCodes.Success) { throw new Exception(response.Code + ":" + response.Message); } else { if (response.Data != null) { result = response.Data.ToString(); } } return(result); } catch (Exception ex) { ApplicationLog.Exception(ex); throw; } }
public async void NextEpoch() { try { ApplicationLog.Info("Beginning new epoch iteration"); ApplicationState.ConsensusState = ConsensusStates.BeginningEpoch; ApplicationState.CurrentSpeaker = null; NodeChainHeight longestChainNode = null; if (ApplicationState.DisconnectedNodes.Count > 0) { RemoveDisconnectedNodes(); //TODO: subsequent epoch can retrieve network nodes from other nodes instead of from seed RetrieveNetworkNodes(); } if (IsChainUpToDate(out longestChainNode)) { ApplicationState.IsChainUpToDate = true; ApplicationState.LiveEpochCount++; SelectSpeaker(); } else { ApplicationState.IsChainUpToDate = false; SyncChain(longestChainNode); ApplicationState.LiveEpochCount = 0; ApplicationState.PendingRecords.Clear(); RegisterSelfOnNetwork(ApplicationState.Node.WalletAddress, ApplicationState.Node.Signature, false); NextEpoch(); } } catch (Exception ex) { ApplicationLog.Exception(ex); ApplicationLog.Info("Retry in 30 seconds."); await Task.Delay(30 * 1000); NextEpoch(); } }
public GenericResponse GetPending() { try { ViewerServices viewerService = new ViewerServices(); var pending = viewerService.GetPending(); return(new GenericResponse(pending, ResponseCodes.Success, ResponseMessages.Success)); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse RegisterNodeAnnouncement(string serverAddress, string walletAddress, string signature) { try { VerifySignature(walletAddress, signature, walletAddress); //Get wallet balance decimal walletBalance = 0; IndexServices indexServices = new IndexServices(); var nativeToken = indexServices.TokenIndex.GetNative(); if (nativeToken != null) //Native token would be null if chain has not yet been sync / no local chain { var walletIndex = indexServices.BalanceIndex.Get(walletAddress, indexServices.TokenIndex.GetNative().Symbol); if (walletIndex != null) { walletBalance = walletIndex.Balance; } } //Add node to consensus Node node = new Node() { ServerAddress = serverAddress, WalletAddress = walletAddress, Signature = signature, Balance = walletBalance }; ConsensusServices consensusService = new ConsensusServices(); consensusService.AddConsensusNode(node); ApplicationLog.Info("Registered node: " + node.ServerAddress); return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
public GenericResponse GetWalletBalance(string address, string tokenSymbol) { try { ViewerServices viewerServices = new ViewerServices(); decimal?balance = viewerServices.GetWalletBalance(address, tokenSymbol); return(new GenericResponse(balance, ResponseCodes.Success, ResponseMessages.Success)); } catch (ValidationException vex) { ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message); return(new GenericResponse(null, vex.Code, vex.Message)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } }
/// <summary> /// This method expects a single XML document and returns one BlastResult. /// </summary> /// <param name="doc">A Stringbuilder containing the XML document.</param> /// <returns>The BlastResult.</returns> private static BlastResult ParseXML(StringBuilder doc) { BlastResult result = new BlastResult(); try { var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Ignore }; StringReader sr = null; try { sr = new StringReader(doc.ToString()); using (XmlReader r = XmlReader.Create(sr, settings)) { string curElement = string.Empty; BlastSearchRecord curRecord = new BlastSearchRecord(); Hit curHit = null; Hsp curHsp = null; BlastStatistics curStatistics = null; BlastXmlMetadata curMetadata = null; while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: curElement = r.Name; switch (curElement) { case "Hit": curHit = new Hit(); break; case "Hsp": curHsp = new Hsp(); break; case "Statistics": curStatistics = new BlastStatistics(); break; case "BlastOutput": curMetadata = new BlastXmlMetadata(); break; } break; case XmlNodeType.Text: if (curElement.StartsWith("BlastOutput_", StringComparison.OrdinalIgnoreCase)) { DoBlastOutput(curElement, r.Value, curMetadata); } else if (curElement.StartsWith("Parameters_", StringComparison.OrdinalIgnoreCase)) { DoParameters(curElement, r.Value, curMetadata); } else if (curElement.StartsWith("Iteration_", StringComparison.OrdinalIgnoreCase)) { DoIteration(curElement, r.Value, curRecord); } else if (curElement.StartsWith("Statistics_", StringComparison.OrdinalIgnoreCase)) { DoStatistics(curElement, r.Value, curStatistics); } else if (curElement.StartsWith("Hit_", StringComparison.OrdinalIgnoreCase)) { DoHit(curElement, r.Value, curHit); } else if (curElement.StartsWith("Hsp_", StringComparison.OrdinalIgnoreCase)) { DoHsp(curElement, r.Value, curHsp); } break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: break; case XmlNodeType.EndElement: if (r.Name == "Iteration") { result.Records.Add(curRecord); curRecord = new BlastSearchRecord(); } else if (r.Name == "Statistics") { curRecord.Statistics = curStatistics; } else if (r.Name == "Hit") { curRecord.Hits.Add(curHit); } else if (r.Name == "Hsp") { curHit.Hsps.Add(curHsp); } else if (r.Name == "BlastOutput") { result.Metadata = curMetadata; } break; } } } } finally { if (sr != null) { sr.Dispose(); } } } catch (Exception e) { ApplicationLog.Exception(e); throw; } return(result); }
/// <summary> /// This method expects a single XML document and returns one BlastResult. /// </summary> /// <param name="doc">A Stringbuilder containing the XML document.</param> /// <returns>The BlastResult.</returns> private static BlastResult ParseXML(StringBuilder doc) { BlastResult result = new BlastResult(); try { XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Ignore; // don't error when encountering a DTD spec // Setting the XmlResolver to null causes the DTDs specified in the XML // header to be ignored. settings.XmlResolver = null; StringReader sr = null; try { sr = new StringReader(doc.ToString()); using (XmlReader r = XmlReader.Create(sr, settings)) { string curElement = string.Empty; BlastSearchRecord curRecord = new BlastSearchRecord(); Hit curHit = null; Hsp curHsp = null; BlastStatistics curStatistics = null; BlastXmlMetadata curMetadata = null; while (r.Read()) { switch (r.NodeType) { case XmlNodeType.Element: curElement = r.Name; // ApplicationLog.WriteLine("element: " + curElement); if (curElement == "Hit") { curHit = new Hit(); } else if (curElement == "Hsp") { curHsp = new Hsp(); } else if (curElement == "Statistics") { curStatistics = new BlastStatistics(); } else if (curElement == "BlastOutput") { curMetadata = new BlastXmlMetadata(); } break; case XmlNodeType.Text: // ApplicationLog.WriteLine("text: " + r.Value); if (curElement.StartsWith("BlastOutput_", StringComparison.OrdinalIgnoreCase)) { DoBlastOutput(curElement, r.Value, curMetadata); } else if (curElement.StartsWith("Parameters_", StringComparison.OrdinalIgnoreCase)) { DoParameters(curElement, r.Value, curMetadata); } else if (curElement.StartsWith("Iteration_", StringComparison.OrdinalIgnoreCase)) { DoIteration(curElement, r.Value, curRecord); } else if (curElement.StartsWith("Statistics_", StringComparison.OrdinalIgnoreCase)) { DoStatistics(curElement, r.Value, curStatistics); } else if (curElement.StartsWith("Hit_", StringComparison.OrdinalIgnoreCase)) { DoHit(curElement, r.Value, curHit); } else if (curElement.StartsWith("Hsp_", StringComparison.OrdinalIgnoreCase)) { DoHsp(curElement, r.Value, curHsp); } else { ApplicationLog.WriteLine("BlastXMLParser Unhandled: curElement '{0}'", curElement); } break; case XmlNodeType.XmlDeclaration: // ApplicationLog.WriteLine("declaration: {0}, {1}", r.Name, r.Value); break; case XmlNodeType.ProcessingInstruction: // ApplicationLog.WriteLine("instruction: {0}, {1}", r.Name, r.Value); break; case XmlNodeType.Comment: // ApplicationLog.WriteLine("comment: " + r.Value); break; case XmlNodeType.EndElement: // ApplicationLog.WriteLine("endelement: " + r.Name); if (r.Name == "Iteration") { result.Records.Add(curRecord); curRecord = new BlastSearchRecord(); } else if (r.Name == "Statistics") { curRecord.Statistics = curStatistics; } else if (r.Name == "Hit") { curRecord.Hits.Add(curHit); } else if (r.Name == "Hsp") { curHit.Hsps.Add(curHsp); } else if (r.Name == "BlastOutput") { result.Metadata = curMetadata; } break; } } } } finally { if (sr != null) { sr.Dispose(); } } } catch (Exception e) { ApplicationLog.Exception(e); throw; } return(result); }
public GenericResponse NewBlockAnnouncement(BlockHeader header) { try { if (ApplicationState.ConsensusState != ConsensusStates.WaitingForSpeaker && ApplicationState.ConsensusState != ConsensusStates.CreatingBlock) { return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } //TODO: verify sender signature //VerifySignature(callerNode.WalletAddress); ApplicationLog.Info("Received new block"); DataServices dataServices = new DataServices(); //Validate if sender is current speaker if (callerNode.ServerAddress != ApplicationState.CurrentSpeaker.ServerAddress && callerNode.WalletAddress != ApplicationState.CurrentSpeaker.WalletAddress) { ApplicationLog.Info("Speaker Not Recognized"); return(new GenericResponse(null, ResponseCodes.SpeakerNotRecognized, ResponseMessages.SpeakerNotRecognized)); } //If first epoch, no need to validate as transactions will unlikely tally due to different start consensus time if (ApplicationState.LiveEpochCount == 1 && ApplicationState.CurrentSpeaker.ServerAddress != ApplicationState.Node.ServerAddress) { dataServices.ClearPendingTxUpToId(header.LastTransactionId); return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } //Validate block transactions with local pending transactions //Note: If somehow this node received all transactions but not in the correct order, block will be discarded //and wait for correction during re-sync in subsequent epochs if (header.Hash != dataServices.HashBlockHeaderAndTransactions(header, dataServices.GetPendingTxUpTo(header.LastTransactionId))) { //Pending Transaction And Block Mismatch ApplicationLog.Info("Pending Transaction And Block Mismatch"); return(new GenericResponse(null, ResponseCodes.PendingTransactionAndBlockMismatch, ResponseMessages.PendingTransactionAndBlockMismatch)); } //Create Block var newBlock = dataServices.CreateBlockAndClearPendingTx(header); //Attach block fee newBlock = dataServices.AttachBlockFee(newBlock, ApplicationState.CurrentSpeaker); //Add block to chain dataServices.SaveBlockToChain(newBlock); ApplicationLog.Info("New block added to chain. Index: " + header.Index); return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success)); } catch (Exception ex) { ApplicationLog.Exception(ex); return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error)); } finally { //Resume next iteration of consensus ConsensusServices consensusServices = new ConsensusServices(); consensusServices.NextEpoch(); } }