hedera query get balance now working =D

This commit is contained in:
Dario 2020-09-03 12:43:32 +02:00
parent 72b4389be4
commit 43f7038af7
47 changed files with 796 additions and 176 deletions

View File

@ -12,6 +12,8 @@
#include "../controller/HederaId.h"
#include "../controller/CryptoKey.h"
#include "../lib/DataTypeConverter.h"
#include "../lib/Profiler.h"
#include "../lib/Success.h"
#include "../SingletonManager/SessionManager.h"
#include "../ServerConfig.h"
@ -37,12 +39,14 @@ void AdminHederaAccountPage::handleRequest(Poco::Net::HTTPServerRequest& request
if (_compressResponse) response.set("Content-Encoding", "gzip");
Poco::Net::HTMLForm form(request, request.stream());
#line 20 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 22 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
const char* pageName = "Hedera Account";
auto sm = SessionManager::getInstance();
auto mm = MemoryManager::getInstance();
auto user = mSession->getNewUser();
Profiler hedera_time;
std::string hedera_time_string;
Poco::URI uri(request.getURI());
auto uri_query = uri.getQueryParameters();
@ -65,7 +69,9 @@ void AdminHederaAccountPage::handleRequest(Poco::Net::HTTPServerRequest& request
if(!hedera_account.size() || hedera_account[0].isNull()) {
addError(new Error("Action Update Balance", "hedera id not found"));
} else {
hedera_time.reset();
hedera_account[0]->updateBalanceFromHedera(user, this);
addNotification(new ParamSuccess("Hedera", "crypto get balance success in ", hedera_time.string()));
}
}
}
@ -225,7 +231,7 @@ void AdminHederaAccountPage::handleRequest(Poco::Net::HTTPServerRequest& request
responseStream << "\t\t<div class=\"content\">";
// end include header_large.cpsp
responseStream << "\n";
#line 150 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 156 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( getErrorsHtml() );
responseStream << "\n";
responseStream << "<div class=\"center-form-container\">\n";
@ -242,37 +248,37 @@ void AdminHederaAccountPage::handleRequest(Poco::Net::HTTPServerRequest& request
responseStream << "\t\t\t\t<div class=\"cell header-cell c5\">Aktionen</div>\n";
responseStream << "\t\t\t</div>\n";
responseStream << "\t\t\t";
#line 164 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 171 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
for(auto it = hedera_accounts.begin(); it != hedera_accounts.end(); it++) {
auto hedera_account_model = (*it)->getModel();
auto updateUrl = ServerConfig::g_serverPath + "/hedera_account?action=updateBalance&account_id=" + std::to_string(hedera_account_model->getID());
responseStream << "\n";
responseStream << "\t\t\t\t<div class=\"row\">\n";
responseStream << "\t\t\t\t\t<div class=\"cell c2\">";
#line 169 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 176 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( (*it)->getHederaId()->getModel()->toString() );
responseStream << "</div>\n";
responseStream << "\t\t\t\t\t<div class=\"cell c3\">";
#line 170 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 177 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( hedera_account_model->getBalanceDouble() );
responseStream << " hbar</div>\n";
responseStream << "\t\t\t\t\t<div class=\"cell c2\">";
#line 171 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 178 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( model::table::HederaAccount::hederaNetworkTypeToString(hedera_account_model->getNetworkType()) );
responseStream << "</div>\n";
responseStream << "\t\t\t\t\t<div class=\"cell c3\">";
#line 172 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 179 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( hedera_account_model->getUpdatedString() );
responseStream << "</div>\n";
responseStream << "\t\t\t\t\t<button class=\"form-button\" title=\"Anfrage an Hedera, kostet etwas\" onclick=\"window.location.href='";
#line 173 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 180 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( updateUrl );
responseStream << "'\" >\n";
responseStream << "\t\t\t\t\t\tUpdate Balance\n";
responseStream << "\t\t\t\t\t</button>\n";
responseStream << "\t\t\t\t</div>\n";
responseStream << "\t\t\t";
#line 177 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 184 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
} responseStream << "\n";
responseStream << "\t\t</div>\n";
responseStream << "\t</div>\n";
@ -281,7 +287,7 @@ void AdminHederaAccountPage::handleRequest(Poco::Net::HTTPServerRequest& request
responseStream << "\t</div>\n";
responseStream << "\t<div class=\"center-form-form\">\n";
responseStream << "\t\t<form method=\"POST\" action=\"";
#line 184 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 191 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( ServerConfig::g_serverPath );
responseStream << "/hedera_account\">\n";
responseStream << "\t\t\t<label class=\"form-label\">Hedera Account ID</label>\n";
@ -295,21 +301,21 @@ void AdminHederaAccountPage::handleRequest(Poco::Net::HTTPServerRequest& request
responseStream << "\t\t\t<label class=\"form-label\" for=\"account-network-type\">Network Type</label>\n";
responseStream << "\t\t\t<select class=\"form-control\" name=\"account-network-type\" id=\"account-network-type\">\n";
responseStream << "\t\t\t";
#line 195 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 202 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
for(int i = 0; i < model::table::HEDERA_NET_COUNT; i++) { responseStream << "\n";
responseStream << "\t\t\t\t<option value=\"";
#line 196 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 203 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( i );
responseStream << "\">";
#line 196 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 203 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( model::table::HederaAccount::hederaNetworkTypeToString((model::table::HederaNetworkType)i) );
responseStream << "</option>\n";
responseStream << "\t\t\t";
#line 197 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 204 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
} responseStream << "\n";
responseStream << "\t\t\t</select>\n";
responseStream << "\t\t\t<input class=\"center-form-submit form-button\" type=\"submit\" name=\"submit\" value=\"";
#line 199 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
#line 206 "F:\\Gradido\\gradido_login_server\\src\\cpsp\\adminHederaAccount.cpsp"
responseStream << ( gettext("Add Account") );
responseStream << "\">\n";
responseStream << "\t</form>\n";

View File

@ -4,7 +4,7 @@
#include "PageRequestMessagedHandler.h"
#include "../tasks/CPUTask.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "Poco/Net/NameValueCollection.h"
@ -14,7 +14,7 @@ public:
void handleRequest(Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response);
};
class HandleElopageRequestTask : public UniLib::controller::CPUTask, protected ErrorList
class HandleElopageRequestTask : public UniLib::controller::CPUTask, protected NotificationList
{
public:
HandleElopageRequestTask(Poco::Net::NameValueCollection& requestData);

View File

@ -2,7 +2,7 @@
#define PAGE_REQUEST_MESSAGE_HANDLER_INCLUDED
#include "../model/Session.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "../lib/Profiler.h"
#include "../SingletonManager/LanguageManager.h"
@ -11,7 +11,7 @@
#include "Poco/Net/HTMLForm.h"
#include "Poco/RegularExpression.h"
class PageRequestMessagedHandler : public Poco::Net::HTTPRequestHandler, public ErrorList
class PageRequestMessagedHandler : public Poco::Net::HTTPRequestHandler, public NotificationList
{
public:
PageRequestMessagedHandler() {}

View File

@ -48,7 +48,7 @@ void JsonRequestHandler::handleRequest(Poco::Net::HTTPServerRequest& request, Po
}
Poco::Dynamic::Var JsonRequestHandler::parseJsonWithErrorPrintFile(std::istream& request_stream, ErrorList* errorHandler /* = nullptr*/, const char* functionName /* = nullptr*/)
Poco::Dynamic::Var JsonRequestHandler::parseJsonWithErrorPrintFile(std::istream& request_stream, NotificationList* errorHandler /* = nullptr*/, const char* functionName /* = nullptr*/)
{
// debugging answer

View File

@ -4,7 +4,7 @@
#include "Poco/Net/HTTPRequestHandler.h"
#include "Poco/JSON/Object.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
class JsonRequestHandler : public Poco::Net::HTTPRequestHandler
@ -15,7 +15,7 @@ public:
virtual Poco::JSON::Object* handle(Poco::Dynamic::Var params) = 0;
static Poco::Dynamic::Var parseJsonWithErrorPrintFile(std::istream& request_stream, ErrorList* errorHandler = nullptr, const char* functionName = nullptr);
static Poco::Dynamic::Var parseJsonWithErrorPrintFile(std::istream& request_stream, NotificationList* errorHandler = nullptr, const char* functionName = nullptr);
protected:
Poco::JSON::Object* mResultJson;

View File

@ -9,7 +9,7 @@
#include "../MySQL/Poco/Connector.h"
#include "Poco/Exception.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
enum ConnectionType {
CONNECTION_MYSQL_LOGIN_SERVER,
@ -17,7 +17,7 @@ enum ConnectionType {
CONNECTION_MAX
};
class ConnectionManager : public ErrorList
class ConnectionManager : public NotificationList
{
public:
~ConnectionManager();

View File

@ -4,7 +4,7 @@
#include "Poco/Net/SecureSMTPClientSession.h"
#include "Poco/Net/StringPartSource.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "../model/email/Email.h"
@ -34,19 +34,19 @@ ErrorManager::~ErrorManager()
mErrorsMap.clear();
}
void ErrorManager::addError(Error* error, bool log/* = true*/)
void ErrorManager::addError(Notification* error, bool log/* = true*/)
{
DHASH id = DRMakeStringHash(error->getFunctionName());
mWorkingMutex.lock();
auto it = mErrorsMap.find(id);
std::list<Error*>* list = nullptr;
std::list<Notification*>* list = nullptr;
//printf("[ErrorManager::addError] error with function: %s, %s\n", error->getFunctionName(), error->getMessage());
if(log) mLogging.error("[ErrorManager::addError] %s", error->getString(false));
if (it == mErrorsMap.end()) {
list = new std::list<Error *>;
mErrorsMap.insert(std::pair<DHASH, std::list<Error*>*>(id, list));
list = new std::list<Notification *>;
mErrorsMap.insert(std::pair<DHASH, std::list<Notification*>*>(id, list));
}
else {
list = it->second;
@ -62,9 +62,9 @@ void ErrorManager::addError(Error* error, bool log/* = true*/)
}
int ErrorManager::getErrors(ErrorList* send)
int ErrorManager::getErrors(NotificationList* send)
{
Error* error = nullptr;
Notification* error = nullptr;
int iCount = 0;
while (error = send->getLastError()) {
addError(error, false);

View File

@ -15,7 +15,7 @@
#include <list>
#include <map>
#include <cstring>
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "../lib/DRHash.h"
#include "../tasks/CPUTask.h"
@ -24,7 +24,7 @@
#include "Poco/Net/MailMessage.h"
class ErrorManager : public IErrorCollection
class ErrorManager : public INotificationCollection
{
public:
~ErrorManager();
@ -32,9 +32,9 @@ public:
static ErrorManager* getInstance();
// will called delete on error
virtual void addError(Error* error, bool log = true);
virtual void addError(Notification* error, bool log = true);
int getErrors(ErrorList* send);
int getErrors(NotificationList* send);
virtual void sendErrorsAsEmail();
@ -43,7 +43,7 @@ protected:
// access mutex
Poco::Mutex mWorkingMutex;
std::map<DHASH, std::list<Error*>*> mErrorsMap;
std::map<DHASH, std::list<Notification*>*> mErrorsMap;
// how many errors should be stored
// poco logging

View File

@ -170,7 +170,7 @@ Session* SessionManager::getNewSession(int* handle)
}
}
else {
ErrorList errors;
NotificationList errors;
errors.addError(new Error(functionName, "found dead locked session, keeping in memory without reference"));
errors.addError(new ParamError(functionName, "last succeeded lock:", result->getLastSucceededLock().data()));
errors.sendErrorsAsEmail();
@ -235,7 +235,7 @@ bool SessionManager::releaseSession(int requestHandleSession)
session->setActive(false);
}
else {
ErrorList errors;
NotificationList errors;
errors.addError(new Error("SessionManager::releaseSession", "found dead locked session"));
errors.sendErrorsAsEmail();
mRequestSessionMap.erase(requestHandleSession);
@ -531,7 +531,7 @@ void SessionManager::deleteLoginCookies(Poco::Net::HTTPServerRequest& request, P
//session_id = atoi(cookies.get("GRADIDO_LOGIN").data());
}
bool SessionManager::checkPwdValidation(const std::string& pwd, ErrorList* errorReciver)
bool SessionManager::checkPwdValidation(const std::string& pwd, NotificationList* errorReciver)
{
if (!isValid(pwd, VALIDATE_PASSWORD)) {
errorReciver->addError(new Error("Passwort", "Bitte gebe ein g&uuml;ltiges Password ein mit mindestens 8 Zeichen, Gro&szlig;- und Kleinbuchstaben, mindestens einer Zahl und einem Sonderzeichen (@$!%*?&+-_) ein!"));

View File

@ -69,7 +69,7 @@ public:
bool isValid(const std::string& subject, SessionValidationTypes validationType);
//! \return true if password is valid
bool checkPwdValidation(const std::string& pwd, ErrorList* errorReciver);
bool checkPwdValidation(const std::string& pwd, NotificationList* errorReciver);
void checkTimeoutSession();

View File

@ -73,7 +73,7 @@ namespace controller {
return resultVector;
}
bool HederaAccount::updateBalanceFromHedera(Poco::AutoPtr<controller::User> user, ErrorList* errorReceiver/* = nullptr*/)
bool HederaAccount::updateBalanceFromHedera(Poco::AutoPtr<controller::User> user, NotificationList* errorReceiver/* = nullptr*/)
{
static const char* functionName = "HederaAccount::updateBalanceFromHedera";
@ -86,27 +86,45 @@ namespace controller {
auto hedera_node = NodeServer::pick(account_model->networkTypeToNodeServerType(account_model->getNetworkType()));
auto crypto_key = controller::CryptoKey::load(account_model->getCryptoKeyId());
if (crypto_key.isNull()) {
printf("[%s] error, crypto key with id: %d not found\n", functionName, account_model->getCryptoKeyId());
if (errorReceiver) { errorReceiver->addError(new Error("Keys", "could not found crypto key for account"));}
else { printf("[%s] error, crypto key with id: %d not found\n", functionName, account_model->getCryptoKeyId()); }
return false;
}
auto hedera_key_pair = crypto_key->getKeyPair(user);
if (!hedera_key_pair) {
if (errorReceiver) { errorReceiver->addError(new Error("Keys", "error decrypting private key"));}
printf("[%s] error decrypting private key with id: %d, with user: %d\n", functionName, account_model->getCryptoKeyId(), user->getModel()->getID());
return false;
}
auto query = model::hedera::Query::getBalance(mHederaID, hedera_node);
if (!query) {
printf("[%s] error creating query\n", functionName);
}
query->sign(std::move(hedera_key_pair));
HederaRequest request;
model::hedera::Response response;
try {
request.request(query);
if (HEDERA_REQUEST_RETURN_OK == request.request(query, &response) && proto::OK == response.getResponseCode()) {
account_model->updateIntoDB("balance", response.getAccountBalance());
}
else {
if (errorReceiver) {
errorReceiver->addError(new Error("Hedera", "Hedera request failed"));
errorReceiver->addError(new ParamError("Hedera", "Hedera Response Code", proto::ResponseCodeEnum_Name(response.getResponseCode())));
}
else {
printf("[%s] hedera response code: %s\n", functionName, proto::ResponseCodeEnum_Name(response.getResponseCode()).data());
}
}
//request.requestViaPHPRelay(query);
}
catch (Poco::Exception& ex) {
printf("[HederaAccount::updateBalanceFromHedera] exception calling hedera request: %s\n", ex.displayText().data());
}
if (errorReceiver) {
errorReceiver->getErrors(&request);
}

View File

@ -27,7 +27,7 @@ namespace controller {
inline void setHederaId(Poco::AutoPtr<controller::HederaId> hederaId) { mHederaID = hederaId; }
inline Poco::AutoPtr<controller::HederaId> getHederaId() { return mHederaID; }
bool updateBalanceFromHedera(Poco::AutoPtr<controller::User> user, ErrorList* errorReceiver = nullptr);
bool updateBalanceFromHedera(Poco::AutoPtr<controller::User> user, NotificationList* errorReceiver = nullptr);
protected:
HederaAccount(model::table::HederaAccount* dbModel);

View File

@ -9,6 +9,7 @@
#include <grpcpp/create_channel.h>
#include <chrono>
HederaRequest::HederaRequest()
{
@ -19,29 +20,62 @@ HederaRequest::~HederaRequest()
}
HederaRequestReturn HederaRequest::request(model::hedera::Query* query)
HederaRequestReturn HederaRequest::request(model::hedera::Query* query, model::hedera::Response* response, Poco::UInt64 fee/* = 0*/)
{
auto channel = grpc::CreateChannel(query->getConnectionString(), grpc::InsecureChannelCredentials());
grpc::ClientContext context;
std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() +
std::chrono::milliseconds(10000);
std::chrono::milliseconds(5000);
context.set_deadline(deadline);
grpc::CompletionQueue cq;
//grpc::CompletionQueue cq;
auto proto_query = query->getProtoQuery();
auto proto_query_serialized = proto_query->SerializeAsString();
auto query_hex_string = DataTypeConverter::binToHex((unsigned char*)proto_query_serialized.data(), proto_query_serialized.size());
printf("[HederaRequest::request] query as hex: %s\n", query_hex_string.data());
proto::Response* response = nullptr;
//auto query_hex_string = DataTypeConverter::binToHex((unsigned char*)proto_query_serialized.data(), proto_query_serialized.size());
//printf("[HederaRequest::request] query as hex: %s\n", query_hex_string.data());
auto proto_response = response->getResponsePtr();
auto connect_string = query->getConnectionString();
if (proto_query->has_cryptogetaccountbalance()) {
auto stub = proto::CryptoService::NewStub(channel);
auto connect_string = query->getConnectionString();
printf("try connection to hedera with: %s\n", connect_string.data());
//auto stream = stub->PrepareAsynccryptoGetBalance(&context, *proto_query, &cq);
auto status = stub->cryptoGetBalance(&context, *proto_query, response);
//stream->StartCall();
addError(new ParamError("Hedera Request", "crypto get balance", status.error_message()));
printf("[HederaRequest::request] error details: %s\n", status.error_details().data());
auto stub = proto::CryptoService::NewStub(channel);
// crypto account get balance currently hasn't fees
query->setResponseType(proto::ANSWER_ONLY);
auto status = stub->cryptoGetBalance(&context, *proto_query, proto_response);
if (status.ok()) {
return HEDERA_REQUEST_RETURN_OK;
}
else {
addError(new ParamError("Hedera Request", "crypto get balance error message:", status.error_message()));
addError(new ParamError("Hedera Request", "details: ", status.error_details()));
return HEDERA_REQUEST_RETURN_ERROR;
}
}
return HEDERA_REQUEST_RETURN_OK;
}
#include "Poco/JSON/Object.h"
#include "../lib/JsonRequest.h"
HederaRequestReturn HederaRequest::requestViaPHPRelay(model::hedera::Query* query)
{
JsonRequest phpRelay("***REMOVED***", 88);
Poco::Net::NameValueCollection parameters;
std::string query_string = query->getProtoQuery()->SerializeAsString();
//auto query_base64 = DataTypeConverter::binToBase64((const unsigned char*)query_string.data(), query_string.size(), sodium_base64_VARIANT_URLSAFE_NO_PADDING);
//auto findPos = query_string.find_first_of("\u");
auto query_hex = DataTypeConverter::binToHex((const unsigned char*)query_string.data(), query_string.size());
parameters.set("content", query_hex.substr(0, query_hex.size()-1));
parameters.set("server", query->getConnectionString());
parameters.set("method", "getBalance");
parameters.set("service", "crypto");
phpRelay.requestGRPCRelay(parameters);
//phpRelay.request("")
return HEDERA_REQUEST_RETURN_OK;
}

View File

@ -12,6 +12,8 @@
#include "../controller/NodeServer.h"
#include "../model/hedera/Query.h"
#include "../model/hedera/Transaction.h"
#include "../model/hedera/Response.h"
enum HederaRequestReturn
{
@ -22,13 +24,15 @@ enum HederaRequestReturn
};
// NodeServerConnection
class HederaRequest : public ErrorList
class HederaRequest : public NotificationList
{
public:
HederaRequest();
~HederaRequest();
HederaRequestReturn request(model::hedera::Query* query);
HederaRequestReturn request(model::hedera::Query* query, model::hedera::Response* response, Poco::UInt64 fee = 0);
//! for testing, didn't work server say invalid json :/
HederaRequestReturn requestViaPHPRelay(model::hedera::Query* query);
protected:

View File

@ -138,18 +138,17 @@ namespace DataTypeConverter
}
std::string binToBase64(const MemoryBin* data)
std::string binToBase64(const unsigned char* data, size_t size, int variant /*= sodium_base64_VARIANT_ORIGINAL*/)
{
auto mm = MemoryManager::getInstance();
size_t binSize = data->size();
size_t encodedSize = sodium_base64_encoded_len(binSize, sodium_base64_VARIANT_ORIGINAL);
size_t encodedSize = sodium_base64_encoded_len(size, variant);
auto base64 = mm->getFreeMemory(encodedSize);
memset(*base64, 0, encodedSize);
size_t resultBinSize = 0;
if (0 != sodium_bin2base64(*base64, encodedSize, *data, binSize, sodium_base64_VARIANT_ORIGINAL)) {
if (nullptr == sodium_bin2base64(*base64, encodedSize, data, size, variant)) {
mm->releaseMemory(base64);
return "";
}

View File

@ -9,6 +9,8 @@
#include "Poco/Data/LOB.h"
#include "../SingletonManager/LanguageManager.h"
#include "sodium.h"
namespace DataTypeConverter {
enum NumberParseState
@ -25,8 +27,9 @@ namespace DataTypeConverter {
MemoryBin* hexToBin(const std::string& hexString);
MemoryBin* base64ToBin(const std::string& base64String);
std::string binToBase64(const MemoryBin* data);
std::string binToBase64(const unsigned char* data, size_t size, int variant = sodium_base64_VARIANT_ORIGINAL);
inline std::string binToBase64(const MemoryBin* data, int variant = sodium_base64_VARIANT_ORIGINAL) { return binToBase64(data->data(), data->size(), variant); }
std::string binToHex(const unsigned char* data, size_t size);
std::string binToHex(const Poco::Nullable<Poco::Data::BLOB>& nullableBin);

View File

@ -2,7 +2,7 @@
Error::Error(const char* functionName, const char* message)
: mFunctionName(functionName), mMessage(message)
: Notification(functionName, message)
{
}
@ -12,7 +12,7 @@ Error::~Error()
}
std::string Error::getString(bool withNewline/* = true*/)
std::string Error::getString(bool withNewline/* = true*/) const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage;
@ -20,7 +20,7 @@ std::string Error::getString(bool withNewline/* = true*/)
return ss.str();
}
std::string Error::getHtmlString()
std::string Error::getHtmlString() const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage;
@ -28,7 +28,7 @@ std::string Error::getHtmlString()
return ss.str();
}
std::string ParamError::getString(bool withNewline/* = true*/)
std::string ParamError::getString(bool withNewline/* = true*/) const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage << " " << mParam;
@ -36,7 +36,7 @@ std::string ParamError::getString(bool withNewline/* = true*/)
return ss.str();
}
std::string ParamError::getHtmlString()
std::string ParamError::getHtmlString() const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage << " " << mParam << std::endl;

View File

@ -10,23 +10,24 @@
#ifndef DR_LUA_WEB_MODULE_ERROR_ERROR_H
#define DR_LUA_WEB_MODULE_ERROR_ERROR_H
#include <string>
#include "Notification.h"
#include <sstream>
class Error
class Error : public Notification
{
public:
Error(const char* functionName, const char* message);
~Error();
const char* getFunctionName() { return mFunctionName.data(); }
const char* getMessage() { return mMessage.data(); }
virtual std::string getString(bool withNewline = true);
virtual std::string getHtmlString();
virtual std::string getString(bool withNewline = true) const;
virtual std::string getHtmlString() const;
virtual bool isError() { return true; }
protected:
std::string mFunctionName;
std::string mMessage;
};
class ParamError : public Error
@ -44,18 +45,18 @@ public:
mParam = ss.str();
}
virtual std::string getString(bool withNewline = true);
virtual std::string getHtmlString();
virtual std::string getString(bool withNewline = true) const;
virtual std::string getHtmlString() const;
protected:
std::string mParam;
};
class IErrorCollection
class INotificationCollection
{
public:
virtual void addError(Error*, bool log = true) = 0;
virtual void addError(Notification*, bool log = true) = 0;
};
#endif // DR_LUA_WEB_MODULE_ERROR_ERROR_H

View File

@ -37,7 +37,6 @@ JsonRequestReturn JsonRequest::request(const char* methodName, const Poco::Net::
try {
Profiler phpRequestTime;
Poco::Net::HTTPSClientSession httpsClientSession(mServerHost, mServerPort);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/JsonRequestHandler");
request.setChunkedTransferEncoding(true);
@ -99,5 +98,95 @@ JsonRequestReturn JsonRequest::request(const char* methodName, const Poco::Net::
return JSON_REQUEST_CONNECT_ERROR;
}
return JSON_REQUEST_RETURN_OK;
}
#include "Poco/JSON/Stringifier.h"
JsonRequestReturn JsonRequest::requestGRPCRelay(const Poco::Net::NameValueCollection& payload)
{
static const char* functionName = "JsonRequest::requestGRPCRelay";
Poco::JSON::Object requestJson;
for (auto it = payload.begin(); it != payload.end(); it++) {
requestJson.set(it->first, it->second);
}
// send post request via https
// 443 = HTTPS Default
// TODO: adding port into ServerConfig
try {
Profiler phpRequestTime;
Poco::Net::HTTPClientSession httpClientSession(mServerHost, mServerPort);
Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_POST, "/hedera_rpc_relay/gRPCProxy.php");
request.setChunkedTransferEncoding(false);
std::ostream& requestStream = httpClientSession.sendRequest(request);
requestJson.stringify(requestStream);
std::stringstream ss;
requestJson.stringify(ss);
auto f = fopen("grpc.txt", "wt");
std::string grpc = ss.str();
fwrite(grpc.data(), grpc.size(), 1, f);
fclose(f);
Poco::Net::HTTPResponse response;
std::istream& request_stream = httpClientSession.receiveResponse(response);
// debugging answer
std::stringstream responseStringStream;
for (std::string line; std::getline(request_stream, line); ) {
responseStringStream << line << std::endl;
}
Poco::Logger& speedLog = Poco::Logger::get("SpeedLog");
speedLog.information("[gRPC relay] php server time: %s", phpRequestTime.string());
// extract parameter from request
Poco::JSON::Parser jsonParser;
Poco::Dynamic::Var parsedJson;
try {
parsedJson = jsonParser.parse(responseStringStream.str());
}
catch (Poco::Exception& ex) {
addError(new ParamError(functionName, "error parsing request answer grpc relay", ex.displayText().data()));
std::string fileName = "response_grpc_";
fileName += ".html";
FILE* f = fopen(fileName.data(), "wt");
std::string responseString = responseStringStream.str();
fwrite(responseString.data(), 1, responseString.size(), f);
fclose(f);
// */
sendErrorsAsEmail(responseStringStream.str());
return JSON_REQUEST_RETURN_PARSE_ERROR;
}
Poco::JSON::Object object = *parsedJson.extract<Poco::JSON::Object::Ptr>();
auto state = object.get("state");
std::string stateString = state.convert<std::string>();
if (stateString == "error") {
addError(new Error(functionName, "php server return error"));
if (!object.isNull("msg")) {
addError(new ParamError(functionName, "msg:", object.get("msg").convert<std::string>().data()));
}
if (!object.isNull("details")) {
addError(new ParamError(functionName, "details:", object.get("details").convert<std::string>().data()));
}
sendErrorsAsEmail();
return JSON_REQUEST_RETURN_ERROR;
}
ss.clear();
Poco::JSON::Stringifier::stringify(object, ss);
printf("json request result: %s\n", ss.str().data());
}
catch (Poco::Exception& e) {
addError(new ParamError(functionName, "connect error to php server", e.displayText().data()));
sendErrorsAsEmail();
return JSON_REQUEST_CONNECT_ERROR;
}
return JSON_REQUEST_RETURN_OK;
}

View File

@ -8,7 +8,7 @@
*
*/
#include "ErrorList.h"
#include "NotificationList.h"
#include "Poco/Net/NameValueCollection.h"
#ifndef __GRADIDO_LOGIN_SERVER_LIB_JSON_REQUEST_
@ -22,17 +22,19 @@ enum JsonRequestReturn
JSON_REQUEST_CONNECT_ERROR
};
class JsonRequest : public ErrorList
class JsonRequest : public NotificationList
{
public:
JsonRequest(const std::string& serverHost, int serverPort);
~JsonRequest();
JsonRequestReturn request(const char* methodName, const Poco::Net::NameValueCollection& payload);
JsonRequestReturn requestGRPCRelay(const Poco::Net::NameValueCollection& payload);
protected:
int mServerPort;
std::string mServerHost;
};

View File

@ -1,5 +1,5 @@
#include "MultithreadContainer.h"
#include "ErrorList.h"
#include "NotificationList.h"
namespace UniLib {
namespace lib {
@ -14,7 +14,7 @@ namespace UniLib {
}
}
catch (Poco::TimeoutException& ex) {
ErrorList errors;
NotificationList errors;
errors.addError(new ParamError(functionName, "lock timeout", ex.displayText()));
if (mLastSucceededLock != "") {
errors.addError(new ParamError(functionName, "last succeed lock by ", mLastSucceededLock.data()));

View File

@ -0,0 +1,7 @@
#include "Notification.h"
Notification::Notification(const char* functionName, const char* message)
: mFunctionName(functionName), mMessage(message)
{
}

View File

@ -0,0 +1,24 @@
#ifndef GRADIDO_LOGIN_SERVER_LIB_NOTIFICATION_H
#define GRADIDO_LOGIN_SERVER_LIB_NOTIFICATION_H
#include <string>
class Notification
{
public:
Notification(const char* functionName, const char* message);
const char* getFunctionName() { return mFunctionName.data(); }
const char* getMessage() { return mMessage.data(); }
virtual std::string getString(bool withNewline = true) const = 0;
virtual std::string getHtmlString() const = 0;
virtual bool isError() { return false; }
virtual bool isSuccess() { return false; }
protected:
std::string mFunctionName;
std::string mMessage;
};
#endif //GRADIDO_LOGIN_SERVER_LIB_NOTIFICATION_H

View File

@ -1,4 +1,4 @@
#include "ErrorList.h"
#include "NotificationList.h"
#include "../ServerConfig.h"
@ -42,13 +42,13 @@ int SendErrorMessage::run()
// ------------------------------------------------------------------------------------
ErrorList::ErrorList()
NotificationList::NotificationList()
: mLogging(Poco::Logger::get("errorLog"))
{
}
ErrorList::~ErrorList()
NotificationList::~NotificationList()
{
while (mErrorStack.size() > 0) {
delete mErrorStack.top();
@ -56,7 +56,7 @@ ErrorList::~ErrorList()
}
}
void ErrorList::addError(Error* error, bool log/* = true */)
void NotificationList::addError(Notification* error, bool log/* = true */)
{
if (log) {
@ -67,13 +67,18 @@ void ErrorList::addError(Error* error, bool log/* = true */)
mErrorStack.push(error);
}
Error* ErrorList::getLastError()
void NotificationList::addNotification(Notification* notification)
{
mErrorStack.push(notification);
}
Notification* NotificationList::getLastError()
{
if (mErrorStack.size() == 0) {
return nullptr;
}
Error* error = mErrorStack.top();
Notification* error = mErrorStack.top();
if (error) {
mErrorStack.pop();
}
@ -81,7 +86,7 @@ Error* ErrorList::getLastError()
return error;
}
void ErrorList::clearErrors()
void NotificationList::clearErrors()
{
while (mErrorStack.size()) {
auto error = mErrorStack.top();
@ -93,9 +98,9 @@ void ErrorList::clearErrors()
}
int ErrorList::getErrors(ErrorList* send)
int NotificationList::getErrors(NotificationList* send)
{
Error* error = nullptr;
Notification* error = nullptr;
int iCount = 0;
while (error = send->getLastError()) {
addError(error, false);
@ -104,7 +109,7 @@ int ErrorList::getErrors(ErrorList* send)
return iCount;
}
void ErrorList::printErrors()
void NotificationList::printErrors()
{
while (mErrorStack.size() > 0) {
auto error = mErrorStack.top();
@ -114,14 +119,19 @@ void ErrorList::printErrors()
}
}
std::string ErrorList::getErrorsHtml()
std::string NotificationList::getErrorsHtml()
{
std::string res;
res = "<ul class='grd-no-style'>";
while (mErrorStack.size() > 0) {
auto error = mErrorStack.top();
mErrorStack.pop();
res += "<li class='grd-error'>";
if (error->isError()) {
res += "<li class='grd-error'>";
}
else if (error->isSuccess()) {
res += "<li class='grd-success'>";
}
res += error->getHtmlString();
res += "</li>";
delete error;
@ -130,15 +140,20 @@ std::string ErrorList::getErrorsHtml()
return res;
}
std::string ErrorList::getErrorsHtmlNewFormat()
std::string NotificationList::getErrorsHtmlNewFormat()
{
std::string html;
while (mErrorStack.size() > 0) {
auto error = std::unique_ptr<Error>(mErrorStack.top());
auto error = std::unique_ptr<Notification>(mErrorStack.top());
mErrorStack.pop();
html += "<div class=\"alert alert-error\" role=\"alert\">";
html += "<i class=\"material-icons-outlined\">report_problem</i>";
if (error->isError()) {
html += "<div class=\"alert alert-error\" role=\"alert\">";
html += "<i class=\"material-icons-outlined\">report_problem</i>";
}
else if (error->isSuccess()) {
html += "<div class=\"alert alert-success\" role=\"alert\">";
}
html += "<span>";
html += error->getHtmlString();
html += "</span>";
@ -154,7 +169,7 @@ std::string ErrorList::getErrorsHtmlNewFormat()
*/
void ErrorList::sendErrorsAsEmail(std::string rawHtml/* = ""*/)
void NotificationList::sendErrorsAsEmail(std::string rawHtml/* = ""*/)
{
auto em = EmailManager::getInstance();
/*auto message = new Poco::Net::MailMessage();

View File

@ -19,27 +19,28 @@
#include "Poco/Net/StringPartSource.h"
#include "Poco/Logger.h"
class ErrorList : public IErrorCollection
class NotificationList : public INotificationCollection
{
public:
ErrorList();
~ErrorList();
NotificationList();
~NotificationList();
// push error, error will be deleted in deconstructor
virtual void addError(Error* error, bool log = true);
virtual void addError(Notification* error, bool log = true);
void addNotification(Notification* notification);
// return error on top of stack, please delete after using
Error* getLastError();
Notification* getLastError();
inline size_t errorCount() { return mErrorStack.size(); }
// delete all errors
void clearErrors();
static int moveErrors(ErrorList* recv, ErrorList* send) {
static int moveErrors(NotificationList* recv, NotificationList* send) {
return recv->getErrors(send);
}
int getErrors(ErrorList* send);
int getErrors(NotificationList* send);
void printErrors();
std::string getErrorsHtml();
@ -48,7 +49,7 @@ public:
void sendErrorsAsEmail(std::string rawHtml = "");
protected:
std::stack<Error*> mErrorStack;
std::stack<Notification*> mErrorStack;
// poco logging
Poco::Logger& mLogging;
};

52
src/cpp/lib/Success.cpp Normal file
View File

@ -0,0 +1,52 @@
#include "Success.h"
#include <sstream>
Success::Success(const char* functionName, const char* message)
: Notification(functionName, message)
{
}
std::string Success::getString(bool withNewline/* = true*/) const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage;
if (withNewline) ss << std::endl;
return ss.str();
}
std::string Success::getHtmlString() const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage;
return ss.str();
}
ParamSuccess::ParamSuccess(const char* functionName, const char* message, std::string param)
: Success(functionName, message), mParam(param)
{
}
ParamSuccess::ParamSuccess(const char* functionName, const char* message, int param)
: Success(functionName, message), mParam(std::to_string(param))
{
}
std::string ParamSuccess::getString(bool withNewline/* = true*/) const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage << " " << mParam;
if (withNewline) ss << std::endl;
return ss.str();
}
std::string ParamSuccess::getHtmlString() const
{
std::stringstream ss;
ss << mFunctionName << ": " << mMessage << " " << mParam;
return ss.str();
}

30
src/cpp/lib/Success.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef GRADIDO_LOGIN_SERVER_LIB_SUCCESS_H
#define GRADIDO_LOGIN_SERVER_LIB_SUCCESS_H
#include "Notification.h"
class Success : public Notification
{
public:
Success(const char* functionName, const char* message);
std::string getString(bool withNewline = true) const;
std::string getHtmlString() const;
virtual bool isSuccess() { return true; }
};
class ParamSuccess : public Success
{
public:
ParamSuccess(const char* functionName, const char* message, std::string param);
ParamSuccess(const char* functionName, const char* message, int param);
std::string getString(bool withNewline = true) const;
std::string getHtmlString() const;
protected:
std::string mParam;
};
#endif //GRADIDO_LOGIN_SERVER_LIB_SUCCESS_H

View File

@ -10,7 +10,7 @@
#ifndef DR_LUA_WEB_MODULE_SESSION_SESSION_H
#define DR_LUA_WEB_MODULE_SESSION_SESSION_H
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "User.h"
#include "../controller/User.h"
@ -54,7 +54,7 @@ class UpdateUserPasswordPage;
class PassphrasePage;
class RepairDefectPassphrase;
class Session : public ErrorList, public UniLib::lib::MultithreadContainer
class Session : public NotificationList, public UniLib::lib::MultithreadContainer
{
friend WriteEmailVerification;
friend SessionManager;

View File

@ -11,11 +11,11 @@
#pragma warning(disable:4800)
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "../proto/gradido/BasicTypes.pb.h"
#include "../SingletonManager/MemoryManager.h"
class TransactionBase : public ErrorList, public UniLib::lib::MultithreadContainer
class TransactionBase : public NotificationList, public UniLib::lib::MultithreadContainer
{
public:
TransactionBase(const std::string& memo);

View File

@ -732,7 +732,7 @@ void User::setEmailChecked()
unlock();
}
bool User::validatePwd(const std::string& pwd, ErrorList* validationErrorsToPrint)
bool User::validatePwd(const std::string& pwd, NotificationList* validationErrorsToPrint)
{
auto mm = MemoryManager::getInstance();
auto cmpCryptoKey = createCryptoKey(pwd);
@ -935,7 +935,7 @@ MemoryBin* User::createCryptoKey(const std::string& password)
return key;
}
User::passwordHashed User::createPasswordHashed(MemoryBin* cryptoKey, ErrorList* errorReceiver/* = nullptr*/)
User::passwordHashed User::createPasswordHashed(MemoryBin* cryptoKey, NotificationList* errorReceiver/* = nullptr*/)
{
if (sizeof(User::passwordHashed) != crypto_shorthash_BYTES) {
throw Poco::Exception("crypto_shorthash_BYTES != sizeof(User::passwordHashed)");

View File

@ -4,7 +4,7 @@
#include "../Crypto/KeyPair.h"
#include <string>
//#include "ModelBase.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "Poco/Thread.h"
#include "Poco/Types.h"
@ -50,7 +50,7 @@ enum UserFields
USER_FIELDS_LANGUAGE
};
class User : public ErrorList
class User : public NotificationList
{
friend UserCreateCryptoKey;
friend UserWriteIntoDB;
@ -115,7 +115,7 @@ public:
bool isEmptyPassword();
//bool setNewPassword(const std::string& newPassword);
bool updatePassword(const std::string& newPassword, const std::string& passphrase, Poco::AutoPtr<controller::User> newUser);
bool validatePwd(const std::string& pwd, ErrorList* validationErrorsToPrint);
bool validatePwd(const std::string& pwd, NotificationList* validationErrorsToPrint);
bool validateIdentHash(HASH hash);
MemoryBin* encrypt(const MemoryBin* data);
@ -134,7 +134,7 @@ protected:
typedef Poco::UInt64 passwordHashed;
MemoryBin* createCryptoKey(const std::string& password);
static passwordHashed createPasswordHashed(MemoryBin* cryptoKey, ErrorList* errorReceiver = nullptr);
static passwordHashed createPasswordHashed(MemoryBin* cryptoKey, NotificationList* errorReceiver = nullptr);
inline void setCryptoKey(MemoryBin* cryptoKey) { lock(); mCryptoKey = cryptoKey; unlock(); }
//void detectState();

View File

@ -17,7 +17,7 @@
#include "../../SingletonManager/LanguageManager.h"
#include "../../lib/ErrorList.h"
#include "../../lib/NotificationList.h"
namespace model {
using namespace Poco;
@ -39,7 +39,7 @@ namespace model {
EMAIL_MAX
};
class Email: public ErrorList
class Email: public NotificationList
{
public:
Email(AutoPtr<controller::EmailVerificationCode> emailVerification, AutoPtr<controller::User> user, EmailType type);

View File

@ -0,0 +1,53 @@
#include "CryptoTransferTransaction.h"
namespace model {
namespace hedera {
CryptoTransferTransaction::CryptoTransferTransaction()
: mCryptoTransfer(nullptr)
{
mCryptoTransfer = new proto::CryptoTransferTransactionBody;
}
CryptoTransferTransaction::~CryptoTransferTransaction()
{
if (mCryptoTransfer) {
delete mCryptoTransfer;
mCryptoTransfer = nullptr;
}
}
void CryptoTransferTransaction::addSender(Poco::AutoPtr<controller::HederaId> senderAccountId, Poco::UInt64 amountTinybars)
{
auto transfers = mCryptoTransfer->mutable_transfers();
auto accountAmounts = transfers->add_accountamounts();
accountAmounts->set_amount(-(Poco::Int64)amountTinybars);
senderAccountId->copyToProtoAccountId(accountAmounts->mutable_accountid());
}
void CryptoTransferTransaction::addReceiver(Poco::AutoPtr<controller::HederaId> receiverAccountId, Poco::UInt64 amountTinybars)
{
auto transfers = mCryptoTransfer->mutable_transfers();
auto accountAmounts = transfers->add_accountamounts();
accountAmounts->set_amount(amountTinybars);
receiverAccountId->copyToProtoAccountId(accountAmounts->mutable_accountid());
}
bool CryptoTransferTransaction::validate()
{
auto transfers = mCryptoTransfer->mutable_transfers();
auto account_amounts = transfers->accountamounts();
Poco::Int64 sum = 0;
for (int i = 0; i < transfers->accountamounts_size(); i++) {
auto account_amount = account_amounts.Mutable(i);
sum += account_amount->amount();
}
return 0 == sum && transfers->accountamounts_size() > 0;
}
void CryptoTransferTransaction::resetPointer()
{
mCryptoTransfer = nullptr;
}
}
}

View File

@ -0,0 +1,40 @@
#ifndef _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_CRYPTO_TRANSFER_TRANSACTION_H
#define _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_CRYPTO_TRANSFER_TRANSACTION_H
/*!
* @author: Dario Rekowski
*
* @date: 02.09.20
*
* @brief: class for creating a hedera transfer transaction
*
*/
#include "../../proto/hedera/CryptoTransfer.pb.h"
#include "../../controller/HederaId.h"
namespace model {
namespace hedera {
class CryptoTransferTransaction
{
public:
CryptoTransferTransaction();
~CryptoTransferTransaction();
void addSender(Poco::AutoPtr<controller::HederaId> senderAccountId, Poco::UInt64 amountTinybars);
void addReceiver(Poco::AutoPtr<controller::HederaId> receiverAccountId, Poco::UInt64 amountTinybars);
bool validate();
// set pointer to zero, after hand over pointer to transaction body
void resetPointer();
inline proto::CryptoTransferTransactionBody* getProtoTransactionBody() { return mCryptoTransfer; }
protected:
proto::CryptoTransferTransactionBody* mCryptoTransfer;
};
}
}
#endif //_GRADIDO_LOGIN_SERVER_MODEL_HEDERA_CRYPTO_TRANSFER_TRANSACTION_H

View File

@ -2,18 +2,24 @@
#include "Poco/Timestamp.h"
#include "../../SingletonManager/MemoryManager.h"
#include "Transaction.h"
#include "TransactionBody.h"
#include "CryptoTransferTransaction.h"
namespace model {
namespace hedera {
Query::Query(const controller::NodeServerConnection& connection)
: mConnection(connection)
: mConnection(connection), mTransactionBody(nullptr)
{
}
Query::~Query()
{
if (mTransactionBody) {
delete mTransactionBody;
}
}
Query* Query::getBalance(Poco::AutoPtr<controller::HederaId> accountId, const controller::NodeServerConnection& connection)
@ -26,58 +32,46 @@ namespace model {
accountId->copyToProtoAccountId(get_account_balance->mutable_accountid());
auto query_header = get_account_balance->mutable_header();
query_header->set_responsetype(proto::COST_ANSWER);
auto transaction = query_header->mutable_payment();
query->mTransactionBody = new TransactionBody(accountId, connection);
CryptoTransferTransaction crypto_transaction;
crypto_transaction.addSender(accountId, 0);
crypto_transaction.addReceiver(connection.hederaId, 0);
query->mTransactionBody->setCryptoTransfer(crypto_transaction);
//auto transaction = query_header->mutable_payment();
//auto transaction_body = transaction->mutable_body();
// body content
// transaction id
auto transaction_id = query->mTransactionBody.mutable_transactionid();
auto timestamp = transaction_id->mutable_transactionvalidstart();
Poco::Timestamp now;
auto microseconds = now.epochMicroseconds() - now.epochTime() * now.resolution(); // 1*10^6
timestamp->set_seconds(now.epochTime());
timestamp->set_nanos(microseconds * 1000);
accountId->copyToProtoAccountId(transaction_id->mutable_accountid());
//
// sdk default, but can be changed
query->mTransactionBody.set_transactionfee(100000000);
auto valid_duration = query->mTransactionBody.mutable_transactionvalidduration();
// maximal 2 minutes
valid_duration->set_seconds(120);
auto crypto_transfer = query->mTransactionBody.mutable_cryptotransfer();
auto transfer_list = crypto_transfer->mutable_transfers();
auto account_amounts = transfer_list->mutable_accountamounts();
account_amounts->Add();
auto account_amount = account_amounts->Mutable(0);
account_amount->set_amount(1000);
connection.hederaId->copyToProtoAccountId(account_amount->mutable_accountid());
// node account id
return query;
}
bool Query::sign(std::unique_ptr<KeyPairHedera> keyPairHedera)
{
auto mm = MemoryManager::getInstance();
auto body_bytes = mTransactionBody.SerializeAsString();
auto transaction = mQueryProto.mutable_cryptogetaccountbalance()->mutable_header()->mutable_payment();
transaction->set_bodybytes(body_bytes.data());
auto signature_map = transaction->mutable_sigmap();
auto signature_pairs = signature_map->mutable_sigpair();
signature_pairs->Add();
auto signature_pair = signature_pairs->Mutable(0);
auto public_key = keyPairHedera->getPublicKey();
Transaction transaction;
auto sign_result = transaction.sign(std::move(keyPairHedera), mTransactionBody);
auto query_header = mQueryProto.mutable_cryptogetaccountbalance()->mutable_header();
query_header->set_allocated_payment(transaction.getTransaction());
transaction.resetPointer();
auto sign = keyPairHedera->sign(body_bytes);
if (!sign) {
printf("[Query::sign] error signing message\n");
return false;
}
signature_pair->set_pubkeyprefix(public_key, keyPairHedera->getPublicKeySize());
signature_pair->set_ed25519(*sign, sign->size());
return sign_result;
}
mm->releaseMemory(sign);
void Query::setResponseType(proto::ResponseType type)
{
auto get_account_balance = mQueryProto.mutable_cryptogetaccountbalance();
auto query_header = get_account_balance->mutable_header();
query_header->set_responsetype(type);
return true;
}
proto::ResponseType Query::getResponseType()
{
auto get_account_balance = mQueryProto.mutable_cryptogetaccountbalance();
auto query_header = get_account_balance->mutable_header();
return query_header->responsetype();
}
}
}

View File

@ -13,6 +13,7 @@
#include "../../proto/hedera/Query.pb.h"
#include "../../controller/NodeServer.h"
#include "../../Crypto/KeyPairHedera.h"
#include "TransactionBody.h"
namespace model {
namespace hedera {
@ -23,13 +24,16 @@ namespace model {
static Query* getBalance(Poco::AutoPtr<controller::HederaId> accountId, const controller::NodeServerConnection& connection);
bool sign(std::unique_ptr<KeyPairHedera> keyPairHedera);
void setResponseType(proto::ResponseType type);
proto::ResponseType getResponseType();
void setFee(Poco::UInt64 fee);
inline const proto::Query* getProtoQuery() const { return &mQueryProto; }
inline std::string getConnectionString() const { return mConnection.getUriWithPort(); }
protected:
Query(const controller::NodeServerConnection& connection);
proto::Query mQueryProto;
proto::TransactionBody mTransactionBody;
TransactionBody* mTransactionBody;
controller::NodeServerConnection mConnection;
};
}

View File

@ -0,0 +1,32 @@
#include "Response.h"
namespace model {
namespace hedera {
Response::Response()
{
}
Response::~Response()
{
}
Poco::UInt64 Response::getAccountBalance()
{
if (isCryptoGetAccountBalanceResponse()) {
auto balance_response = mResponseProto.cryptogetaccountbalance();
return balance_response.balance();
}
return 0;
}
proto::ResponseCodeEnum Response::getResponseCode()
{
if (isCryptoGetAccountBalanceResponse()) {
auto balance_response = mResponseProto.cryptogetaccountbalance();
return balance_response.header().nodetransactionprecheckcode();
}
return proto::NOT_SUPPORTED;
}
}
}

View File

@ -0,0 +1,38 @@
#ifndef _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_RESPONSE_H
#define _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_RESPONSE_H
/*!
* @author: Dario Rekowski
*
* @date: 03.09.20
*
* @brief: class for simply accessing hedera responses
*
*/
#include "../../proto/hedera/Response.pb.h"
#include "Poco/Types.h"
namespace model {
namespace hedera {
class Response
{
public:
Response();
~Response();
inline proto::Response* getResponsePtr() { return &mResponseProto; }
Poco::UInt64 getAccountBalance();
proto::ResponseCodeEnum getResponseCode();
inline bool isCryptoGetAccountBalanceResponse() { return mResponseProto.has_cryptogetaccountbalance(); }
protected:
proto::Response mResponseProto;
};
}
}
#endif //_GRADIDO_LOGIN_SERVER_MODEL_HEDERA_RESPONSE_H

View File

@ -0,0 +1,43 @@
#include "Transaction.h"
namespace model {
namespace hedera {
Transaction::Transaction()
: mTransaction(nullptr)
{
mTransaction = new proto::Transaction;
}
Transaction::~Transaction()
{
if (mTransaction) {
delete mTransaction;
mTransaction = nullptr;
}
}
bool Transaction::sign(std::unique_ptr<KeyPairHedera> keyPairHedera, const TransactionBody* transactionBody)
{
auto mm = MemoryManager::getInstance();
auto transaction_body_proto = transactionBody->getProtoTransactionBody();
auto body_bytes = transaction_body_proto->SerializeAsString();
mTransaction->set_bodybytes(body_bytes.data());
auto signature_map = mTransaction->mutable_sigmap();
auto signature_pairs = signature_map->mutable_sigpair();
signature_map->add_sigpair();
auto signature_pair = signature_pairs->Mutable(0);
auto public_key = keyPairHedera->getPublicKey();
auto sign = keyPairHedera->sign(body_bytes);
if (!sign) {
printf("[Query::sign] error signing message\n");
return false;
}
signature_pair->set_pubkeyprefix(public_key, keyPairHedera->getPublicKeySize());
signature_pair->set_ed25519(*sign, sign->size());
mm->releaseMemory(sign);
return true;
}
}
}

View File

@ -0,0 +1,38 @@
#ifndef _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_TRANSACTION_H
#define _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_TRANSACTION_H
/*!
* @author: Dario Rekowski
*
* @date: 02.09.20
*
* @brief: class for composing hedera transaction
*
*/
#include "../../proto/hedera/Transaction.pb.h"
#include "../../Crypto/KeyPairHedera.h"
#include "TransactionBody.h"
namespace model {
namespace hedera {
class Transaction
{
public:
Transaction();
~Transaction();
bool sign(std::unique_ptr<KeyPairHedera> keyPairHedera, const TransactionBody* transactionBody);
inline proto::Transaction* getTransaction() { return mTransaction; }
void resetPointer() { mTransaction = nullptr; }
protected:
proto::Transaction* mTransaction;
};
}
}
#endif //_GRADIDO_LOGIN_SERVER_MODEL_HEDERA_TRANSACTION_H

View File

@ -0,0 +1,47 @@
#include "TransactionBody.h"
namespace model {
namespace hedera {
TransactionBody::TransactionBody(Poco::AutoPtr<controller::HederaId> operatorAccountId, const controller::NodeServerConnection& connection)
{
connection.hederaId->copyToProtoAccountId(mTransactionBody.mutable_nodeaccountid());
auto transaction_id = mTransactionBody.mutable_transactionid();
operatorAccountId->copyToProtoAccountId(transaction_id->mutable_accountid());
mTransactionBody.set_transactionfee(10000);
auto transaction_valid_duration = mTransactionBody.mutable_transactionvalidduration();
transaction_valid_duration->set_seconds(120);
updateTimestamp();
}
TransactionBody::~TransactionBody()
{
}
bool TransactionBody::setCryptoTransfer(CryptoTransferTransaction& cryptoTransferTransaction)
{
if (cryptoTransferTransaction.validate()) {
mTransactionBody.set_allocated_cryptotransfer(cryptoTransferTransaction.getProtoTransactionBody());
cryptoTransferTransaction.resetPointer();
return true;
}
return false;
}
void TransactionBody::setMemo(const std::string& memo)
{
mTransactionBody.set_memo(memo);
}
void TransactionBody::updateTimestamp()
{
auto transaction_id = mTransactionBody.mutable_transactionid();
auto timestamp = transaction_id->mutable_transactionvalidstart();
Poco::Timestamp now;
auto microseconds = now.epochMicroseconds() - now.epochTime() * now.resolution(); // 1*10^6
timestamp->set_seconds(now.epochTime());
timestamp->set_nanos(microseconds * 1000);
}
}
}

View File

@ -0,0 +1,39 @@
#ifndef _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_TRANSACTION_BODY_H
#define _GRADIDO_LOGIN_SERVER_MODEL_HEDERA_TRANSACTION_BODY_H
/*!
* @author: Dario Rekowski
*
* @date: 02.09.20
*
* @brief: class for composing transaction body for hedera transaction
*
*/
#include "../../proto/hedera/TransactionBody.pb.h"
#include "../../controller/NodeServer.h"
#include "CryptoTransferTransaction.h"
namespace model {
namespace hedera {
class TransactionBody
{
public:
TransactionBody(Poco::AutoPtr<controller::HederaId> operatorAccountId, const controller::NodeServerConnection& connection);
~TransactionBody();
void setMemo(const std::string& memo);
bool setCryptoTransfer(CryptoTransferTransaction& cryptoTransferTransaction);
inline const proto::TransactionBody* getProtoTransactionBody() const { return &mTransactionBody; }
protected:
void updateTimestamp();
proto::TransactionBody mTransactionBody;
};
}
}
#endif //_GRADIDO_LOGIN_SERVER_MODEL_HEDERA_TRANSACTION_BODY_H

View File

@ -24,7 +24,7 @@ namespace model {
MYSQL_CONDITION_OR
};
class ModelBase : public UniLib::lib::MultithreadContainer, public ErrorList
class ModelBase : public UniLib::lib::MultithreadContainer, public NotificationList
{
public:
ModelBase(int id) :mID(id), mReferenceCount(1) {}

View File

@ -3,7 +3,7 @@
#include "CPUTask.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "../lib/DRHash.h"
#include "../model/TransactionBase.h"
@ -26,7 +26,7 @@ class TransactionCreation;
class TransactionTransfer;
class SigningTransaction;
class ProcessingTransaction : public UniLib::controller::CPUTask, public ErrorList
class ProcessingTransaction : public UniLib::controller::CPUTask, public NotificationList
{
friend SigningTransaction;
public:

View File

@ -3,7 +3,7 @@
#include "CPUTask.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
#include "../model/TransactionBase.h"
#include "../model/User.h"
#include "../controller/User.h"
@ -19,7 +19,7 @@
* @desc: Task for signing Transactions
*/
class SigningTransaction : public UniLib::controller::CPUTask, public ErrorList
class SigningTransaction : public UniLib::controller::CPUTask, public NotificationList
{
public:
SigningTransaction(Poco::AutoPtr<ProcessingTransaction> processingeTransaction, Poco::AutoPtr<controller::User> newUser);

View File

@ -1,5 +1,5 @@
#include "Task.h"
#include "../lib/ErrorList.h"
#include "../lib/NotificationList.h"
namespace UniLib {
namespace controller {
@ -87,7 +87,7 @@ namespace UniLib {
mWorkingMutex.lock(500);
}
catch (Poco::TimeoutException& ex) {
ErrorList errors;
NotificationList errors;
errors.addError(new ParamError("Task::lock", getResourceType(), ex.displayText()));
errors.sendErrorsAsEmail();
}

View File

@ -10,6 +10,8 @@
#include "../controller/HederaId.h"
#include "../controller/CryptoKey.h"
#include "../lib/DataTypeConverter.h"
#include "../lib/Profiler.h"
#include "../lib/Success.h"
#include "../SingletonManager/SessionManager.h"
#include "../ServerConfig.h"
@ -22,6 +24,8 @@
auto sm = SessionManager::getInstance();
auto mm = MemoryManager::getInstance();
auto user = mSession->getNewUser();
Profiler hedera_time;
std::string hedera_time_string;
Poco::URI uri(request.getURI());
auto uri_query = uri.getQueryParameters();
@ -44,7 +48,9 @@
if(!hedera_account.size() || hedera_account[0].isNull()) {
addError(new Error("Action Update Balance", "hedera id not found"));
} else {
hedera_time.reset();
hedera_account[0]->updateBalanceFromHedera(user, this);
addNotification(new ParamSuccess("Hedera", "crypto get balance success in ", hedera_time.string()));
}
}
}
@ -148,6 +154,7 @@
%><%@ include file="header_large.cpsp" %>
<%= getErrorsHtml() %>
<div class="center-form-container">
<div class="content-list">
<div class="content-list-title">