Skip to content

Commit

Permalink
Add query and transaction responses handling in client:
Browse files Browse the repository at this point in the history
- Add logger
  • Loading branch information
grimadas committed Aug 6, 2017
1 parent 0e76ac6 commit 6f9fb9b
Show file tree
Hide file tree
Showing 10 changed files with 287 additions and 49 deletions.
8 changes: 7 additions & 1 deletion iroha-cli/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,24 @@ target_link_libraries(keys_manager

add_library(client
client.cpp
impl/query_response_handler.cpp
impl/transaction_response_handler.cpp
)
target_link_libraries(client
model_converters
crypto
optional
logger
rapidjson
command_client
query_client
ametsuchi
)

target_include_directories(client PUBLIC
${PROJECT_SOURCE_DIR}/iroha-cli
)

# IrohaCli
add_executable(iroha-cli
main.cpp
Expand All @@ -51,7 +58,6 @@ target_link_libraries(iroha-cli
cli-flags_validators
bootstrap_network
rapidjson
logger
ametsuchi
model
keys_manager
Expand Down
2 changes: 1 addition & 1 deletion iroha-cli/client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ namespace iroha_cli {
CliClient::CliClient(std::string target_ip, int port)
: command_client_(target_ip, port), query_client_(target_ip, port) {}

CliClient::Status CliClient::sendTx(std::string json_tx) {
CliClient::TxStatus CliClient::sendTx(std::string json_tx) {
iroha::model::converters::JsonTransactionFactory serializer;
auto doc = iroha::model::converters::stringToJson(std::move(json_tx));
if (not doc.has_value()) {
Expand Down
4 changes: 2 additions & 2 deletions iroha-cli/client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ namespace iroha_cli {

class CliClient {
public:
enum Status { WRONG_FORMAT, NOT_VALID, OK };
enum TxStatus { WRONG_FORMAT, NOT_VALID, OK };

CliClient(std::string target_ip, int port);
/**
* Send transaction to Iroha-Network
* @param json_tx
* @return
*/
Status sendTx(std::string json_tx);
TxStatus sendTx(std::string json_tx);

iroha::protocol::QueryResponse sendQuery(std::string json_query);

Expand Down
116 changes: 116 additions & 0 deletions iroha-cli/impl/query_response_handler.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#include "query_response_handler.hpp"

using namespace iroha::protocol;
namespace iroha_cli {

QueryResponseHandler::QueryResponseHandler()
: log_(logger::log("QueryResponseHandler")) {
handler_map_[typeid(ErrorResponse)] =
&QueryResponseHandler::handleErrorResponse;
handler_map_[typeid(AccountResponse)] =
&QueryResponseHandler::handleAccountResponse;
handler_map_[typeid(AccountAssetResponse)] =
&QueryResponseHandler::handleAccountAssetsResponse;
handler_map_[typeid(TransactionsResponse)] =
&QueryResponseHandler::handleTransactionsResponse;
handler_map_[typeid(SignatoriesResponse)] =
&QueryResponseHandler::handleSignatoriesResponse;
}

void QueryResponseHandler::handle(
const iroha::protocol::QueryResponse &response) {
auto it = handler_map_.find(typeid(response));
if (it != handler_map_.end()) {
(this->*it->second)(response);
} else {
log_->error("Response Handle not Implemented");
}
}

void QueryResponseHandler::handleErrorResponse(
const iroha::protocol::QueryResponse &response) {
switch (response.error_response().reason()) {
case ErrorResponse::STATEFUL_INVALID:
log_->error("Query is stateful invalid");
break;
case ErrorResponse::STATELESS_INVALID:
log_->error("Query is stateless invalid");
break;
case ErrorResponse::NO_ACCOUNT:
log_->error("Account not found");
break;
case ErrorResponse::NO_ACCOUNT_ASSETS:
log_->error("Account assets not found");
break;
case ErrorResponse::NO_SIGNATORIES:
log_->error("No signatories found");
break;
case ErrorResponse::NOT_SUPPORTED:
log_->error("Query not supported");
break;
case ErrorResponse::WRONG_FORMAT:
log_->error("Query has wrong format");
break;
case ErrorResponse_Reason_ErrorResponse_Reason_INT_MIN_SENTINEL_DO_NOT_USE_:
break;
case ErrorResponse_Reason_ErrorResponse_Reason_INT_MAX_SENTINEL_DO_NOT_USE_:
break;
}
}

void QueryResponseHandler::handleAccountResponse(
const iroha::protocol::QueryResponse &response) {
auto account = response.account_response().account();
log_->info("[Account]:");
log_->info("-Id:- {}", account.account_id());
// TODO : print permissions
log_->info("-Domain- {}", account.domain_name());
}

void QueryResponseHandler::handleAccountAssetsResponse(
const iroha::protocol::QueryResponse &response) {
auto acc_assets = response.account_assets_response().account_asset();
log_->info("[Account Assets]");
log_->info("-Account Id- {}", acc_assets.account_id());
log_->info("-Asset Id- {}", acc_assets.asset_id());
log_->info("-Balance- {}", acc_assets.balance());
}

void QueryResponseHandler::handleSignatoriesResponse(
const iroha::protocol::QueryResponse &response) {
auto signatories = response.signatories_response().keys();
log_->info("[Signatories]");
std::for_each(
signatories.begin(), signatories.end(),
[this](auto signatory) { log_->info("-Signatory- {}", signatory); });
}

void QueryResponseHandler::handleTransactionsResponse(
const iroha::protocol::QueryResponse &response) {
auto txs = response.transactions_response().transactions();
log_->info("[Transactions]");
std::for_each(txs.begin(), txs.end(), [this](auto tx) {
log_->info("-[tx]-");
log_->info("--[Creator Id] -- {}", tx.meta().creator_account_id());
// TODO: add other fields
});
}

} // namespace iroha_cli
39 changes: 39 additions & 0 deletions iroha-cli/impl/transaction_response_handler.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "transaction_response_handler.hpp"
#include "logger/logger.hpp"

namespace iroha_cli {

void TransactionResponseHandler::handle(
const CliClient::TxStatus status) const {
switch (status) {
case iroha_cli::CliClient::OK:
log_->info("Transaction successfully sent");
break;
case iroha_cli::CliClient::WRONG_FORMAT:
log_->error("Transaction wrong json format");
break;
case iroha_cli::CliClient::NOT_VALID:
log_->error("Transaction is not valid");
break;
}
}
TransactionResponseHandler::TransactionResponseHandler()
: log_(logger::log("TransactionResponseHandler")) {}

} // namespace iroha_cli
57 changes: 20 additions & 37 deletions iroha-cli/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,29 @@
*/

#include <gflags/gflags.h>
#include <responses.pb.h>
#include <fstream>
#include <iostream>
#include <responses.pb.h>
#include "bootstrap_network.hpp"
#include "common/assert_config.hpp"
#include "genesis_block_client_impl.hpp"
#include "validators.hpp"

#include "client.hpp"
#include "impl/keys_manager_impl.hpp"
#include "logger/logger.hpp"
#include "query_response_handler.hpp"
#include "transaction_response_handler.hpp"

// ** Genesis Block and Provisioning ** //
// Reference is here (TODO: move to doc):
// https://hackmd.io/GwRmwQ2BmCFoCsAGARtOAWBIBMcAcS0GcAZjhNNPvpAKZIDGQA==

DEFINE_string(config, "", "Trusted peer's ip addresses");
//DEFINE_validator(config, &iroha_cli::validate_config);
// DEFINE_validator(config, &iroha_cli::validate_config);

DEFINE_string(genesis_block, "", "Genesis block for sending network");
//DEFINE_validator(genesis_block, &iroha_cli::validate_genesis_block);
// DEFINE_validator(genesis_block, &iroha_cli::validate_genesis_block);

DEFINE_bool(new_account, false, "Choose if account does not exist");
DEFINE_string(name, "", "Name of the account");
Expand All @@ -49,31 +52,20 @@ DEFINE_validator(torii_port, &iroha_cli::validate_port);
DEFINE_string(json_transaction, "", "Transaction in json format");
DEFINE_string(json_query, "", "Query in json format");

void print_response(iroha::protocol::QueryResponse response){
// TODO: implement beautiful output
if (response.has_error_response()){
std::cout << "Iroha returned error " << response.error_response().reason()<< std::endl;
}
if (response.has_account_response()){
auto account = response.account_response().account();
std::cout << "[Account:] " << std::endl;
std::cout << "---- AccountID: "<< account.account_id() << std::endl;
}
}
using namespace iroha::protocol;

int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
gflags::ShutDownCommandLineFlags();

auto logger = logger::log("CLI-MAIN");
if (FLAGS_new_account) {
// Create new pub/priv key
auto keysManager = iroha_cli::KeysManagerImpl(FLAGS_name);
if (not keysManager.createKeys(FLAGS_pass_phrase)) {
std::cout << "Keys already exist" << std::endl;
logger->error("Keys already exist");
} else {
std::cout
<< "Public and private key has been generated in current directory"
<< std::endl;
logger->info(
"Public and private key has been generated in current directory");
};
} else if (not FLAGS_config.empty() && not FLAGS_genesis_block.empty()) {
iroha_cli::GenesisBlockClientImpl genesis_block_client;
Expand All @@ -85,32 +77,23 @@ int main(int argc, char* argv[]) {
} else if (FLAGS_grpc) {
iroha_cli::CliClient client(FLAGS_address, FLAGS_torii_port);
if (not FLAGS_json_transaction.empty()) {
std::cout << "Send transaction to " << FLAGS_address << ":"
<< FLAGS_torii_port << std::endl;
iroha_cli::TransactionResponseHandler tx_resp_handler;
logger->info("Send transaction to {}:{} ", FLAGS_address,
FLAGS_torii_port);
std::ifstream file(FLAGS_json_transaction);
std::string str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
auto status = client.sendTx(str);
switch (status) {
case iroha_cli::CliClient::OK:
std::cout << "Transaction successfully sent" << std::endl;
break;
case iroha_cli::CliClient::WRONG_FORMAT:
std::cout << "Transaction wrong json format" << std::endl;
break;
case iroha_cli::CliClient::NOT_VALID:
std::cout << "Transaction is not valid." << std::endl;
break;
}

tx_resp_handler.handle(client.sendTx(str));
}
if (not FLAGS_json_query.empty()){
std::cout << "Send query to " << FLAGS_address << ":"
<< FLAGS_torii_port << std::endl;
if (not FLAGS_json_query.empty()) {
logger->info("Send query to {}:{}", FLAGS_address, FLAGS_torii_port);
iroha_cli::QueryResponseHandler responseHandler;
std::ifstream file(FLAGS_json_transaction);
std::string str((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
auto response = client.sendQuery(str);
print_response(response);
responseHandler.handle(response);
}

} else {
Expand Down
54 changes: 54 additions & 0 deletions iroha-cli/query_response_handler.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

#ifndef IROHA_CLI_QUERY_RESPONSE_HANDLER_HPP
#define IROHA_CLI_QUERY_RESPONSE_HANDLER_HPP
#include <typeindex>
#include <unordered_map>
#include "logger/logger.hpp"
#include "responses.pb.h"

namespace iroha_cli {
class QueryResponseHandler {
public:
QueryResponseHandler();

/**
* Handle query response
* @param response - iroha protocol
*/
void handle(const iroha::protocol::QueryResponse& response);

private:
void handleErrorResponse(const iroha::protocol::QueryResponse& response);
void handleAccountResponse(const iroha::protocol::QueryResponse& response);
void handleAccountAssetsResponse(
const iroha::protocol::QueryResponse& response);
void handleTransactionsResponse(
const iroha::protocol::QueryResponse& response);
void handleSignatoriesResponse(
const iroha::protocol::QueryResponse& response);
// -- --
using Handler =
void (QueryResponseHandler::*)(const iroha::protocol::QueryResponse&);
std::unordered_map<std::type_index, Handler> handler_map_;

std::shared_ptr<spdlog::logger> log_;
};

} // namespace iroha_cli
#endif // IROHA_QUERY_RESPONSE_HANDLER_HPP
Loading

0 comments on commit 6f9fb9b

Please sign in to comment.