Fixes #618
This commit is contained in:
cyan317
2023-05-02 14:07:26 +01:00
committed by GitHub
parent 7776a5ffb6
commit 36ac3215e2
7 changed files with 1005 additions and 1 deletions

View File

@@ -92,6 +92,7 @@ target_sources(clio PRIVATE
src/rpc/ngHandlers/AccountNFTs.cpp
src/rpc/ngHandlers/AccountObjects.cpp
src/rpc/ngHandlers/BookChanges.cpp
src/rpc/ngHandlers/Ledger.cpp
## RPC Methods
# Account
src/rpc/handlers/AccountChannels.cpp
@@ -179,6 +180,7 @@ if(BUILD_TESTS)
unittests/rpc/handlers/LedgerDataTest.cpp
unittests/rpc/handlers/AccountObjectsTest.cpp
unittests/rpc/handlers/BookChangesTest.cpp
unittests/rpc/handlers/LedgerTest.cpp
# Backend
unittests/backend/cassandra/BaseTests.cpp
unittests/backend/cassandra/BackendTests.cpp

View File

@@ -22,7 +22,6 @@
#include <rpc/common/Validators.h>
#include <boost/json/value.hpp>
#include <fmt/core.h>
#include <charconv>
#include <string_view>

View File

@@ -23,6 +23,8 @@
#include <rpc/common/Specs.h>
#include <rpc/common/Types.h>
#include <fmt/core.h>
namespace RPCng::validation {
/**
@@ -107,6 +109,65 @@ struct Required final
verify(boost::json::value const& value, std::string_view key) const;
};
/**
* @brief A validator that forbids a field to be present
* If there is a value provided, it will forbid the field only when the value equals
* If there is no value provided, it will forbid the field when the field shows up
*/
template <typename... T>
class NotSupported;
/**
* @brief A specialized NotSupported validator that forbids a field to be present when the value equals the given value
*/
template <typename T>
class NotSupported<T> final
{
T value_;
public:
[[nodiscard]] MaybeError
verify(boost::json::value const& value, std::string_view key) const
{
if (value.is_object() and value.as_object().contains(key.data()))
{
using boost::json::value_to;
auto const res = value_to<T>(value.as_object().at(key.data()));
if (value_ == res)
return Error{RPC::Status{
RPC::RippledError::rpcNOT_SUPPORTED,
fmt::format("Not supported field '{}'s value '{}'", std::string{key}, res)}};
}
return {};
}
NotSupported(T val) : value_(val)
{
}
};
/**
* @brief A specialized NotSupported validator that forbids a field to be present
*/
template <>
class NotSupported<> final
{
public:
[[nodiscard]] MaybeError
verify(boost::json::value const& value, std::string_view key) const
{
if (value.is_object() and value.as_object().contains(key.data()))
{
return Error{RPC::Status{RPC::RippledError::rpcNOT_SUPPORTED, "Not supported field '" + std::string{key}}};
}
return {};
}
};
// deduction guide to avoid having to specify the template arguments
template <typename... T>
NotSupported(T&&... t) -> NotSupported<T...>;
/**
* @brief Validates that the type of the value is one of the given types
*/

View File

@@ -0,0 +1,174 @@
//------------------------------------------------------------------------------
/*
This file is part of clio: https://github.com/XRPLF/clio
Copyright (c) 2023, the clio developers.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <rpc/ngHandlers/Ledger.h>
namespace RPCng {
LedgerHandler::Result
LedgerHandler::process(LedgerHandler::Input input, Context const& ctx) const
{
auto const range = sharedPtrBackend_->fetchLedgerRange();
auto const lgrInfoOrStatus = RPC::getLedgerInfoFromHashOrSeq(
*sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence);
if (auto const status = std::get_if<RPC::Status>(&lgrInfoOrStatus))
return Error{*status};
auto const lgrInfo = std::get<ripple::LedgerInfo>(lgrInfoOrStatus);
Output output;
if (input.binary)
{
output.header[JS(ledger_data)] = ripple::strHex(RPC::ledgerInfoToBlob(lgrInfo));
}
else
{
output.header[JS(accepted)] = true;
output.header[JS(account_hash)] = ripple::strHex(lgrInfo.accountHash);
output.header[JS(close_flags)] = lgrInfo.closeFlags;
output.header[JS(close_time)] = lgrInfo.closeTime.time_since_epoch().count();
output.header[JS(close_time_human)] = ripple::to_string(lgrInfo.closeTime);
output.header[JS(close_time_resolution)] = lgrInfo.closeTimeResolution.count();
output.header[JS(closed)] = true;
output.header[JS(hash)] = ripple::strHex(lgrInfo.hash);
output.header[JS(ledger_hash)] = ripple::strHex(lgrInfo.hash);
output.header[JS(ledger_index)] = std::to_string(lgrInfo.seq);
output.header[JS(parent_close_time)] = lgrInfo.parentCloseTime.time_since_epoch().count();
output.header[JS(parent_hash)] = ripple::strHex(lgrInfo.parentHash);
output.header[JS(seqNum)] = std::to_string(lgrInfo.seq);
output.header[JS(totalCoins)] = ripple::to_string(lgrInfo.drops);
output.header[JS(total_coins)] = ripple::to_string(lgrInfo.drops);
output.header[JS(transaction_hash)] = ripple::strHex(lgrInfo.txHash);
}
output.header[JS(closed)] = true;
if (input.transactions)
{
output.header[JS(transactions)] = boost::json::value(boost::json::array_kind);
boost::json::array& jsonTxs = output.header.at(JS(transactions)).as_array();
if (input.expand)
{
auto txns = sharedPtrBackend_->fetchAllTransactionsInLedger(lgrInfo.seq, ctx.yield);
std::transform(
std::move_iterator(txns.begin()),
std::move_iterator(txns.end()),
std::back_inserter(jsonTxs),
[&](auto obj) {
boost::json::object entry;
if (!input.binary)
{
auto [txn, meta] = RPC::toExpandedJson(obj);
entry = std::move(txn);
entry[JS(metaData)] = std::move(meta);
}
else
{
entry[JS(tx_blob)] = ripple::strHex(obj.transaction);
entry[JS(meta)] = ripple::strHex(obj.metadata);
}
return entry;
});
}
else
{
auto hashes = sharedPtrBackend_->fetchAllTransactionHashesInLedger(lgrInfo.seq, ctx.yield);
std::transform(
std::move_iterator(hashes.begin()),
std::move_iterator(hashes.end()),
std::back_inserter(jsonTxs),
[](auto hash) { return boost::json::string(ripple::strHex(hash)); });
}
}
if (input.diff)
{
output.header["diff"] = boost::json::value(boost::json::array_kind);
boost::json::array& jsonDiff = output.header.at("diff").as_array();
auto diff = sharedPtrBackend_->fetchLedgerDiff(lgrInfo.seq, ctx.yield);
for (auto const& obj : diff)
{
boost::json::object entry;
entry["object_id"] = ripple::strHex(obj.key);
if (input.binary)
{
entry["object"] = ripple::strHex(obj.blob);
}
else if (obj.blob.size())
{
ripple::STLedgerEntry const sle{ripple::SerialIter{obj.blob.data(), obj.blob.size()}, obj.key};
entry["object"] = RPC::toJson(sle);
}
else
{
entry["object"] = "";
}
jsonDiff.push_back(std::move(entry));
}
}
output.ledgerHash = ripple::strHex(lgrInfo.hash);
output.ledgerIndex = lgrInfo.seq;
return output;
}
void
tag_invoke(boost::json::value_from_tag, boost::json::value& jv, LedgerHandler::Output const& output)
{
jv = boost::json::object{
{JS(ledger_hash), output.ledgerHash},
{JS(ledger_index), output.ledgerIndex},
{JS(validated), output.validated},
{JS(ledger), output.header},
};
}
LedgerHandler::Input
tag_invoke(boost::json::value_to_tag<LedgerHandler::Input>, boost::json::value const& jv)
{
auto const& jsonObject = jv.as_object();
LedgerHandler::Input input;
if (jsonObject.contains(JS(ledger_hash)))
input.ledgerHash = jv.at(JS(ledger_hash)).as_string().c_str();
if (jsonObject.contains(JS(ledger_index)))
{
if (!jsonObject.at(JS(ledger_index)).is_string())
input.ledgerIndex = jv.at(JS(ledger_index)).as_int64();
else if (jsonObject.at(JS(ledger_index)).as_string() != "validated")
input.ledgerIndex = std::stoi(jv.at(JS(ledger_index)).as_string().c_str());
}
if (jsonObject.contains(JS(transactions)))
input.transactions = jv.at(JS(transactions)).as_bool();
if (jsonObject.contains(JS(binary)))
input.binary = jv.at(JS(binary)).as_bool();
if (jsonObject.contains(JS(expand)))
input.expand = jv.at(JS(expand)).as_bool();
if (jsonObject.contains("diff"))
input.diff = jv.at("diff").as_bool();
return input;
}
} // namespace RPCng

View File

@@ -0,0 +1,89 @@
//------------------------------------------------------------------------------
/*
This file is part of clio: https://github.com/XRPLF/clio
Copyright (c) 2023, the clio developers.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#pragma once
#include <backend/BackendInterface.h>
#include <rpc/RPCHelpers.h>
#include <rpc/common/Types.h>
#include <rpc/common/Validators.h>
namespace RPCng {
class LedgerHandler
{
std::shared_ptr<BackendInterface> sharedPtrBackend_;
public:
struct Output
{
uint32_t ledgerIndex;
std::string ledgerHash;
// TODO: use better type
boost::json::object header;
bool validated = true;
};
// clio not support : accounts/full/owner_finds/queue/type
// clio will throw error when accounts/full/owner_funds/queue is set to true
// https://github.com/XRPLF/clio/issues/603
struct Input
{
std::optional<std::string> ledgerHash;
std::optional<uint32_t> ledgerIndex;
bool binary = false;
bool expand = false;
bool transactions = false;
bool diff = false;
};
using Result = RPCng::HandlerReturnType<Output>;
LedgerHandler(std::shared_ptr<BackendInterface> const& sharedPtrBackend) : sharedPtrBackend_(sharedPtrBackend)
{
}
RpcSpecConstRef
spec() const
{
static auto const rpcSpec = RpcSpec{
{JS(full), validation::Type<bool>{}, validation::NotSupported{true}},
{JS(accounts), validation::Type<bool>{}, validation::NotSupported{true}},
{JS(owner_funds), validation::Type<bool>{}, validation::NotSupported{true}},
{JS(queue), validation::Type<bool>{}, validation::NotSupported{true}},
{JS(ledger_hash), validation::Uint256HexStringValidator},
{JS(ledger_index), validation::LedgerIndexValidator},
{JS(transactions), validation::Type<bool>{}},
{JS(expand), validation::Type<bool>{}},
{JS(binary), validation::Type<bool>{}},
};
return rpcSpec;
}
Result
process(Input input, Context const& ctx) const;
private:
friend void
tag_invoke(boost::json::value_from_tag, boost::json::value& jv, Output const& output);
friend Input
tag_invoke(boost::json::value_to_tag<Input>, boost::json::value const& jv);
};
} // namespace RPCng

View File

@@ -322,6 +322,23 @@ TEST_F(RPCBaseTest, CustomValidator)
ASSERT_FALSE(spec.validate(failingInput));
}
TEST_F(RPCBaseTest, NotSupported)
{
auto spec = RpcSpec{
{"taker", Type<uint32_t>{}, NotSupported{123}},
{"getter", NotSupported{}},
};
auto passingInput = json::parse(R"({ "taker": 2 })");
ASSERT_TRUE(spec.validate(passingInput));
auto failingInput = json::parse(R"({ "taker": 123 })");
ASSERT_FALSE(spec.validate(failingInput));
failingInput = json::parse(R"({ "taker": 2, "getter": 2 })");
ASSERT_FALSE(spec.validate(failingInput));
}
TEST_F(RPCBaseTest, LedgerIndexValidator)
{
auto spec = RpcSpec{

View File

@@ -0,0 +1,662 @@
//------------------------------------------------------------------------------
/*
This file is part of clio: https://github.com/XRPLF/clio
Copyright (c) 2023, the clio developers.
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <rpc/common/AnyHandler.h>
#include <rpc/ngHandlers/Ledger.h>
#include <util/Fixtures.h>
#include <util/TestObject.h>
#include <fmt/core.h>
constexpr static auto ACCOUNT = "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn";
constexpr static auto ACCOUNT2 = "rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun";
constexpr static auto LEDGERHASH = "4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652";
constexpr static auto INDEX1 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC";
constexpr static auto INDEX2 = "1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1";
constexpr static auto RANGEMIN = 10;
constexpr static auto RANGEMAX = 30;
using namespace RPCng;
namespace json = boost::json;
using namespace testing;
class RPCLedgerHandlerTest : public HandlerBaseTest
{
};
struct LedgerParamTestCaseBundle
{
std::string testName;
std::string testJson;
std::string expectedError;
std::string expectedErrorMessage;
};
// parameterized test cases for parameters check
struct LedgerParameterTest : public RPCLedgerHandlerTest, public WithParamInterface<LedgerParamTestCaseBundle>
{
struct NameGenerator
{
template <class ParamType>
std::string
operator()(const testing::TestParamInfo<ParamType>& info) const
{
auto bundle = static_cast<LedgerParamTestCaseBundle>(info.param);
return bundle.testName;
}
};
};
static auto
generateTestValuesForParametersTest()
{
return std::vector<LedgerParamTestCaseBundle>{
{
"AccountsNotBool",
R"({"accounts": 123})",
"invalidParams",
"Invalid parameters.",
},
{
"AccountsInvalid",
R"({"accounts": true})",
"notSupported",
"Not supported field 'accounts's value 'true'",
},
{
"FullExist",
R"({"full": true})",
"notSupported",
"Not supported field 'full's value 'true'",
},
{
"FullNotBool",
R"({"full": 123})",
"invalidParams",
"Invalid parameters.",
},
{
"QueueExist",
R"({"queue": true})",
"notSupported",
"Not supported field 'queue's value 'true'",
},
{
"QueueNotBool",
R"({"queue": 123})",
"invalidParams",
"Invalid parameters.",
},
{
"OwnerFundsExist",
R"({"owner_funds": true})",
"notSupported",
"Not supported field 'owner_funds's value 'true'",
},
{
"OwnerFundsNotBool",
R"({"owner_funds": 123})",
"invalidParams",
"Invalid parameters.",
},
{
"LedgerHashInvalid",
R"({"account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_hash": "x"})",
"invalidParams",
"ledger_hashMalformed",
},
{
"LedgerHashNotString",
R"({"account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_hash": 123})",
"invalidParams",
"ledger_hashNotString",
},
{
"LedgerIndexNotInt",
R"({"account": "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn", "ledger_index": "x"})",
"invalidParams",
"ledgerIndexMalformed",
},
{
"TransactionsNotBool",
R"({"transactions": "x"})",
"invalidParams",
"Invalid parameters.",
},
{
"ExpandNotBool",
R"({"expand": "x"})",
"invalidParams",
"Invalid parameters.",
},
{
"BinaryNotBool",
R"({"binary": "x"})",
"invalidParams",
"Invalid parameters.",
},
};
}
INSTANTIATE_TEST_CASE_P(
RPCLedgerGroup1,
LedgerParameterTest,
ValuesIn(generateTestValuesForParametersTest()),
LedgerParameterTest::NameGenerator{});
TEST_P(LedgerParameterTest, InvalidParams)
{
auto const testBundle = GetParam();
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(testBundle.testJson);
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_FALSE(output);
auto const err = RPC::makeError(output.error());
std::cout << err << std::endl;
EXPECT_EQ(err.at("error").as_string(), testBundle.expectedError);
EXPECT_EQ(err.at("error_message").as_string(), testBundle.expectedErrorMessage);
});
}
TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaIntSequence)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN); // min
mockBackendPtr->updateRange(RANGEMAX); // max
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(std::nullopt));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(fmt::format(
R"({{
"ledger_index": {}
}})",
RANGEMAX));
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_FALSE(output);
auto const err = RPC::makeError(output.error());
EXPECT_EQ(err.at("error").as_string(), "lgrNotFound");
EXPECT_EQ(err.at("error_message").as_string(), "ledgerNotFound");
});
}
TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaStringSequence)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN); // min
mockBackendPtr->updateRange(RANGEMAX); // max
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(std::nullopt));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(fmt::format(
R"({{
"ledger_index": "{}"
}})",
RANGEMAX));
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_FALSE(output);
auto const err = RPC::makeError(output.error());
EXPECT_EQ(err.at("error").as_string(), "lgrNotFound");
EXPECT_EQ(err.at("error_message").as_string(), "ledgerNotFound");
});
}
TEST_F(RPCLedgerHandlerTest, LedgerNotExistViaHash)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN); // min
mockBackendPtr->updateRange(RANGEMAX); // max
EXPECT_CALL(*rawBackendPtr, fetchLedgerByHash).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerByHash(ripple::uint256{LEDGERHASH}, _)).WillByDefault(Return(std::nullopt));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(fmt::format(
R"({{
"ledger_hash": "{}"
}})",
LEDGERHASH));
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_FALSE(output);
auto const err = RPC::makeError(output.error());
EXPECT_EQ(err.at("error").as_string(), "lgrNotFound");
EXPECT_EQ(err.at("error_message").as_string(), "ledgerNotFound");
});
}
TEST_F(RPCLedgerHandlerTest, Default)
{
static auto constexpr expectedOut =
R"({
"ledger_hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_index":30,
"validated":true,
"ledger":{
"accepted":true,
"account_hash":"0000000000000000000000000000000000000000000000000000000000000000",
"close_flags":0,
"close_time":0,
"close_time_resolution":0,
"closed":true,
"hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_index":"30",
"parent_close_time":0,
"parent_hash":"0000000000000000000000000000000000000000000000000000000000000000",
"seqNum":"30",
"totalCoins":"0",
"total_coins":"0",
"transaction_hash":"0000000000000000000000000000000000000000000000000000000000000000"
}
})";
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse("{}");
auto output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
// remove human readable time, it is sightly different cross the platform
EXPECT_EQ(output->as_object().at("ledger").as_object().erase("close_time_human"), 1);
EXPECT_EQ(*output, json::parse(expectedOut));
});
}
// not supported fields can be set to its default value
TEST_F(RPCLedgerHandlerTest, NotSupportedFieldsDefaultValue)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"full": false,
"accounts": false,
"queue": false,
"owner_funds": false
})");
auto output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
});
}
TEST_F(RPCLedgerHandlerTest, QueryViaLedgerIndex)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(15, _)).WillByDefault(Return(ledgerinfo));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(R"({"ledger_index": 15})");
auto output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_TRUE(output->as_object().contains("ledger"));
});
}
TEST_F(RPCLedgerHandlerTest, QueryViaLedgerHash)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerByHash).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerByHash(ripple::uint256{INDEX1}, _)).WillByDefault(Return(ledgerinfo));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(fmt::format(R"({{"ledger_hash": "{}" }})", INDEX1));
auto output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_TRUE(output->as_object().contains("ledger"));
});
}
TEST_F(RPCLedgerHandlerTest, BinaryTrue)
{
static auto constexpr expectedOut =
R"({
"ledger_hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_index":30,
"validated":true,
"ledger":{
"ledger_data":"0000001E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"closed":true
}
})";
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"binary": true
})");
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_EQ(*output, json::parse(expectedOut));
});
}
TEST_F(RPCLedgerHandlerTest, TransactionsExpandBinary)
{
static auto constexpr expectedOut =
R"({
"ledger_hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_index":30,
"validated":true,
"ledger":{
"ledger_data":"0000001E000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"closed":true,
"transactions":[
{
"tx_blob":"120000240000001E61400000000000006468400000000000000373047465737481144B4E9C06F24296074F7BC48F92A97916C6DC5EA98314D31252CF902EF8DD8451243869B38667CBD89DF3",
"meta":"201C00000000F8E5110061E762400000000000006E81144B4E9C06F24296074F7BC48F92A97916C6DC5EA9E1E1E5110061E762400000000000001E8114D31252CF902EF8DD8451243869B38667CBD89DF3E1E1F1031000"
},
{
"tx_blob":"120000240000001E61400000000000006468400000000000000373047465737481144B4E9C06F24296074F7BC48F92A97916C6DC5EA98314D31252CF902EF8DD8451243869B38667CBD89DF3",
"meta":"201C00000000F8E5110061E762400000000000006E81144B4E9C06F24296074F7BC48F92A97916C6DC5EA9E1E1E5110061E762400000000000001E8114D31252CF902EF8DD8451243869B38667CBD89DF3E1E1F1031000"
}
]
}
})";
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
TransactionAndMetadata t1;
t1.transaction = CreatePaymentTransactionObject(ACCOUNT, ACCOUNT2, 100, 3, RANGEMAX).getSerializer().peekData();
t1.metadata = CreatePaymentTransactionMetaObject(ACCOUNT, ACCOUNT2, 110, 30).getSerializer().peekData();
t1.ledgerSequence = RANGEMAX;
EXPECT_CALL(*rawBackendPtr, fetchAllTransactionsInLedger).Times(1);
ON_CALL(*rawBackendPtr, fetchAllTransactionsInLedger(RANGEMAX, _)).WillByDefault(Return(std::vector{t1, t1}));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"binary": true,
"expand": true,
"transactions": true
})");
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_EQ(*output, json::parse(expectedOut));
});
}
TEST_F(RPCLedgerHandlerTest, TransactionsExpandNotBinary)
{
static auto constexpr expectedOut =
R"({
"ledger_hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_index":30,
"validated":true,
"ledger":{
"accepted":true,
"account_hash":"0000000000000000000000000000000000000000000000000000000000000000",
"close_flags":0,
"close_time":0,
"close_time_resolution":0,
"closed":true,
"hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_hash":"4BC50C9B0D8515D3EAAE1E74B29A95804346C491EE1A95BF25E4AAB854A6A652",
"ledger_index":"30",
"parent_close_time":0,
"parent_hash":"0000000000000000000000000000000000000000000000000000000000000000",
"seqNum":"30",
"totalCoins":"0",
"total_coins":"0",
"transaction_hash":"0000000000000000000000000000000000000000000000000000000000000000",
"transactions":[
{
"Account":"rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"Amount":"100",
"Destination":"rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun",
"Fee":"3",
"Sequence":30,
"SigningPubKey":"74657374",
"TransactionType":"Payment",
"hash":"70436A9332F7CD928FAEC1A41269A677739D8B11F108CE23AE23CBF0C9113F8C",
"metaData":{
"AffectedNodes":[
{
"ModifiedNode":{
"FinalFields":{
"Account":"rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"Balance":"110"
},
"LedgerEntryType":"AccountRoot"
}
},
{
"ModifiedNode":{
"FinalFields":{
"Account":"rLEsXccBGNR3UPuPu2hUXPjziKC3qKSBun",
"Balance":"30"
},
"LedgerEntryType":"AccountRoot"
}
}
],
"TransactionIndex":0,
"TransactionResult":"tesSUCCESS",
"delivered_amount":"unavailable"
}
}
]
}
})";
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
TransactionAndMetadata t1;
t1.transaction = CreatePaymentTransactionObject(ACCOUNT, ACCOUNT2, 100, 3, RANGEMAX).getSerializer().peekData();
t1.metadata = CreatePaymentTransactionMetaObject(ACCOUNT, ACCOUNT2, 110, 30).getSerializer().peekData();
t1.ledgerSequence = RANGEMAX;
EXPECT_CALL(*rawBackendPtr, fetchAllTransactionsInLedger).Times(1);
ON_CALL(*rawBackendPtr, fetchAllTransactionsInLedger(RANGEMAX, _)).WillByDefault(Return(std::vector{t1}));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"binary": false,
"expand": true,
"transactions": true
})");
auto output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
// remove human readable time, it is sightly different cross the platform
EXPECT_EQ(output->as_object().at("ledger").as_object().erase("close_time_human"), 1);
EXPECT_EQ(*output, json::parse(expectedOut));
});
}
TEST_F(RPCLedgerHandlerTest, TransactionsNotExpand)
{
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
EXPECT_CALL(*rawBackendPtr, fetchAllTransactionHashesInLedger).Times(1);
ON_CALL(*rawBackendPtr, fetchAllTransactionHashesInLedger(RANGEMAX, _))
.WillByDefault(Return(std::vector{ripple::uint256{INDEX1}, ripple::uint256{INDEX2}}));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"transactions": true
})");
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_EQ(
output->as_object().at("ledger").at("transactions"),
json::parse(fmt::format(R"(["{}","{}"])", INDEX1, INDEX2)));
});
}
TEST_F(RPCLedgerHandlerTest, DiffNotBinary)
{
static auto constexpr expectedOut =
R"([
{
"object_id":"1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1",
"object":""
},
{
"object_id":"1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC",
"object":{
"Account":"rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn",
"Balance":"10",
"Flags":4194304,
"LedgerEntryType":"AccountRoot",
"OwnerCount":2,
"PreviousTxnID":"1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC",
"PreviousTxnLgrSeq":3,
"Sequence":1,
"TransferRate":0,
"index":"1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC"
}
}
])";
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
std::vector<LedgerObject> los;
EXPECT_CALL(*rawBackendPtr, fetchLedgerDiff).Times(1);
los.push_back(LedgerObject{ripple::uint256{INDEX2}, Blob{}});
los.push_back(LedgerObject{
ripple::uint256{INDEX1},
CreateAccountRootObject(ACCOUNT, ripple::lsfGlobalFreeze, 1, 10, 2, INDEX1, 3).getSerializer().peekData()});
ON_CALL(*rawBackendPtr, fetchLedgerDiff(RANGEMAX, _)).WillByDefault(Return(los));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"diff": true
})");
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_EQ(output->at("ledger").at("diff"), json::parse(expectedOut));
});
}
TEST_F(RPCLedgerHandlerTest, DiffBinary)
{
static auto constexpr expectedOut =
R"([
{
"object_id":"1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515B1",
"object":""
},
{
"object_id":"1B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC",
"object":"1100612200400000240000000125000000032B000000002D00000002551B8590C01B0006EDFA9ED60296DD052DC5E90F99659B25014D08E1BC983515BC62400000000000000A81144B4E9C06F24296074F7BC48F92A97916C6DC5EA9"
}
])";
auto const rawBackendPtr = static_cast<MockBackend*>(mockBackendPtr.get());
mockBackendPtr->updateRange(RANGEMIN);
mockBackendPtr->updateRange(RANGEMAX);
auto const ledgerinfo = CreateLedgerInfo(LEDGERHASH, RANGEMAX);
EXPECT_CALL(*rawBackendPtr, fetchLedgerBySequence).Times(1);
ON_CALL(*rawBackendPtr, fetchLedgerBySequence(RANGEMAX, _)).WillByDefault(Return(ledgerinfo));
std::vector<LedgerObject> los;
EXPECT_CALL(*rawBackendPtr, fetchLedgerDiff).Times(1);
los.push_back(LedgerObject{ripple::uint256{INDEX2}, Blob{}});
los.push_back(LedgerObject{
ripple::uint256{INDEX1},
CreateAccountRootObject(ACCOUNT, ripple::lsfGlobalFreeze, 1, 10, 2, INDEX1, 3).getSerializer().peekData()});
ON_CALL(*rawBackendPtr, fetchLedgerDiff(RANGEMAX, _)).WillByDefault(Return(los));
runSpawn([&, this](auto& yield) {
auto const handler = AnyHandler{LedgerHandler{mockBackendPtr}};
auto const req = json::parse(
R"({
"diff": true,
"binary": true
})");
auto const output = handler.process(req, Context{std::ref(yield)});
ASSERT_TRUE(output);
EXPECT_EQ(output->at("ledger").at("diff"), json::parse(expectedOut));
});
}