From 55222dc5d1de7082faaddd57aa5194c1232ba1c5 Mon Sep 17 00:00:00 2001 From: Tom Ritchford Date: Thu, 19 Jun 2014 18:21:28 -0400 Subject: [PATCH] New types Account, Currency, Directory: * New tagged uint types. * Extract to_string functions from header to hide dependencies. * Include what you use and C++11 for cleanups. --- Builds/VisualStudio2013/RippleD.vcxproj | 34 +- .../VisualStudio2013/RippleD.vcxproj.filters | 42 +- src/ripple/module/app/book/Taker.h | 1 - src/ripple/module/app/book/Types.h | 38 -- src/ripple/module/app/book/impl/Types.cpp | 29 -- .../module/app/book/tests/Quality.test.cpp | 2 +- .../module/app/consensus/DisputedTx.cpp | 42 +- src/ripple/module/app/consensus/DisputedTx.h | 10 +- .../module/app/consensus/LedgerConsensus.cpp | 26 +- src/ripple/module/app/contracts/Contract.cpp | 48 -- src/ripple/module/app/contracts/Contract.h | 46 -- .../module/app/contracts/Interpreter.cpp | 228 ---------- src/ripple/module/app/contracts/Interpreter.h | 102 ----- src/ripple/module/app/contracts/Operation.cpp | 38 -- src/ripple/module/app/contracts/Operation.h | 380 ---------------- .../module/app/contracts/ScriptData.cpp | 22 - src/ripple/module/app/contracts/ScriptData.h | 186 -------- src/ripple/module/app/ledger/Ledger.cpp | 424 ++++++++++-------- src/ripple/module/app/ledger/Ledger.h | 257 +++++++---- .../module/app/ledger/LedgerEntrySet.cpp | 190 ++++---- src/ripple/module/app/ledger/LedgerEntrySet.h | 75 ++-- src/ripple/module/app/ledger/LedgerProposal.h | 4 +- src/ripple/module/app/ledger/OrderBookDB.cpp | 43 +- src/ripple/module/app/ledger/OrderBookDB.h | 33 +- .../module/app/ledger/OrderBookIterator.cpp | 9 +- .../module/app/ledger/OrderBookIterator.h | 23 +- .../module/app/ledger/SerializedValidation.h | 4 +- src/ripple/module/app/misc/AccountItem.h | 12 +- src/ripple/module/app/misc/AccountItems.cpp | 30 +- src/ripple/module/app/misc/AccountItems.h | 5 +- .../module/app/misc/AmendmentTableImpl.cpp | 6 +- src/ripple/module/app/misc/FeeVoteImpl.cpp | 12 +- src/ripple/module/app/misc/NetworkOPs.cpp | 290 +++++++----- src/ripple/module/app/misc/NetworkOPs.h | 27 +- src/ripple/module/app/misc/Offer.cpp | 3 +- src/ripple/module/app/misc/Offer.h | 3 +- src/ripple/module/app/misc/OrderBook.cpp | 8 +- src/ripple/module/app/misc/OrderBook.h | 27 +- .../module/app/misc/SerializedLedger.cpp | 10 +- .../module/app/misc/SerializedTransaction.cpp | 2 +- src/ripple/module/app/misc/Validations.cpp | 59 ++- src/ripple/module/app/misc/Validations.h | 24 +- .../module/app/paths/CalcNodeAdvance.cpp | 41 +- .../module/app/paths/CalcNodeDeliverFwd.cpp | 13 +- .../module/app/paths/CalcNodeDeliverRev.cpp | 24 +- src/ripple/module/app/paths/Calculators.h | 4 +- .../paths/ComputeAccountLiquidityForward.cpp | 14 +- .../paths/ComputeAccountLiquidityReverse.cpp | 4 +- .../module/app/paths/ComputeLiquidity.cpp | 2 +- .../app/paths/ComputeRippleLiquidity.cpp | 4 +- src/ripple/module/app/paths/Node.cpp | 6 +- src/ripple/module/app/paths/Node.h | 7 +- src/ripple/module/app/paths/PathRequest.cpp | 91 ++-- src/ripple/module/app/paths/PathRequest.h | 8 +- src/ripple/module/app/paths/PathState.cpp | 66 +-- src/ripple/module/app/paths/PathState.h | 3 - src/ripple/module/app/paths/Pathfinder.cpp | 247 +++++----- src/ripple/module/app/paths/Pathfinder.h | 72 +-- src/ripple/module/app/paths/RippleCalc.cpp | 13 +- src/ripple/module/app/paths/RippleCalc.h | 4 +- .../module/app/paths/RippleLineCache.cpp | 10 +- src/ripple/module/app/paths/RippleLineCache.h | 8 +- src/ripple/module/app/paths/RippleState.cpp | 8 +- src/ripple/module/app/paths/RippleState.h | 23 +- src/ripple/module/app/paths/Types.cpp | 27 -- src/ripple/module/app/paths/Types.h | 12 +- .../module/app/transactors/AddWallet.cpp | 15 +- .../module/app/transactors/CancelOffer.cpp | 2 +- .../module/app/transactors/CreateOffer.cpp | 34 +- .../app/transactors/CreateOfferBridged.cpp | 5 +- .../app/transactors/CreateOfferDirect.cpp | 10 +- .../app/transactors/CreateOfferLegacy.cpp | 56 +-- .../app/transactors/CreateOfferLegacy.h | 20 +- src/ripple/module/app/transactors/Payment.cpp | 8 +- .../module/app/transactors/SetRegularKey.cpp | 2 +- .../module/app/transactors/SetTrust.cpp | 16 +- .../module/app/transactors/Transactor.h | 6 +- .../module/app/tx/TransactionAcquire.cpp | 3 - src/ripple/module/app/tx/TransactionEngine.h | 12 +- src/ripple/module/app/tx/TransactionMeta.cpp | 2 +- .../module/data/protocol/FieldNames.cpp | 38 +- src/ripple/module/data/protocol/FieldNames.h | 9 +- src/ripple/module/data/protocol/Protocol.h | 7 - .../module/data/protocol/RippleAddress.cpp | 126 +++--- .../module/data/protocol/RippleAddress.h | 61 +-- .../module/data/protocol/RippleSystem.h | 2 - src/ripple/module/data/protocol/STAmount.cpp | 299 +++++------- .../module/data/protocol/STAmountRound.cpp | 44 +- .../module/data/protocol/STParsedJSON.cpp | 14 +- .../module/data/protocol/SerializedObject.cpp | 64 +-- .../module/data/protocol/SerializedObject.h | 29 +- .../module/data/protocol/SerializedTypes.cpp | 90 ++-- .../module/data/protocol/SerializedTypes.h | 196 ++++---- .../module/data/protocol/Serializer.cpp | 15 - src/ripple/module/data/protocol/Serializer.h | 27 +- src/ripple/module/net/rpc/InfoSub.h | 20 +- .../module/rpc/handlers/AccountCurrencies.cpp | 30 +- .../module/rpc/handlers/AccountLines.cpp | 2 +- src/ripple/module/rpc/handlers/BookOffers.cpp | 63 +-- .../module/rpc/handlers/LedgerEntry.cpp | 5 +- src/ripple/module/rpc/handlers/Profile.cpp | 8 +- .../module/rpc/handlers/RipplePathFind.cpp | 33 +- src/ripple/module/rpc/handlers/Subscribe.cpp | 22 +- .../module/rpc/handlers/Unsubscribe.cpp | 43 +- .../module/rpc/impl/AccountFromString.cpp | 2 +- .../module/rpc/impl/TransactionSign.cpp | 4 +- src/ripple/types/api/RippleAssets.h | 46 +- src/ripple/types/api/UInt160.h | 8 +- src/ripple/types/api/UintTypes.h | 135 ++++++ src/ripple/types/api/base_uint.h | 70 +-- src/ripple/types/impl/RippleAssets.cpp | 52 +-- src/ripple/types/impl/UInt160.cpp | 29 -- src/ripple/types/impl/UintTypes.cpp | 151 +++++++ src/ripple/unity/app.h | 5 - src/ripple/unity/app1.cpp | 3 +- src/ripple/unity/app3.cpp | 4 - src/ripple/unity/app9.cpp | 1 - src/ripple/unity/types.cpp | 3 +- 118 files changed, 2352 insertions(+), 3164 deletions(-) delete mode 100644 src/ripple/module/app/book/impl/Types.cpp delete mode 100644 src/ripple/module/app/contracts/Contract.cpp delete mode 100644 src/ripple/module/app/contracts/Contract.h delete mode 100644 src/ripple/module/app/contracts/Interpreter.cpp delete mode 100644 src/ripple/module/app/contracts/Interpreter.h delete mode 100644 src/ripple/module/app/contracts/Operation.cpp delete mode 100644 src/ripple/module/app/contracts/Operation.h delete mode 100644 src/ripple/module/app/contracts/ScriptData.cpp delete mode 100644 src/ripple/module/app/contracts/ScriptData.h delete mode 100644 src/ripple/module/app/paths/Types.cpp create mode 100644 src/ripple/types/api/UintTypes.h delete mode 100644 src/ripple/types/impl/UInt160.cpp create mode 100644 src/ripple/types/impl/UintTypes.cpp diff --git a/Builds/VisualStudio2013/RippleD.vcxproj b/Builds/VisualStudio2013/RippleD.vcxproj index 049790aa22..c280dee3e7 100644 --- a/Builds/VisualStudio2013/RippleD.vcxproj +++ b/Builds/VisualStudio2013/RippleD.vcxproj @@ -1983,9 +1983,6 @@ True - - True - True @@ -2002,26 +1999,6 @@ - - True - - - - - True - - - - - True - - - - - True - - - True @@ -2333,9 +2310,6 @@ - - True - @@ -2378,10 +2352,10 @@ - + True - + True @@ -3383,6 +3357,8 @@ + + @@ -3402,7 +3378,7 @@ True - + True diff --git a/Builds/VisualStudio2013/RippleD.vcxproj.filters b/Builds/VisualStudio2013/RippleD.vcxproj.filters index 91f61eb755..a5245d5f84 100644 --- a/Builds/VisualStudio2013/RippleD.vcxproj.filters +++ b/Builds/VisualStudio2013/RippleD.vcxproj.filters @@ -367,9 +367,6 @@ {28E35C4D-F39A-6C32-60CB-B29F44A08B72} - - {4EC681B8-69F8-73E2-8E0E-FD12EEC5AD2C} - {22718803-3748-7147-16F9-822D9BBFA8DC} @@ -2970,9 +2967,6 @@ ripple\module\app\book\impl - - ripple\module\app\book\impl - ripple\module\app\book\tests @@ -2991,30 +2985,6 @@ ripple\module\app\consensus - - ripple\module\app\contracts - - - ripple\module\app\contracts - - - ripple\module\app\contracts - - - ripple\module\app\contracts - - - ripple\module\app\contracts - - - ripple\module\app\contracts - - - ripple\module\app\contracts - - - ripple\module\app\contracts - ripple\module\app\data @@ -3387,9 +3357,6 @@ ripple\module\app\paths - - ripple\module\app\paths - ripple\module\app\paths @@ -3441,10 +3408,10 @@ ripple\module\app\shamap - + ripple\module\app\shamap - + ripple\module\app\shamap @@ -4650,6 +4617,9 @@ ripple\types\api + + ripple\types\api + ripple\types\api @@ -4671,7 +4641,7 @@ ripple\types\impl - + ripple\types\impl diff --git a/src/ripple/module/app/book/Taker.h b/src/ripple/module/app/book/Taker.h index 580472f451..3d504431f1 100644 --- a/src/ripple/module/app/book/Taker.h +++ b/src/ripple/module/app/book/Taker.h @@ -70,7 +70,6 @@ private: // The amounts still left over for us to try and take. Amounts m_remain; -private: Amounts flow (Amounts amount, Offer const& offer, Account const& taker); diff --git a/src/ripple/module/app/book/Types.h b/src/ripple/module/app/book/Types.h index 73b39af375..8de49a2754 100644 --- a/src/ripple/module/app/book/Types.h +++ b/src/ripple/module/app/book/Types.h @@ -30,38 +30,6 @@ namespace ripple { namespace core { -namespace detail { - -class AccountTag {}; -class CurrencyTag {}; - -} // detail - -typedef base_uint<160, detail::AccountTag> Account; -typedef base_uint<160, detail::CurrencyTag> Currency; - -inline std::string to_string(Currency const& c) -{ - return STAmount::createHumanCurrency(c); -} - -inline std::string to_string(Account const& a) -{ - return RippleAddress::createHumanAccountID(a); -} - -inline std::ostream& operator<< (std::ostream& os, Account const& x) -{ - os << to_string (x); - return os; -} - -inline std::ostream& operator<< (std::ostream& os, Currency const& x) -{ - os << to_string (x); - return os; -} - /** A mutable view that overlays an immutable ledger to track changes. */ typedef LedgerEntrySet LedgerView; @@ -85,12 +53,6 @@ public: }; } // core - -inline bool isXRP(core::Currency const& c) -{ - return c == zero; -} - } // ripple #endif diff --git a/src/ripple/module/app/book/impl/Types.cpp b/src/ripple/module/app/book/impl/Types.cpp deleted file mode 100644 index ca2aaa4bc4..0000000000 --- a/src/ripple/module/app/book/impl/Types.cpp +++ /dev/null @@ -1,29 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2014 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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 - -namespace ripple { -namespace core { - -const path::Account XRP_ACCOUNT(0); -const path::Currency XRP_CURRENCY(0); - -} -} diff --git a/src/ripple/module/app/book/tests/Quality.test.cpp b/src/ripple/module/app/book/tests/Quality.test.cpp index 5e8813012e..6e5eac3772 100644 --- a/src/ripple/module/app/book/tests/Quality.test.cpp +++ b/src/ripple/module/app/book/tests/Quality.test.cpp @@ -32,7 +32,7 @@ public: Amount static raw (std::uint64_t mantissa, int exponent) { - return Amount (uint160(3), uint160(3), mantissa, exponent); + return Amount (Currency(3), Account(3), mantissa, exponent); } template diff --git a/src/ripple/module/app/consensus/DisputedTx.cpp b/src/ripple/module/app/consensus/DisputedTx.cpp index 4a4a92be6c..12310e1c6a 100644 --- a/src/ripple/module/app/consensus/DisputedTx.cpp +++ b/src/ripple/module/app/consensus/DisputedTx.cpp @@ -22,30 +22,31 @@ namespace ripple { // #define TRUST_NETWORK // Track a peer's yes/no vote on a particular disputed transaction -void DisputedTx::setVote (const uint160& peer, bool votesYes) +void DisputedTx::setVote (NodeID const& peer, bool votesYes) { - // VFALCO TODO Simplify this declaration. It doesn't exactly roll off the tongue! - std::pair ::iterator, bool> res = - mVotes.insert (std::make_pair (peer, votesYes)); + auto res = mVotes.insert (std::make_pair (peer, votesYes)); // new vote if (res.second) { if (votesYes) { - WriteLog (lsDEBUG, LedgerConsensus) << "Peer " << peer << " votes YES on " << mTransactionID; + WriteLog (lsDEBUG, LedgerConsensus) + << "Peer " << peer << " votes YES on " << mTransactionID; ++mYays; } else { - WriteLog (lsDEBUG, LedgerConsensus) << "Peer " << peer << " votes NO on " << mTransactionID; + WriteLog (lsDEBUG, LedgerConsensus) + << "Peer " << peer << " votes NO on " << mTransactionID; ++mNays; } } // changes vote to yes else if (votesYes && !res.first->second) { - WriteLog (lsDEBUG, LedgerConsensus) << "Peer " << peer << " now votes YES on " << mTransactionID; + WriteLog (lsDEBUG, LedgerConsensus) + << "Peer " << peer << " now votes YES on " << mTransactionID; --mNays; ++mYays; res.first->second = true; @@ -53,7 +54,8 @@ void DisputedTx::setVote (const uint160& peer, bool votesYes) // changes vote to no else if (!votesYes && res.first->second) { - WriteLog (lsDEBUG, LedgerConsensus) << "Peer " << peer << " now votes NO on " << mTransactionID; + WriteLog (lsDEBUG, LedgerConsensus) << "Peer " << peer + << " now votes NO on " << mTransactionID; ++mNays; --mYays; res.first->second = false; @@ -61,9 +63,9 @@ void DisputedTx::setVote (const uint160& peer, bool votesYes) } // Remove a peer's vote on this disputed transasction -void DisputedTx::unVote (const uint160& peer) +void DisputedTx::unVote (NodeID const& peer) { - ripple::unordered_map::iterator it = mVotes.find (peer); + auto it = mVotes.find (peer); if (it != mVotes.end ()) { @@ -95,10 +97,12 @@ bool DisputedTx::updateVote (int percentTime, bool proposing) // This is basically the percentage of nodes voting 'yes' (including us) weight = (mYays * 100 + (mOurVote ? 100 : 0)) / (mNays + mYays + 1); - // VFALCO TODO Rename these macros and turn them into language constructs. - // consolidate them into a class that collects all these related values. + // VFALCO TODO Rename these macros and turn them into language + // constructs. consolidate them into a class that collects + // all these related values. // - // To prevent avalanche stalls, we increase the needed weight slightly over time + // To prevent avalanche stalls, we increase the needed weight slightly + // over time. if (percentTime < AV_MID_CONSENSUS_TIME) newPosition = weight > AV_INIT_CONSENSUS_PCT; else if (percentTime < AV_LATE_CONSENSUS_TIME) @@ -116,14 +120,17 @@ bool DisputedTx::updateVote (int percentTime, bool proposing) if (newPosition == mOurVote) { - WriteLog (lsINFO, LedgerConsensus) << - "No change (" << (mOurVote ? "YES" : "NO") << ") : weight " << weight << ", percent " << percentTime; + WriteLog (lsINFO, LedgerConsensus) + << "No change (" << (mOurVote ? "YES" : "NO") << ") : weight " + << weight << ", percent " << percentTime; WriteLog (lsDEBUG, LedgerConsensus) << getJson (); return false; } mOurVote = newPosition; - WriteLog (lsDEBUG, LedgerConsensus) << "We now vote " << (mOurVote ? "YES" : "NO") << " on " << mTransactionID; + WriteLog (lsDEBUG, LedgerConsensus) + << "We now vote " << (mOurVote ? "YES" : "NO") + << " on " << mTransactionID; WriteLog (lsDEBUG, LedgerConsensus) << getJson (); return true; } @@ -140,9 +147,7 @@ Json::Value DisputedTx::getJson () { Json::Value votesj (Json::objectValue); for (auto& vote : mVotes) - { votesj[to_string (vote.first)] = vote.second; - } ret["votes"] = votesj; } @@ -150,4 +155,3 @@ Json::Value DisputedTx::getJson () } } // ripple - diff --git a/src/ripple/module/app/consensus/DisputedTx.h b/src/ripple/module/app/consensus/DisputedTx.h index 35c9de5e35..7278088b34 100644 --- a/src/ripple/module/app/consensus/DisputedTx.h +++ b/src/ripple/module/app/consensus/DisputedTx.h @@ -66,8 +66,8 @@ public: // VFALCO NOTE its not really a peer, its the 160 bit hash of the validator's public key // - void setVote (uint160 const& peer, bool votesYes); - void unVote (uint160 const& peer); + void setVote (NodeID const& peer, bool votesYes); + void unVote (NodeID const& peer); bool updateVote (int percentTime, bool proposing); Json::Value getJson (); @@ -78,12 +78,10 @@ private: int mNays; bool mOurVote; Serializer transaction; - ripple::unordered_map mVotes; + + ripple::unordered_map mVotes; }; -// VFALCO TODO Rename and put these in a tidy place -typedef std::map::value_type u256_lct_pair; -typedef std::map::value_type u160_prop_pair; #define LEDGER_TOTAL_PASSES 8 #define LEDGER_RETRY_PASSES 5 diff --git a/src/ripple/module/app/consensus/LedgerConsensus.cpp b/src/ripple/module/app/consensus/LedgerConsensus.cpp index 053f64fc22..6d420831e0 100644 --- a/src/ripple/module/app/consensus/LedgerConsensus.cpp +++ b/src/ripple/module/app/consensus/LedgerConsensus.cpp @@ -18,6 +18,7 @@ //============================================================================== #include +#include namespace ripple { @@ -340,7 +341,7 @@ public: mAcquiring.erase (hash); // Adjust tracking for each peer that takes this position - std::vector peers; + std::vector peers; for (auto& it : mPeerPositions) { if (it.second->getCurrentHash () == map->getHash ()) @@ -392,7 +393,7 @@ public: if (mHaveCorrectLCL) priorLedger = mPreviousLedger->getParentHash (); // don't jump back - ripple::unordered_map vals = + ripple::unordered_map vals = getApp().getValidations ().getCurrentValidations (favoredLedger, priorLedger); @@ -701,7 +702,7 @@ public: */ bool peerPosition (LedgerProposal::ref newPosition) { - uint160 peerID = newPosition->getPeerID (); + auto peerID = newPosition->getPeerID (); if (mDeadNodes.find (peerID) != mDeadNodes.end ()) { @@ -761,8 +762,6 @@ public: { WriteLog (lsDEBUG, LedgerConsensus) << "Don't have tx set for peer"; - // BOOST_FOREACH(u256_lct_pair& it, mDisputes) - // it.second->unVote(peerID); } return true; @@ -1194,7 +1193,7 @@ private: /** Adjust the counts on all disputed transactions based on the set of peers taking this position */ - void adjustCount (SHAMap::ref map, const std::vector& peers) + void adjustCount (SHAMap::ref map, const std::vector& peers) { for (auto& it : mDisputes) { @@ -1380,7 +1379,7 @@ private: return resultSuccess; } - if (isTefFailure (result) || isTemMalformed (result) || + if (isTefFailure (result) || isTemMalformed (result) || isTelLocal (result)) { // failure @@ -1696,15 +1695,10 @@ private: */ void playbackProposals () { - ripple::unordered_map < uint160, - std::list > & storedProposals - = getApp().getOPs ().peekStoredProposals (); - - for (auto it = storedProposals.begin () - , end = storedProposals.end (); it != end; ++it) + for (auto it: getApp().getOPs ().peekStoredProposals ()) { bool relay = false; - for (auto proposal : it->second) + for (auto proposal : it.second) { if (proposal->hasSignature ()) { @@ -1892,7 +1886,7 @@ private: int mPreviousMSeconds; // Convergence tracking, trusted peers indexed by hash of public key - ripple::unordered_map mPeerPositions; + ripple::unordered_map mPeerPositions; // Transaction Sets, indexed by hash of transaction tree ripple::unordered_map mAcquired; @@ -1910,7 +1904,7 @@ private: std::map mCloseTimes; // nodes that have bowed out of this consensus process - boost::unordered_set mDeadNodes; + NodeIDSet mDeadNodes; }; //------------------------------------------------------------------------------ diff --git a/src/ripple/module/app/contracts/Contract.cpp b/src/ripple/module/app/contracts/Contract.cpp deleted file mode 100644 index 782a291d88..0000000000 --- a/src/ripple/module/app/contracts/Contract.cpp +++ /dev/null @@ -1,48 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -namespace ripple { - -Contract::Contract () -{ - -} - - -void Contract::executeCreate () -{ - -} -void Contract::executeRemove () -{ - -} -void Contract::executeFund () -{ - -} -void Contract::executeAccept () -{ - //std::vector code; - - //Interpreter interpreter; - //interpreter.interpret(this,code); -} - -} // ripple diff --git a/src/ripple/module/app/contracts/Contract.h b/src/ripple/module/app/contracts/Contract.h deleted file mode 100644 index bd6d508ea2..0000000000 --- a/src/ripple/module/app/contracts/Contract.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -#ifndef CONTRACT_H -#define CONTRACT_H - -namespace ripple { - -class Contract -{ -public: - Contract (); - - uint160& getIssuer (); - uint160& getOwner (); - STAmount& getRippleEscrow (); - std::uint32_t getEscrow (); - std::uint32_t getBond (); - - Script::Data getData (int index); - - void executeCreate (); - void executeRemove (); - void executeFund (); - void executeAccept (); -}; - -} // ripple - -#endif diff --git a/src/ripple/module/app/contracts/Interpreter.cpp b/src/ripple/module/app/contracts/Interpreter.cpp deleted file mode 100644 index bdbd06474c..0000000000 --- a/src/ripple/module/app/contracts/Interpreter.cpp +++ /dev/null @@ -1,228 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -namespace ripple { - -namespace Script -{ - -Interpreter::Interpreter () -{ - mContract = nullptr; - mCode = nullptr; - mInstructionPointer = 0; - mTotalFee = 0; - - mInBlock = false; - mBlockSuccess = true; - mBlockJump = 0; - - mFunctionTable.resize (NUM_OF_OPS); - - mFunctionTable[INT_OP] = new IntOp (); - mFunctionTable[FLOAT_OP] = new FloatOp (); - mFunctionTable[UINT160_OP] = new Uint160Op (); - mFunctionTable[BOOL_OP] = new Uint160Op (); - mFunctionTable[PATH_OP] = new Uint160Op (); - - mFunctionTable[ADD_OP] = new AddOp (); - mFunctionTable[SUB_OP] = new SubOp (); - mFunctionTable[MUL_OP] = new MulOp (); - mFunctionTable[DIV_OP] = new DivOp (); - mFunctionTable[MOD_OP] = new ModOp (); - mFunctionTable[GTR_OP] = new GtrOp (); - mFunctionTable[LESS_OP] = new LessOp (); - mFunctionTable[EQUAL_OP] = new SubOp (); - mFunctionTable[NOT_EQUAL_OP] = new SubOp (); - mFunctionTable[AND_OP] = new SubOp (); - mFunctionTable[OR_OP] = new SubOp (); - mFunctionTable[NOT_OP] = new SubOp (); - mFunctionTable[JUMP_OP] = new SubOp (); - mFunctionTable[JUMPIF_OP] = new SubOp (); - mFunctionTable[STOP_OP] = new SubOp (); - mFunctionTable[CANCEL_OP] = new SubOp (); - mFunctionTable[BLOCK_OP] = new SubOp (); - mFunctionTable[BLOCK_END_OP] = new SubOp (); - mFunctionTable[SEND_XRP_OP] = new SendXRPOp (); - /* - mFunctionTable[SEND_OP]=new SendOp(); - mFunctionTable[REMOVE_CONTRACT_OP]=new SubOp(); - mFunctionTable[FEE_OP]=new SubOp(); - mFunctionTable[CHANGE_CONTRACT_OWNER_OP]=new SubOp(); - mFunctionTable[STOP_REMOVE_OP]=new SubOp(); - mFunctionTable[SET_DATA_OP]=new SubOp(); - mFunctionTable[GET_DATA_OP]=new SubOp(); - mFunctionTable[GET_NUM_DATA_OP]=new SubOp(); - mFunctionTable[SET_REGISTER_OP]=new SubOp(); - mFunctionTable[GET_REGISTER_OP]=new SubOp(); - mFunctionTable[GET_ISSUER_ID_OP]=new SubOp(); - mFunctionTable[GET_OWNER_ID_OP]=new SubOp(); - mFunctionTable[GET_LEDGER_TIME_OP]=new SubOp(); - mFunctionTable[GET_LEDGER_NUM_OP]=new SubOp(); - mFunctionTable[GET_RAND_FLOAT_OP]=new SubOp(); - mFunctionTable[GET_XRP_ESCROWED_OP]=new SubOp(); - mFunctionTable[GET_RIPPLE_ESCROWED_OP]=new SubOp(); - mFunctionTable[GET_RIPPLE_ESCROWED_CURRENCY_OP]=new SubOp(); - mFunctionTable[GET_RIPPLE_ESCROWED_ISSUER]=new GetRippleEscrowedIssuerOp(); - mFunctionTable[GET_ACCEPT_DATA_OP]=new AcceptDataOp(); - mFunctionTable[GET_ACCEPTOR_ID_OP]=new GetAcceptorIDOp(); - mFunctionTable[GET_CONTRACT_ID_OP]=new GetContractIDOp(); - */ - -} - -Data::pointer Interpreter::popStack () -{ - if (mStack.size ()) - { - Data::pointer item = mStack[mStack.size () - 1]; - mStack.pop_back (); - return (item); - } - else - { - return (Data::pointer (new ErrorData ())); - } -} - -void Interpreter::pushStack (Data::pointer data) -{ - mStack.push_back (data); -} - - -// offset is where to jump to if the block fails -bool Interpreter::startBlock (int offset) -{ - if (mInBlock) return (false); // can't nest blocks - - mBlockSuccess = true; - mInBlock = true; - mBlockJump = offset + mInstructionPointer; - return (true); -} - -bool Interpreter::endBlock () -{ - if (!mInBlock) return (false); - - mInBlock = false; - mBlockJump = 0; - pushStack (Data::pointer (new BoolData (mBlockSuccess))); - return (true); -} - -TER Interpreter::interpret (Contract* contract, const SerializedTransaction& txn, Blob& code) -{ - mContract = contract; - mCode = &code; - mTotalFee = 0; - mInstructionPointer = 0; - - while (mInstructionPointer < code.size ()) - { - unsigned int fun = (*mCode)[mInstructionPointer]; - mInstructionPointer++; - - if (fun >= mFunctionTable.size ()) - { - // TODO: log - return (temMALFORMED); // TODO: is this actually what we want to do? - } - - mTotalFee += mFunctionTable[ fun ]->getFee (); // FIXME: You can't use fees this way, there's no consensus - - if (mTotalFee > txn.getTransactionFee ().getNValue ()) - { - // TODO: log - return (telINSUF_FEE_P); - } - else - { - if (!mFunctionTable[ fun ]->work (this)) - { - // TODO: log - return (temMALFORMED); // TODO: is this actually what we want to do? - } - } - } - - return (tesSUCCESS); -} - - -Data::pointer Interpreter::getIntData () -{ - int value = 0; // TODO - mInstructionPointer += 4; - return (Data::pointer (new IntData (value))); -} - -Data::pointer Interpreter::getFloatData () -{ - float value = 0; // TODO - mInstructionPointer += 4; - return (Data::pointer (new FloatData (value))); -} - -Data::pointer Interpreter::getUint160Data () -{ - uint160 value; // TODO - mInstructionPointer += 20; - return (Data::pointer (new Uint160Data (value))); -} - - - -bool Interpreter::jumpTo (int offset) -{ - if (offset < 0) - { - if (-offset > mInstructionPointer) - return false; - } - else - { - if (offset > mCode->size () || - mInstructionPointer > mCode->size () - offset) - return false; - } - - mInstructionPointer += offset; - return (true); -} - -void Interpreter::stop () -{ - mInstructionPointer = mCode->size (); -} - -Data::pointer Interpreter::getContractData (int index) -{ - return (Data::pointer (new ErrorData ())); -} - -bool Interpreter::canSign (const uint160& signer) -{ - return (true); -} - -} - -} // ripple diff --git a/src/ripple/module/app/contracts/Interpreter.h b/src/ripple/module/app/contracts/Interpreter.h deleted file mode 100644 index 5c9dc7b8a4..0000000000 --- a/src/ripple/module/app/contracts/Interpreter.h +++ /dev/null @@ -1,102 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -#ifndef INTERPRETER_H -#define INTERPRETER_H - -namespace ripple { - -namespace Script { - -class Operation; -// Contracts are non typed have variable data types - -class Interpreter -{ - std::vector mFunctionTable; - - std::vector mStack; - - Contract* mContract; - Blob* mCode; - unsigned int mInstructionPointer; - int mTotalFee; - - bool mInBlock; - int mBlockJump; - bool mBlockSuccess; - -public: - - - enum { INT_OP = 1, FLOAT_OP, UINT160_OP, BOOL_OP, PATH_OP, - ADD_OP, SUB_OP, MUL_OP, DIV_OP, MOD_OP, - GTR_OP, LESS_OP, EQUAL_OP, NOT_EQUAL_OP, - AND_OP, OR_OP, NOT_OP, - JUMP_OP, JUMPIF_OP, - STOP_OP, CANCEL_OP, - - BLOCK_OP, BLOCK_END_OP, - SEND_XRP_OP, SEND_OP, REMOVE_CONTRACT_OP, FEE_OP, CHANGE_CONTRACT_OWNER_OP, - STOP_REMOVE_OP, - SET_DATA_OP, GET_DATA_OP, GET_NUM_DATA_OP, - SET_REGISTER_OP, GET_REGISTER_OP, - GET_ISSUER_ID_OP, GET_OWNER_ID_OP, GET_LEDGER_TIME_OP, GET_LEDGER_NUM_OP, GET_RAND_FLOAT_OP, - GET_XRP_ESCROWED_OP, GET_RIPPLE_ESCROWED_OP, GET_RIPPLE_ESCROWED_CURRENCY_OP, GET_RIPPLE_ESCROWED_ISSUER, - GET_ACCEPT_DATA_OP, GET_ACCEPTOR_ID_OP, GET_CONTRACT_ID_OP, - NUM_OF_OPS - }; - - Interpreter (); - - // returns a TransactionEngineResult - TER interpret (Contract* contract, const SerializedTransaction& txn, Blob& code); - - void stop (); - - bool canSign (const uint160& signer); - - int getInstructionPointer () - { - return (mInstructionPointer); - } - void setInstructionPointer (int n) - { - mInstructionPointer = n; - } - - Data::pointer popStack (); - void pushStack (Data::pointer data); - bool jumpTo (int offset); - - bool startBlock (int offset); - bool endBlock (); - - Data::pointer getIntData (); - Data::pointer getFloatData (); - Data::pointer getUint160Data (); - Data::pointer getAcceptData (int index); - Data::pointer getContractData (int index); -}; - -} // end namespace - -} // ripple - -#endif diff --git a/src/ripple/module/app/contracts/Operation.cpp b/src/ripple/module/app/contracts/Operation.cpp deleted file mode 100644 index 8614e80291..0000000000 --- a/src/ripple/module/app/contracts/Operation.cpp +++ /dev/null @@ -1,38 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -/* -We also need to charge for each op - -*/ - -namespace ripple { - -namespace Script -{ - - -int Operation::getFee () -{ - return (getConfig ().FEE_CONTRACT_OPERATION); -} - -} - -} // ripple diff --git a/src/ripple/module/app/contracts/Operation.h b/src/ripple/module/app/contracts/Operation.h deleted file mode 100644 index 6bb1f96e92..0000000000 --- a/src/ripple/module/app/contracts/Operation.h +++ /dev/null @@ -1,380 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -#ifndef OPERATION_H -#define OPERATION_H - -namespace ripple { - -namespace Script { - -// Contracts are non typed have variable data types - - -class Operation -{ -public: - // returns false if there was an error - virtual bool work (Interpreter* interpreter) = 0; - - virtual int getFee (); - - virtual ~Operation () - { - ; - } -}; - -// this is just an Int in the code -class IntOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data = interpreter->getIntData (); - - if (data->isInt32 ()) - { - interpreter->pushStack ( data ); - return (true); - } - - return (false); - } -}; - -class FloatOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data = interpreter->getFloatData (); - - if (data->isFloat ()) - { - interpreter->pushStack ( data ); - return (true); - } - - return (false); - } -}; - -class Uint160Op : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data = interpreter->getUint160Data (); - - if (data->isUint160 ()) - { - interpreter->pushStack ( data ); - return (true); - } - - return (false); - } -}; - -class AddOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( (data1->isInt32 () || data1->isFloat ()) && - (data2->isInt32 () || data2->isFloat ()) ) - { - if (data1->isFloat () || data2->isFloat ()) interpreter->pushStack (Data::pointer (new FloatData (data1->getFloat () + data2->getFloat ()))); - else interpreter->pushStack (Data::pointer (new IntData (data1->getInt () + data2->getInt ()))); - - return (true); - } - else - { - return (false); - } - } -}; - -class SubOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( (data1->isInt32 () || data1->isFloat ()) && - (data2->isInt32 () || data2->isFloat ()) ) - { - if (data1->isFloat () || data2->isFloat ()) interpreter->pushStack (Data::pointer (new FloatData (data1->getFloat () - data2->getFloat ()))); - else interpreter->pushStack (Data::pointer (new IntData (data1->getInt () - data2->getInt ()))); - - return (true); - } - else - { - return (false); - } - } -}; - -class MulOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( (data1->isInt32 () || data1->isFloat ()) && - (data2->isInt32 () || data2->isFloat ()) ) - { - if (data1->isFloat () || data2->isFloat ()) interpreter->pushStack (Data::pointer (new FloatData (data1->getFloat ()*data2->getFloat ()))); - else interpreter->pushStack (Data::pointer (new IntData (data1->getInt ()*data2->getInt ()))); - - return (true); - } - else - { - return (false); - } - } -}; - -class DivOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( (data1->isInt32 () || data1->isFloat ()) && - (data2->isInt32 () || data2->isFloat ()) ) - { - if (data1->isFloat () || data2->isFloat ()) interpreter->pushStack (Data::pointer (new FloatData (data1->getFloat () / data2->getFloat ()))); - else interpreter->pushStack (Data::pointer (new IntData (data1->getInt () / data2->getInt ()))); - - return (true); - } - else - { - return (false); - } - } -}; - -class GtrOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( (data1->isInt32 () || data1->isFloat ()) && - (data2->isInt32 () || data2->isFloat ()) ) - { - interpreter->pushStack (Data::pointer (new BoolData (data1->getFloat () > data2->getFloat ()))); - return (true); - } - else - { - return (false); - } - } -}; - -class LessOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( (data1->isInt32 () || data1->isFloat ()) && - (data2->isInt32 () || data2->isFloat ()) ) - { - interpreter->pushStack (Data::pointer (new FloatData (data1->getFloat () < data2->getFloat ()))); - return (true); - } - else - { - return (false); - } - } -}; - -class ModOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data1 = interpreter->popStack (); - Data::pointer data2 = interpreter->popStack (); - - if ( data1->isInt32 () && data2->isInt32 () ) - { - interpreter->pushStack (Data::pointer (new IntData (data1->getInt () % data2->getInt ()))); - return (true); - } - else - { - return (false); - } - } -}; - - -class StartBlockOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer offset = interpreter->getIntData (); - return (interpreter->startBlock (offset->getInt ())); - } -}; - -class EndBlockOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - return (interpreter->endBlock ()); - } -}; - -class StopOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - interpreter->stop (); - return (true); - } -}; - -class AcceptDataOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer data = interpreter->popStack (); - - if (data->isInt32 ()) - { - interpreter->pushStack ( interpreter->getAcceptData (data->getInt ()) ); - return (true); - } - - return (false); - } -}; - -class JumpIfOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer offset = interpreter->getIntData (); - Data::pointer cond = interpreter->popStack (); - - if (cond->isBool () && offset->isInt32 ()) - { - if (cond->isTrue ()) - { - return (interpreter->jumpTo (offset->getInt ())); - } - - return (true); - } - - return (false); - } -}; - -class JumpOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer offset = interpreter->getIntData (); - - if (offset->isInt32 ()) - { - return (interpreter->jumpTo (offset->getInt ())); - } - - return (false); - } -}; - -class SendXRPOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer sourceID = interpreter->popStack (); - Data::pointer destID = interpreter->popStack (); - Data::pointer amount = interpreter->popStack (); - - if (sourceID->isUint160 () && destID->isUint160 () && amount->isInt32 () && interpreter->canSign (sourceID->getUint160 ())) - { - // make sure: - // source is either, this contract, issuer, or acceptor - - // TODO do the send - //interpreter->pushStack( send result); - - return (true); - } - - return (false); - } -}; - -class GetDataOp : public Operation -{ -public: - bool work (Interpreter* interpreter) - { - Data::pointer index = interpreter->popStack (); - - if (index->isInt32 ()) - { - interpreter->pushStack ( interpreter->getContractData (index->getInt ())); - return (true); - } - - return (false); - } -}; - -} - -} // ripple - -#endif diff --git a/src/ripple/module/app/contracts/ScriptData.cpp b/src/ripple/module/app/contracts/ScriptData.cpp deleted file mode 100644 index 5f37c43da7..0000000000 --- a/src/ripple/module/app/contracts/ScriptData.cpp +++ /dev/null @@ -1,22 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -namespace ripple { - -} // ripple diff --git a/src/ripple/module/app/contracts/ScriptData.h b/src/ripple/module/app/contracts/ScriptData.h deleted file mode 100644 index 0fbd6cd657..0000000000 --- a/src/ripple/module/app/contracts/ScriptData.h +++ /dev/null @@ -1,186 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -#ifndef SCRIPT_DATA_H -#define SCRIPT_DATA_H - -namespace ripple { - -namespace Script -{ -class Data -{ -public: - typedef std::shared_ptr pointer; - - virtual ~Data () - { - ; - } - - virtual bool isInt32 () - { - return (false); - } - virtual bool isFloat () - { - return (false); - } - virtual bool isUint160 () - { - return (false); - } - virtual bool isError () - { - return (false); - } - virtual bool isTrue () - { - return (false); - } - virtual bool isBool () - { - return (false); - } - //virtual bool isBlockEnd(){ return(false); } - - virtual int getInt () - { - return (0); - } - virtual float getFloat () - { - return (0); - } - virtual uint160 getUint160 () - { - return uint160(0); - } - - //virtual bool isCurrency(){ return(false); } -}; - -class IntData : public Data -{ - int mValue; -public: - IntData (int value) - { - mValue = value; - } - bool isInt32 () - { - return (true); - } - int getInt () - { - return (mValue); - } - float getFloat () - { - return ((float)mValue); - } - bool isTrue () - { - return (mValue != 0); - } -}; - -class FloatData : public Data -{ - float mValue; -public: - FloatData (float value) - { - mValue = value; - } - bool isFloat () - { - return (true); - } - float getFloat () - { - return (mValue); - } - bool isTrue () - { - return (mValue != 0); - } -}; - -class Uint160Data : public Data -{ - uint160 mValue; -public: - Uint160Data (uint160 value) : mValue (value) - { - ; - } - bool isUint160 () - { - return (true); - } - uint160 getUint160 () - { - return (mValue); - } -}; - -class BoolData : public Data -{ - bool mValue; -public: - BoolData (bool value) - { - mValue = value; - } - bool isBool () - { - return (true); - } - bool isTrue () - { - return (mValue); - } -}; - -class ErrorData : public Data -{ -public: - bool isError () - { - return (true); - } -}; - -class BlockEndData : public Data -{ -public: - bool isBlockEnd () - { - return (true); - } -}; - - -} - -} // ripple - -#endif diff --git a/src/ripple/module/app/ledger/Ledger.cpp b/src/ripple/module/app/ledger/Ledger.cpp index 975b9dfed5..2ee9f574e0 100644 --- a/src/ripple/module/app/ledger/Ledger.cpp +++ b/src/ripple/module/app/ledger/Ledger.cpp @@ -46,20 +46,22 @@ Ledger::Ledger (const RippleAddress& masterID, std::uint64_t startAmount) std::ref (getApp().getFullBelowCache()))) { // special case: put coins in root account - AccountState::pointer startAccount = std::make_shared (masterID); + auto startAccount = std::make_shared (masterID); + auto& sle = startAccount->peekSLE (); + sle.setFieldAmount (sfBalance, startAmount); + sle.setFieldU32 (sfSequence, 1); - startAccount->peekSLE ().setFieldAmount (sfBalance, startAmount); - - startAccount->peekSLE ().setFieldU32 (sfSequence, 1); - - WriteLog (lsTRACE, Ledger) << "root account: " << startAccount->peekSLE ().getJson (0); + WriteLog (lsTRACE, Ledger) + << "root account: " << startAccount->peekSLE ().getJson (0); mAccountStateMap->armDirty (); writeBack (lepCREATE, startAccount->getSLE ()); auto dirtyNodes = mAccountStateMap->disarmDirty(); - mAccountStateMap->flushDirty (*dirtyNodes, 256, hotACCOUNT_NODE, mLedgerSeq); + mAccountStateMap->flushDirty ( + *dirtyNodes, 256, hotACCOUNT_NODE, mLedgerSeq); + // TODO(tom): why 256? initializeFees (); } @@ -96,13 +98,15 @@ Ledger::Ledger (uint256 const& parentHash, updateHash (); loaded = true; - if (mTransHash.isNonZero () && !mTransactionMap->fetchRoot (mTransHash, nullptr)) + if (mTransHash.isNonZero () && + !mTransactionMap->fetchRoot (mTransHash, nullptr)) { loaded = false; WriteLog (lsWARNING, Ledger) << "Don't have TX root for ledger"; } - if (mAccountHash.isNonZero () && !mAccountStateMap->fetchRoot (mAccountHash, nullptr)) + if (mAccountHash.isNonZero () && + !mAccountStateMap->fetchRoot (mAccountHash, nullptr)) { loaded = false; WriteLog (lsWARNING, Ledger) << "Don't have AS root for ledger"; @@ -166,7 +170,8 @@ Ledger::Ledger (bool /* dummy */, if (prevLedger.mCloseTime == 0) { - mCloseTime = roundCloseTime (getApp().getOPs ().getCloseTimeNC (), mCloseResolution); + mCloseTime = roundCloseTime ( + getApp().getOPs ().getCloseTimeNC (), mCloseResolution); } else { @@ -319,12 +324,14 @@ void Ledger::addRaw (Serializer& s) const s.add8 (mCloseFlags); } -void Ledger::setAccepted (std::uint32_t closeTime, int closeResolution, bool correctCloseTime) +void Ledger::setAccepted ( + std::uint32_t closeTime, int closeResolution, bool correctCloseTime) { - // used when we witnessed the consensus - // Rounds the close time, updates the hash, and sets the ledger accepted and immutable + // Used when we witnessed the consensus. Rounds the close time, updates the + // hash, and sets the ledger accepted and immutable. assert (mClosed && !mAccepted); - mCloseTime = correctCloseTime ? roundCloseTime (closeTime, closeResolution) : closeTime; + mCloseTime = correctCloseTime ? roundCloseTime (closeTime, closeResolution) + : closeTime; mCloseResolution = closeResolution; mCloseFlags = correctCloseTime ? 0 : sLCF_NoConsensusTime; mAccepted = true; @@ -374,17 +381,17 @@ AccountState::pointer Ledger::getAccountState (const RippleAddress& accountID) NicknameState::pointer Ledger::getNicknameState (uint256 const& uNickname) { - SHAMapItem::pointer item = mAccountStateMap->peekItem (Ledger::getNicknameIndex (uNickname)); + auto item = mAccountStateMap->peekItem ( + Ledger::getNicknameIndex (uNickname)); if (!item) - { return NicknameState::pointer (); - } - SerializedLedgerEntry::pointer sle = - std::make_shared (item->peekSerializer (), item->getTag ()); + auto sle = std::make_shared ( + item->peekSerializer (), item->getTag ()); - if (sle->getType () != ltNICKNAME) return NicknameState::pointer (); + if (sle->getType () != ltNICKNAME) + return NicknameState::pointer (); return std::make_shared (sle); } @@ -392,11 +399,12 @@ NicknameState::pointer Ledger::getNicknameState (uint256 const& uNickname) bool Ledger::addTransaction (uint256 const& txID, const Serializer& txn) { // low-level - just add to table - SHAMapItem::pointer item = std::make_shared (txID, txn.peekData ()); + auto item = std::make_shared (txID, txn.peekData ()); if (!mTransactionMap->addGiveItem (item, true, false)) { - WriteLog (lsWARNING, Ledger) << "Attempt to add transaction to ledger that already had it"; + WriteLog (lsWARNING, Ledger) + << "Attempt to add transaction to ledger that already had it"; return false; } @@ -404,17 +412,19 @@ bool Ledger::addTransaction (uint256 const& txID, const Serializer& txn) return true; } -bool Ledger::addTransaction (uint256 const& txID, const Serializer& txn, const Serializer& md) +bool Ledger::addTransaction ( + uint256 const& txID, const Serializer& txn, const Serializer& md) { // low-level - just add to table Serializer s (txn.getDataLength () + md.getDataLength () + 16); s.addVL (txn.peekData ()); s.addVL (md.peekData ()); - SHAMapItem::pointer item = std::make_shared (txID, s.peekData ()); + auto item = std::make_shared (txID, s.peekData ()); if (!mTransactionMap->addGiveItem (item, true, true)) { - WriteLog (lsFATAL, Ledger) << "Attempt to add transaction+MD to ledger that already had it"; + WriteLog (lsFATAL, Ledger) + << "Attempt to add transaction+MD to ledger that already had it"; return false; } @@ -427,9 +437,10 @@ Transaction::pointer Ledger::getTransaction (uint256 const& transID) const SHAMapTreeNode::TNType type; SHAMapItem::pointer item = mTransactionMap->peekItem (transID, type); - if (!item) return Transaction::pointer (); + if (!item) + return Transaction::pointer (); - Transaction::pointer txn = getApp().getMasterTransaction ().fetch (transID, false); + auto txn = getApp().getMasterTransaction ().fetch (transID, false); if (txn) return txn; @@ -459,13 +470,15 @@ Transaction::pointer Ledger::getTransaction (uint256 const& transID) const return txn; } -SerializedTransaction::pointer Ledger::getSTransaction (SHAMapItem::ref item, SHAMapTreeNode::TNType type) +SerializedTransaction::pointer Ledger::getSTransaction ( + SHAMapItem::ref item, SHAMapTreeNode::TNType type) { SerializerIterator sit (item->peekSerializer ()); if (type == SHAMapTreeNode::tnTRANSACTION_NM) return std::make_shared (std::ref (sit)); - else if (type == SHAMapTreeNode::tnTRANSACTION_MD) + + if (type == SHAMapTreeNode::tnTRANSACTION_MD) { Serializer sTxn (sit.getVL ()); SerializerIterator tSit (sTxn); @@ -475,8 +488,9 @@ SerializedTransaction::pointer Ledger::getSTransaction (SHAMapItem::ref item, SH return SerializedTransaction::pointer (); } -SerializedTransaction::pointer Ledger::getSMTransaction (SHAMapItem::ref item, SHAMapTreeNode::TNType type, - TransactionMetaSet::pointer& txMeta) +SerializedTransaction::pointer Ledger::getSMTransaction ( + SHAMapItem::ref item, SHAMapTreeNode::TNType type, + TransactionMetaSet::pointer& txMeta) { SerializerIterator sit (item->peekSerializer ()); @@ -490,15 +504,18 @@ SerializedTransaction::pointer Ledger::getSMTransaction (SHAMapItem::ref item, S Serializer sTxn (sit.getVL ()); SerializerIterator tSit (sTxn); - txMeta = std::make_shared (item->getTag (), mLedgerSeq, sit.getVL ()); - return std::make_shared (std::ref (tSit)); + txMeta = std::make_shared ( + item->getTag (), mLedgerSeq, sit.getVL ()); + return std::make_shared (tSit); } txMeta.reset (); return SerializedTransaction::pointer (); } -bool Ledger::getTransaction (uint256 const& txID, Transaction::pointer& txn, TransactionMetaSet::pointer& meta) +bool Ledger::getTransaction ( + uint256 const& txID, Transaction::pointer& txn, + TransactionMetaSet::pointer& meta) { SHAMapTreeNode::TNType type; SHAMapItem::pointer item = mTransactionMap->peekItem (txID, type); @@ -526,7 +543,8 @@ bool Ledger::getTransaction (uint256 const& txID, Transaction::pointer& txn, Tra else it.getVL (); // skip transaction - meta = std::make_shared (txID, mLedgerSeq, it.getVL ()); + meta = std::make_shared ( + txID, mLedgerSeq, it.getVL ()); } else return false; @@ -538,7 +556,8 @@ bool Ledger::getTransaction (uint256 const& txID, Transaction::pointer& txn, Tra return true; } -bool Ledger::getTransactionMeta (uint256 const& txID, TransactionMetaSet::pointer& meta) +bool Ledger::getTransactionMeta ( + uint256 const& txID, TransactionMetaSet::pointer& meta) { SHAMapTreeNode::TNType type; SHAMapItem::pointer item = mTransactionMap->peekItem (txID, type); @@ -583,6 +602,7 @@ uint256 Ledger::getHash () bool Ledger::saveValidatedLedger (bool current) { + // TODO(tom): Fix this hard-coded SQL! WriteLog (lsTRACE, Ledger) << "saveValidatedLedger " << (current ? "" : "fromAcquire ") << getLedgerSeq (); static boost::format deleteLedger ("DELETE FROM Ledgers WHERE LedgerSeq = %u;"); static boost::format deleteTrans1 ("DELETE FROM Transactions WHERE LedgerSeq = %u;"); @@ -603,8 +623,10 @@ bool Ledger::saveValidatedLedger (bool current) if (getAccountHash () != mAccountStateMap->getHash ()) { - WriteLog (lsFATAL, Ledger) << "sAL: " << getAccountHash () << " != " << mAccountStateMap->getHash (); - WriteLog (lsFATAL, Ledger) << "saveAcceptedLedger: seq=" << mLedgerSeq << ", current=" << current; + WriteLog (lsFATAL, Ledger) << "sAL: " << getAccountHash () + << " != " << mAccountStateMap->getHash (); + WriteLog (lsFATAL, Ledger) << "saveAcceptedLedger: seq=" + << mLedgerSeq << ", current=" << current; assert (false); } @@ -615,7 +637,8 @@ bool Ledger::saveValidatedLedger (bool current) Serializer s (128); s.add32 (HashPrefix::ledgerMaster); addRaw (s); - getApp().getNodeStore ().store (hotLEDGER, mLedgerSeq, std::move (s.modData ()), mHash); + getApp().getNodeStore ().store ( + hotLEDGER, mLedgerSeq, std::move (s.modData ()), mHash); } AcceptedLedger::pointer aLedger; @@ -627,7 +650,9 @@ bool Ledger::saveValidatedLedger (bool current) { WriteLog (lsWARNING, Ledger) << "An accepted ledger was missing nodes"; getApp().getLedgerMaster().failedSave(mLedgerSeq, mHash); - { // Clients can now trust the database for information about this ledger sequence + { + // Clients can now trust the database for information about this + // ledger sequence. StaticScopedLockType sl (sPendingSaveLock); sPendingSaves.erase(getLedgerSeq()); } @@ -636,7 +661,8 @@ bool Ledger::saveValidatedLedger (bool current) { DeprecatedScopedLock sl (getApp().getLedgerDB ()->getDBLock ()); - getApp().getLedgerDB ()->getDB ()->executeSQL (boost::str (deleteLedger % mLedgerSeq)); + getApp().getLedgerDB ()->getDB ()->executeSQL ( + boost::str (deleteLedger % mLedgerSeq)); } { @@ -712,6 +738,7 @@ bool Ledger::saveValidatedLedger (bool current) { DeprecatedScopedLock sl (getApp().getLedgerDB ()->getDBLock ()); + // TODO(tom): ARG! getApp().getLedgerDB ()->getDB ()->executeSQL (boost::str (addLedger % to_string (getHash ()) % mLedgerSeq % to_string (mParentHash) % beast::lexicalCastThrow (mTotCoins) % mCloseTime % @@ -719,7 +746,9 @@ bool Ledger::saveValidatedLedger (bool current) to_string (mAccountHash) % to_string (mTransHash))); } - { // Clients can now trust the database for information about this ledger sequence + { + // Clients can now trust the database for information about this ledger + // sequence. StaticScopedLockType sl (sPendingSaveLock); sPendingSaves.erase(getLedgerSeq()); } @@ -735,10 +764,11 @@ Ledger::pointer Ledger::loadByIndex (std::uint32_t ledgerIndex) Database* db = getApp().getLedgerDB ()->getDB (); DeprecatedScopedLock sl (getApp().getLedgerDB ()->getDBLock ()); - SqliteStatement pSt (db->getSqliteDB (), "SELECT " - "LedgerHash,PrevHash,AccountSetHash,TransSetHash,TotalCoins," - "ClosingTime,PrevClosingTime,CloseTimeRes,CloseFlags,LedgerSeq" - " from Ledgers WHERE LedgerSeq = ?;"); + SqliteStatement pSt ( + db->getSqliteDB (), "SELECT " + "LedgerHash,PrevHash,AccountSetHash,TransSetHash,TotalCoins," + "ClosingTime,PrevClosingTime,CloseTimeRes,CloseFlags,LedgerSeq" + " from Ledgers WHERE LedgerSeq = ?;"); pSt.bind (1, ledgerIndex); ledger = getSQL1 (&pSt); @@ -760,10 +790,11 @@ Ledger::pointer Ledger::loadByHash (uint256 const& ledgerHash) Database* db = getApp().getLedgerDB ()->getDB (); DeprecatedScopedLock sl (getApp().getLedgerDB ()->getDBLock ()); - SqliteStatement pSt (db->getSqliteDB (), "SELECT " - "LedgerHash,PrevHash,AccountSetHash,TransSetHash,TotalCoins," - "ClosingTime,PrevClosingTime,CloseTimeRes,CloseFlags,LedgerSeq" - " from Ledgers WHERE LedgerHash = ?;"); + SqliteStatement pSt ( + db->getSqliteDB (), "SELECT " + "LedgerHash,PrevHash,AccountSetHash,TransSetHash,TotalCoins," + "ClosingTime,PrevClosingTime,CloseTimeRes,CloseFlags,LedgerSeq" + " from Ledgers WHERE LedgerHash = ?;"); pSt.bind (1, to_string (ledgerHash)); ledger = getSQL1 (&pSt); @@ -783,7 +814,7 @@ Ledger::pointer Ledger::loadByHash (uint256 const& ledgerHash) Ledger::pointer Ledger::loadByIndex (std::uint32_t ledgerIndex) { - // This is a low-level function with no caching + // This is a low-level function with no caching. std::string sql = "SELECT * from Ledgers WHERE LedgerSeq='"; sql.append (beast::lexicalCastThrow (ledgerIndex)); sql.append ("';"); @@ -792,7 +823,8 @@ Ledger::pointer Ledger::loadByIndex (std::uint32_t ledgerIndex) Ledger::pointer Ledger::loadByHash (uint256 const& ledgerHash) { - // This is a low-level function with no caching and only gets accepted ledgers + // This is a low-level function with no caching and only gets accepted + // ledgers. std::string sql = "SELECT * from Ledgers WHERE LedgerHash='"; sql.append (to_string (ledgerHash)); sql.append ("';"); @@ -837,8 +869,9 @@ Ledger::pointer Ledger::getSQL (const std::string& sql) // CAUTION: code below appears in two places bool loaded; - Ledger::pointer ret (new Ledger (prevHash, transHash, accountHash, totCoins, - closingTime, prevClosingTime, closeFlags, closeResolution, ledgerSeq, loaded)); + Ledger::pointer ret (new Ledger ( + prevHash, transHash, accountHash, totCoins, closingTime, + prevClosingTime, closeFlags, closeResolution, ledgerSeq, loaded)); if (!loaded) return Ledger::pointer (); @@ -878,7 +911,9 @@ Ledger::pointer Ledger::getSQL1 (SqliteStatement* stmt) if (!stmt->isRow (iRet)) { - WriteLog (lsINFO, Ledger) << "Ledger not found: " << iRet << " = " << stmt->getError (iRet); + WriteLog (lsINFO, Ledger) + << "Ledger not found: " << iRet + << " = " << stmt->getError (iRet); return Ledger::pointer (); } @@ -901,8 +936,9 @@ Ledger::pointer Ledger::getSQL1 (SqliteStatement* stmt) // CAUTION: code below appears in two places bool loaded; - Ledger::pointer ret (new Ledger (prevHash, transHash, accountHash, totCoins, - closingTime, prevClosingTime, closeFlags, closeResolution, ledgerSeq, loaded)); + Ledger::pointer ret (new Ledger ( + prevHash, transHash, accountHash, totCoins, closingTime, + prevClosingTime, closeFlags, closeResolution, ledgerSeq, loaded)); if (!loaded) return Ledger::pointer (); @@ -918,14 +954,16 @@ void Ledger::getSQL2 (Ledger::ref ret) if (getApp().getOPs ().haveLedger (ret->getLedgerSeq ())) ret->setAccepted (); - WriteLog (lsTRACE, Ledger) << "Loaded ledger: " << to_string (ret->getHash ()); + WriteLog (lsTRACE, Ledger) + << "Loaded ledger: " << to_string (ret->getHash ()); } uint256 Ledger::getHashByIndex (std::uint32_t ledgerIndex) { uint256 ret; - std::string sql = "SELECT LedgerHash FROM Ledgers INDEXED BY SeqLedger WHERE LedgerSeq='"; + std::string sql = + "SELECT LedgerHash FROM Ledgers INDEXED BY SeqLedger WHERE LedgerSeq='"; sql.append (beast::lexicalCastThrow (ledgerIndex)); sql.append ("';"); @@ -945,7 +983,8 @@ uint256 Ledger::getHashByIndex (std::uint32_t ledgerIndex) return ret; } -bool Ledger::getHashesByIndex (std::uint32_t ledgerIndex, uint256& ledgerHash, uint256& parentHash) +bool Ledger::getHashesByIndex ( + std::uint32_t ledgerIndex, uint256& ledgerHash, uint256& parentHash) { #ifndef NO_SQLITE3_PREPARE @@ -953,7 +992,8 @@ bool Ledger::getHashesByIndex (std::uint32_t ledgerIndex, uint256& ledgerHash, u DeprecatedScopedLock sl (con->getDBLock ()); SqliteStatement pSt (con->getDB ()->getSqliteDB (), - "SELECT LedgerHash,PrevHash FROM Ledgers INDEXED BY SeqLedger Where LedgerSeq = ?;"); + "SELECT LedgerHash,PrevHash FROM Ledgers " + "INDEXED BY SeqLedger Where LedgerSeq = ?;"); pSt.bind (1, ledgerIndex); @@ -979,7 +1019,8 @@ bool Ledger::getHashesByIndex (std::uint32_t ledgerIndex, uint256& ledgerHash, u #else - std::string sql = "SELECT LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq='"; + std::string sql = + "SELECT LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq='"; sql.append (beast::lexicalCastThrow (ledgerIndex)); sql.append ("';"); @@ -999,7 +1040,8 @@ bool Ledger::getHashesByIndex (std::uint32_t ledgerIndex, uint256& ledgerHash, u ledgerHash.SetHexExact (hash); parentHash.SetHexExact (prevHash); - assert (ledgerHash.isNonZero () && ((ledgerIndex == 0) || parentHash.isNonZero ())); + assert (ledgerHash.isNonZero () && + (ledgerIndex == 0 || parentHash.isNonZero ()); return true; @@ -1011,7 +1053,8 @@ Ledger::getHashesByIndex (std::uint32_t minSeq, std::uint32_t maxSeq) { std::map< std::uint32_t, std::pair > ret; - std::string sql = "SELECT LedgerSeq,LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq >= "; + std::string sql = + "SELECT LedgerSeq,LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq >= "; sql.append (beast::lexicalCastThrow (minSeq)); sql.append (" AND LedgerSeq <= "); sql.append (beast::lexicalCastThrow (maxSeq)); @@ -1040,7 +1083,8 @@ Ledger::pointer Ledger::getLastFullLedger () } catch (SHAMapMissingNode& sn) { - WriteLog (lsWARNING, Ledger) << "Database contains ledger with missing nodes: " << sn; + WriteLog (lsWARNING, Ledger) + << "Database contains ledger with missing nodes: " << sn; return Ledger::pointer (); } } @@ -1069,27 +1113,37 @@ Json::Value Ledger::getJson (int options) ScopedLockType sl (mLock); - ledger[jss::seqNum] = beast::lexicalCastThrow (mLedgerSeq); // DEPRECATED - ledger[jss::parent_hash] = to_string (mParentHash); - ledger[jss::ledger_index] = beast::lexicalCastThrow (mLedgerSeq); + // DEPRECATED + ledger[jss::seqNum] + = beast::lexicalCastThrow (mLedgerSeq); + ledger[jss::parent_hash] = to_string (mParentHash); + ledger[jss::ledger_index] + = beast::lexicalCastThrow (mLedgerSeq); if (mClosed || bFull) { if (mClosed) ledger[jss::closed] = true; - ledger[jss::hash] = to_string (mHash); // DEPRECATED - ledger[jss::totalCoins] = beast::lexicalCastThrow (mTotCoins); // DEPRECATED + // DEPRECATED + ledger[jss::hash] = to_string (mHash); + + // DEPRECATED + ledger[jss::totalCoins] + = beast::lexicalCastThrow (mTotCoins); ledger[jss::ledger_hash] = to_string (mHash); ledger[jss::transaction_hash] = to_string (mTransHash); ledger[jss::account_hash] = to_string (mAccountHash); ledger[jss::accepted] = mAccepted; - ledger[jss::total_coins] = beast::lexicalCastThrow (mTotCoins); + ledger[jss::total_coins] + = beast::lexicalCastThrow (mTotCoins); if (mCloseTime != 0) { ledger[jss::close_time] = mCloseTime; - ledger[jss::close_time_human] = boost::posix_time::to_simple_string (ptFromSeconds (mCloseTime)); + ledger[jss::close_time_human] + = boost::posix_time::to_simple_string ( + ptFromSeconds (mCloseTime)); ledger[jss::close_time_resolution] = mCloseResolution; if ((mCloseFlags & sLCF_NoConsensusTime) != 0) @@ -1106,8 +1160,8 @@ Json::Value Ledger::getJson (int options) Json::Value& txns = (ledger[jss::transactions] = Json::arrayValue); SHAMapTreeNode::TNType type; - for (SHAMapItem::pointer item = mTransactionMap->peekFirstItem (type); !!item; - item = mTransactionMap->peekNextItem (item->getTag (), type)) + for (auto item = mTransactionMap->peekFirstItem (type); !!item; + item = mTransactionMap->peekNextItem (item->getTag (), type)) { if (bFull || bExpand) { @@ -1125,7 +1179,8 @@ Json::Value Ledger::getJson (int options) SerializerIterator tsit (sTxn); SerializedTransaction txn (tsit); - TransactionMetaSet meta (item->getTag (), mLedgerSeq, sit.getVL ()); + TransactionMetaSet meta ( + item->getTag (), mLedgerSeq, sit.getVL ()); Json::Value txJson = txn.getJson (0); txJson[jss::metaData] = meta.getJson (0); txns.append (txJson); @@ -1149,8 +1204,8 @@ Json::Value Ledger::getJson (int options) visitStateItems(std::bind(stateItemFullAppender, std::ref(state), std::placeholders::_1)); else - mAccountStateMap->visitLeaves(std::bind(stateItemTagAppender, - std::ref(state), std::placeholders::_1)); + mAccountStateMap->visitLeaves( + std::bind(stateItemTagAppender, state, std::placeholders::_1)); } return ledger; @@ -1158,7 +1213,8 @@ Json::Value Ledger::getJson (int options) void Ledger::setAcquiring (void) { - if (!mTransactionMap || !mAccountStateMap) throw std::runtime_error ("invalid map"); + if (!mTransactionMap || !mAccountStateMap) + throw std::runtime_error ("invalid map"); mTransactionMap->setSynching (); mAccountStateMap->setSynching (); @@ -1205,7 +1261,7 @@ LedgerStateParms Ledger::writeBack (LedgerStateParms parms, SLE::ref entry) create = true; } - SHAMapItem::pointer item = std::make_shared (entry->getIndex ()); + auto item = std::make_shared (entry->getIndex ()); entry->add (item->peekSerializer ()); if (create) @@ -1261,7 +1317,8 @@ SLE::pointer Ledger::getSLEi (uint256 const& uId) return ret; } -void Ledger::visitAccountItems (const uint160& accountID, std::function func) +void Ledger::visitAccountItems ( + Account const& accountID, std::function func) { // Visit each item in this account's owner directory uint256 rootIndex = Ledger::getOwnerDirIndex (accountID); @@ -1289,7 +1346,8 @@ void Ledger::visitAccountItems (const uint160& accountID, std::function& function, SHAMapItem::ref item) +static void visitHelper ( + std::function& function, SHAMapItem::ref item) { function (std::make_shared (item->peekSerializer (), item->getTag ())); } @@ -1299,13 +1357,19 @@ void Ledger::visitStateItems (std::function function) try { if (mAccountStateMap) - mAccountStateMap->visitLeaves(std::bind(&visitHelper, - std::ref(function), std::placeholders::_1)); + { + mAccountStateMap->visitLeaves( + std::bind(&visitHelper, std::ref(function), + std::placeholders::_1)); + } } catch (SHAMapMissingNode&) { if (mHash.isNonZero ()) - getApp().getInboundLedgers().findCreate(mHash, mLedgerSeq, InboundLedger::fcGENERIC); + { + getApp().getInboundLedgers().findCreate( + mHash, mLedgerSeq, InboundLedger::fcGENERIC); + } throw; } } @@ -1315,7 +1379,7 @@ void Ledger::visitStateItems (std::function function) class AccountItemIterator { public: - explicit AccountItemIterator (uint160 const& accountID) + explicit AccountItemIterator (Account const& accountID) { // Convert the account ID to the root hash // @@ -1407,8 +1471,8 @@ SLE::pointer Ledger::getASNodeI (uint256 const& nodeID, LedgerEntryType let) return node; } -SLE::pointer Ledger::getASNode (LedgerStateParms& parms, uint256 const& nodeID, - LedgerEntryType let ) +SLE::pointer Ledger::getASNode ( + LedgerStateParms& parms, uint256 const& nodeID, LedgerEntryType let) { SHAMapItem::pointer account = mAccountStateMap->peekItem (nodeID); @@ -1442,71 +1506,54 @@ SLE::pointer Ledger::getASNode (LedgerStateParms& parms, uint256 const& nodeID, return sle; } -SLE::pointer Ledger::getAccountRoot (const uint160& accountID) +SLE::pointer Ledger::getAccountRoot (Account const& accountID) { return getASNodeI (getAccountRootIndex (accountID), ltACCOUNT_ROOT); } SLE::pointer Ledger::getAccountRoot (const RippleAddress& naAccountID) { - return getASNodeI (getAccountRootIndex (naAccountID.getAccountID ()), ltACCOUNT_ROOT); + return getASNodeI (getAccountRootIndex ( + naAccountID.getAccountID ()), ltACCOUNT_ROOT); } -// -// Directory -// - SLE::pointer Ledger::getDirNode (uint256 const& uNodeIndex) { return getASNodeI (uNodeIndex, ltDIR_NODE); } -// -// Generator Map -// - -SLE::pointer Ledger::getGenerator (const uint160& uGeneratorID) +SLE::pointer Ledger::getGenerator (Account const& uGeneratorID) { return getASNodeI (getGeneratorIndex (uGeneratorID), ltGENERATOR_MAP); } -// -// Nickname -// - SLE::pointer Ledger::getNickname (uint256 const& uNickname) { return getASNodeI (uNickname, ltNICKNAME); } -// -// Offer -// - - SLE::pointer Ledger::getOffer (uint256 const& uIndex) { return getASNodeI (uIndex, ltOFFER); } -// -// Ripple State -// - SLE::pointer Ledger::getRippleState (uint256 const& uNode) { return getASNodeI (uNode, ltRIPPLE_STATE); } // For an entry put in the 64 bit index or quality. -uint256 Ledger::getQualityIndex (uint256 const& uBase, const std::uint64_t uNodeDir) +uint256 Ledger::getQualityIndex ( + uint256 const& uBase, const std::uint64_t uNodeDir) { // Indexes are stored in big endian format: they print as hex as stored. - // Most significant bytes are first. Least significant bytes represent adjacent entries. - // We place uNodeDir in the 8 right most bytes to be adjacent. - // Want uNodeDir in big endian format so ++ goes to the next entry for indexes. + // Most significant bytes are first. Least significant bytes represent + // adjacent entries. We place uNodeDir in the 8 right most bytes to be + // adjacent. Want uNodeDir in big endian format so ++ goes to the next + // entry for indexes. uint256 uNode (uBase); + // TODO(tom): there must be a better way. ((std::uint64_t*) uNode.end ())[-1] = htobe64 (uNodeDir); return uNode; @@ -1520,16 +1567,11 @@ std::uint64_t Ledger::getQuality (uint256 const& uBase) uint256 Ledger::getQualityNext (uint256 const& uBase) { - static uint256 uNext ("10000000000000000"); - - uint256 uResult = uBase; - - uResult += uNext; - - return uResult; + static uint256 uNext ("10000000000000000"); + return uBase + uNext; } -uint256 Ledger::getAccountRootIndex (const uint160& account) +uint256 Ledger::getAccountRootIndex (Account const& account) { Serializer s (22); @@ -1565,8 +1607,9 @@ uint256 Ledger::getLedgerHashIndex () uint256 Ledger::getLedgerHashIndex (std::uint32_t desiredLedgerIndex) { - // get the index of the node that holds the set of 256 ledgers that includes this ledger's hash - // (or the first ledger after it if it's not a multiple of 256) + // Get the index of the node that holds the set of 256 ledgers that includes + // this ledger's hash (or the first ledger after it if it's not a multiple + // of 256). Serializer s (6); s.add16 (spaceSkipList); s.add32 (desiredLedgerIndex >> 16); @@ -1575,12 +1618,13 @@ uint256 Ledger::getLedgerHashIndex (std::uint32_t desiredLedgerIndex) uint256 Ledger::getLedgerHash (std::uint32_t ledgerIndex) { - // return the hash of the specified ledger, 0 if not available + // Return the hash of the specified ledger, 0 if not available - // easy cases + // Easy cases... if (ledgerIndex > mLedgerSeq) { - WriteLog (lsWARNING, Ledger) << "Can't get seq " << ledgerIndex << " from " << mLedgerSeq << " future"; + WriteLog (lsWARNING, Ledger) << "Can't get seq " << ledgerIndex + << " from " << mLedgerSeq << " future"; return uint256 (); } @@ -1590,38 +1634,44 @@ uint256 Ledger::getLedgerHash (std::uint32_t ledgerIndex) if (ledgerIndex == (mLedgerSeq - 1)) return mParentHash; - // within 256 + // Within 256... int diff = mLedgerSeq - ledgerIndex; if (diff <= 256) { - SLE::pointer hashIndex = getSLEi (getLedgerHashIndex ()); + auto hashIndex = getSLEi (getLedgerHashIndex ()); if (hashIndex) { - assert (hashIndex->getFieldU32 (sfLastLedgerSequence) == (mLedgerSeq - 1)); + assert (hashIndex->getFieldU32 (sfLastLedgerSequence) == + (mLedgerSeq - 1)); STVector256 vec = hashIndex->getFieldV256 (sfHashes); if (vec.size () >= diff) return vec.at (vec.size () - diff); - WriteLog (lsWARNING, Ledger) << "Ledger " << mLedgerSeq << " missing hash for " << ledgerIndex - << " (" << vec.size () << "," << diff << ")"; + WriteLog (lsWARNING, Ledger) + << "Ledger " << mLedgerSeq + << " missing hash for " << ledgerIndex + << " (" << vec.size () << "," << diff << ")"; } else { - WriteLog (lsWARNING, Ledger) << "Ledger " << mLedgerSeq << ":" << getHash () << " missing normal list"; + WriteLog (lsWARNING, Ledger) + << "Ledger " << mLedgerSeq + << ":" << getHash () << " missing normal list"; } } if ((ledgerIndex & 0xff) != 0) { - WriteLog (lsWARNING, Ledger) << "Can't get seq " << ledgerIndex << " from " << mLedgerSeq << " past"; + WriteLog (lsWARNING, Ledger) << "Can't get seq " << ledgerIndex + << " from " << mLedgerSeq << " past"; return uint256 (); } // in skiplist - SLE::pointer hashIndex = getSLEi (getLedgerHashIndex (ledgerIndex)); + auto hashIndex = getSLEi (getLedgerHashIndex (ledgerIndex)); if (hashIndex) { @@ -1636,7 +1686,8 @@ uint256 Ledger::getLedgerHash (std::uint32_t ledgerIndex) return vec.at (vec.size () - sDiff - 1); } - WriteLog (lsWARNING, Ledger) << "Can't get seq " << ledgerIndex << " from " << mLedgerSeq << " error"; + WriteLog (lsWARNING, Ledger) << "Can't get seq " << ledgerIndex + << " from " << mLedgerSeq << " error"; return uint256 (); } @@ -1650,7 +1701,7 @@ std::vector< std::pair > Ledger::getLedgerHashes () STVector256 vec = hashIndex->getFieldV256 (sfHashes); int size = vec.size (); ret.reserve (size); - std::uint32_t seq = hashIndex->getFieldU32 (sfLastLedgerSequence) - size; + auto seq = hashIndex->getFieldU32 (sfLastLedgerSequence) - size; for (int i = 0; i < size; ++i) ret.push_back (std::make_pair (++seq, vec.at (i))); @@ -1673,9 +1724,11 @@ std::vector Ledger::getLedgerAmendments () // XRP to XRP not allowed. // Currencies must have appropriate issuer. // Currencies or accounts must differ. -bool Ledger::isValidBook (const uint160& uTakerPaysCurrency, const uint160& uTakerPaysIssuerID, - const uint160& uTakerGetsCurrency, const uint160& uTakerGetsIssuerID) +bool Ledger::isValidBook ( + Currency const& uTakerPaysCurrency, Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrency, Account const& uTakerGetsIssuerID) { + // TODO(tom): refactor to use == zero, better boolean logic. if (uTakerPaysCurrency.isZero ()) { // XRP in @@ -1703,15 +1756,18 @@ bool Ledger::isValidBook (const uint160& uTakerPaysCurrency, const uint160& uTak } else // non-XRP to non-XRP { - if ((uTakerPaysCurrency == uTakerGetsCurrency) && (uTakerGetsIssuerID == uTakerPaysIssuerID)) - return false; // Input and output cannot be identical + // Input and output cannot be identical + if ((uTakerPaysCurrency == uTakerGetsCurrency) && + (uTakerGetsIssuerID == uTakerPaysIssuerID)) + return false; } return true; } -uint256 Ledger::getBookBase (const uint160& uTakerPaysCurrency, const uint160& uTakerPaysIssuerID, - const uint160& uTakerGetsCurrency, const uint160& uTakerGetsIssuerID) +uint256 Ledger::getBookBase ( + Currency const& uTakerPaysCurrency, Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrency, Account const& uTakerGetsIssuerID) { Serializer s (82); @@ -1723,19 +1779,22 @@ uint256 Ledger::getBookBase (const uint160& uTakerPaysCurrency, const uint160& u uint256 uBaseIndex = getQualityIndex (s.getSHA512Half ()); // Return with quality 0. - WriteLog (lsTRACE, Ledger) << "getBookBase" << - "(" << STAmount::createHumanCurrency (uTakerPaysCurrency) << - "," << RippleAddress::createHumanAccountID (uTakerPaysIssuerID) << - "," << STAmount::createHumanCurrency (uTakerGetsCurrency) << - "," << RippleAddress::createHumanAccountID (uTakerGetsIssuerID) << - ") = " << to_string (uBaseIndex); + WriteLog (lsTRACE, Ledger) + << "getBookBase" + << "(" << uTakerPaysCurrency + << "," << uTakerPaysIssuerID + << "," << uTakerGetsCurrency + << "," << uTakerGetsIssuerID + << ") = " << to_string (uBaseIndex); - assert (isValidBook (uTakerPaysCurrency, uTakerPaysIssuerID, uTakerGetsCurrency, uTakerGetsIssuerID)); + assert (isValidBook (uTakerPaysCurrency, uTakerPaysIssuerID, + uTakerGetsCurrency, uTakerGetsIssuerID)); return uBaseIndex; } -uint256 Ledger::getDirNodeIndex (uint256 const& uDirRoot, const std::uint64_t uNodeIndex) +uint256 Ledger::getDirNodeIndex ( + uint256 const& uDirRoot, const std::uint64_t uNodeIndex) { if (uNodeIndex) { @@ -1753,7 +1812,7 @@ uint256 Ledger::getDirNodeIndex (uint256 const& uDirRoot, const std::uint64_t uN } } -uint256 Ledger::getGeneratorIndex (const uint160& uGeneratorID) +uint256 Ledger::getGeneratorIndex (Account const& uGeneratorID) { Serializer s (22); @@ -1776,7 +1835,7 @@ uint256 Ledger::getNicknameIndex (uint256 const& uNickname) return s.getSHA512Half (); } -uint256 Ledger::getOfferIndex (const uint160& account, std::uint32_t uSequence) +uint256 Ledger::getOfferIndex (Account const& account, std::uint32_t uSequence) { Serializer s (26); @@ -1787,7 +1846,7 @@ uint256 Ledger::getOfferIndex (const uint160& account, std::uint32_t uSequence) return s.getSHA512Half (); } -uint256 Ledger::getOwnerDirIndex (const uint160& account) +uint256 Ledger::getOwnerDirIndex (Account const& account) { Serializer s (22); @@ -1797,17 +1856,19 @@ uint256 Ledger::getOwnerDirIndex (const uint160& account) return s.getSHA512Half (); } -uint256 Ledger::getRippleStateIndex (const RippleAddress& naA, const RippleAddress& naB, const uint160& uCurrency) +uint256 Ledger::getRippleStateIndex ( + const RippleAddress& naA, const RippleAddress& naB, + Currency const& currency) { - uint160 uAID = naA.getAccountID (); - uint160 uBID = naB.getAccountID (); + auto uAID = naA.getAccountID (); + auto uBID = naB.getAccountID (); bool bAltB = uAID < uBID; Serializer s (62); s.add16 (spaceRipple); // 2 s.add160 (bAltB ? uAID : uBID); // 20 s.add160 (bAltB ? uBID : uAID); // 20 - s.add160 (uCurrency); // 20 + s.add160 (currency); // 20 return s.getSHA512Half (); } @@ -1980,15 +2041,16 @@ std::set Ledger::getPendingSaves() return sPendingSaves; } -void Ledger::ownerDirDescriber (SLE::ref sle, bool, const uint160& owner) +void Ledger::ownerDirDescriber (SLE::ref sle, bool, Account const& owner) { sle->setFieldAccount (sfOwner, owner); } -void Ledger::qualityDirDescriber (SLE::ref sle, bool isNew, - const uint160& uTakerPaysCurrency, const uint160& uTakerPaysIssuer, - const uint160& uTakerGetsCurrency, const uint160& uTakerGetsIssuer, - const std::uint64_t& uRate) +void Ledger::qualityDirDescriber ( + SLE::ref sle, bool isNew, + Currency const& uTakerPaysCurrency, Account const& uTakerPaysIssuer, + Currency const& uTakerGetsCurrency, Account const& uTakerGetsIssuer, + const std::uint64_t& uRate) { sle->setFieldH160 (sfTakerPaysCurrency, uTakerPaysCurrency); sle->setFieldH160 (sfTakerPaysIssuer, uTakerPaysIssuer); @@ -1996,8 +2058,11 @@ void Ledger::qualityDirDescriber (SLE::ref sle, bool isNew, sle->setFieldH160 (sfTakerGetsIssuer, uTakerGetsIssuer); sle->setFieldU64 (sfExchangeRate, uRate); if (isNew) - getApp().getOrderBookDB().addOrderBook(uTakerPaysCurrency, uTakerGetsCurrency, - uTakerPaysIssuer, uTakerGetsIssuer); + { + getApp().getOrderBookDB().addOrderBook( + uTakerPaysCurrency, uTakerGetsCurrency, + uTakerPaysIssuer, uTakerGetsIssuer); + } } void Ledger::initializeFees () @@ -2010,13 +2075,15 @@ void Ledger::initializeFees () void Ledger::updateFees () { + if (mBaseFee) + return; std::uint64_t baseFee = getConfig ().FEE_DEFAULT; std::uint32_t referenceFeeUnits = 10; std::uint32_t reserveBase = getConfig ().FEE_ACCOUNT_RESERVE; std::int64_t reserveIncrement = getConfig ().FEE_OWNER_RESERVE; LedgerStateParms p = lepNONE; - SLE::pointer sle = getASNode (p, Ledger::getLedgerFeeIndex (), ltFEE_SETTINGS); + auto sle = getASNode (p, Ledger::getLedgerFeeIndex (), ltFEE_SETTINGS); if (sle) { @@ -2047,21 +2114,20 @@ void Ledger::updateFees () std::uint64_t Ledger::scaleFeeBase (std::uint64_t fee) { - if (!mBaseFee) - updateFees (); - - return getApp().getFeeTrack ().scaleFeeBase (fee, mBaseFee, mReferenceFeeUnits); + updateFees (); + return getApp().getFeeTrack ().scaleFeeBase ( + fee, mBaseFee, mReferenceFeeUnits); } std::uint64_t Ledger::scaleFeeLoad (std::uint64_t fee, bool bAdmin) { - if (!mBaseFee) - updateFees (); - - return getApp().getFeeTrack ().scaleFeeLoad (fee, mBaseFee, mReferenceFeeUnits, bAdmin); + updateFees (); + return getApp().getFeeTrack ().scaleFeeLoad ( + fee, mBaseFee, mReferenceFeeUnits, bAdmin); } -std::vector Ledger::getNeededTransactionHashes (int max, SHAMapSyncFilter* filter) +std::vector Ledger::getNeededTransactionHashes ( + int max, SHAMapSyncFilter* filter) { std::vector ret; @@ -2076,7 +2142,8 @@ std::vector Ledger::getNeededTransactionHashes (int max, SHAMapSyncFilt return ret; } -std::vector Ledger::getNeededAccountStateHashes (int max, SHAMapSyncFilter* filter) +std::vector Ledger::getNeededAccountStateHashes ( + int max, SHAMapSyncFilter* filter) { std::vector ret; @@ -2098,7 +2165,8 @@ class Ledger_test : public beast::unit_test::suite public: void run () { - uint256 uBig ("D2DC44E5DC189318DB36EF87D2104CDF0A0FE3A4B698BEEE55038D7EA4C68000"); + uint256 uBig ( + "D2DC44E5DC189318DB36EF87D2104CDF0A0FE3A4B698BEEE55038D7EA4C68000"); // VFALCO NOTE This fails in the original version as well. expect (6125895493223874560 == Ledger::getQuality (uBig)); diff --git a/src/ripple/module/app/ledger/Ledger.h b/src/ripple/module/app/ledger/Ledger.h index db5ede7cf4..d16def5542 100644 --- a/src/ripple/module/app/ledger/Ledger.h +++ b/src/ripple/module/app/ledger/Ledger.h @@ -89,34 +89,48 @@ public: TR_SUCCESS = 0, TR_NOTFOUND = 1, TR_ALREADY = 2, - TR_BADTRANS = 3, // the transaction itself is corrupt - TR_BADACCT = 4, // one of the accounts is invalid - TR_INSUFF = 5, // the sending(apply)/receiving(remove) account is broke - TR_PASTASEQ = 6, // account is past this transaction - TR_PREASEQ = 7, // account is missing transactions before this - TR_BADLSEQ = 8, // ledger too early - TR_TOOSMALL = 9, // amount is less than Tx fee + + // the transaction itself is corrupt + TR_BADTRANS = 3, + + // one of the accounts is invalid + TR_BADACCT = 4, + + // the sending(apply)/receiving(remove) account is broke + TR_INSUFF = 5, + + // account is past this transaction + TR_PASTASEQ = 6, + + // account is missing transactions before this + TR_PREASEQ = 7, + + // ledger too early + TR_BADLSEQ = 8, + + // amount is less than Tx fee + TR_TOOSMALL = 9, }; // ledger close flags static const std::uint32_t sLCF_NoConsensusTime = 1; public: - Ledger (const RippleAddress & masterID, std::uint64_t startAmount); // used for the starting bootstrap ledger - Ledger (uint256 const & parentHash, uint256 const & transHash, uint256 const & accountHash, - std::uint64_t totCoins, std::uint32_t closeTime, std::uint32_t parentCloseTime, - int closeFlags, int closeResolution, - std::uint32_t ledgerSeq, bool & loaded); // used for database ledgers + // used for the starting bootstrap ledger + Ledger (const RippleAddress & masterID, std::uint64_t startAmount); + + Ledger (uint256 const & parentHash, uint256 const & transHash, + uint256 const & accountHash, + std::uint64_t totCoins, std::uint32_t closeTime, + std::uint32_t parentCloseTime, int closeFlags, int closeResolution, + std::uint32_t ledgerSeq, bool & loaded); + // used for database ledgers Ledger (std::uint32_t ledgerSeq, std::uint32_t closeTime); - Ledger (Blob const & rawLedger, bool hasPrefix); - Ledger (const std::string & rawLedger, bool hasPrefix); - Ledger (bool dummy, Ledger & previous); // ledger after this one - Ledger (Ledger & target, bool isMutable); // snapshot ~Ledger (); @@ -125,7 +139,8 @@ public: static Ledger::pointer getSQL1 (SqliteStatement*); static void getSQL2 (Ledger::ref); static Ledger::pointer getLastFullLedger (); - static std::uint32_t roundCloseTime (std::uint32_t closeTime, std::uint32_t closeResolution); + static std::uint32_t roundCloseTime ( + std::uint32_t closeTime, std::uint32_t closeResolution); void updateHash (); void setClosed () @@ -136,7 +151,9 @@ public: { mValidated = true; } - void setAccepted (std::uint32_t closeTime, int closeResolution, bool correctCloseTime); + void setAccepted ( + std::uint32_t closeTime, int closeResolution, bool correctCloseTime); + void setAccepted (); void setImmutable (); bool isClosed () @@ -254,36 +271,44 @@ public: bool isAcquiringAS (void); // Transaction Functions - bool addTransaction (uint256 const & id, const Serializer & txn); - bool addTransaction (uint256 const & id, const Serializer & txn, const Serializer & metaData); + bool addTransaction (uint256 const& id, Serializer const& txn); + bool addTransaction ( + const uint256& id, Serializer const& txn, Serializer const& metaData); bool hasTransaction (uint256 const & TransID) const { return mTransactionMap->hasItem (TransID); } Transaction::pointer getTransaction (uint256 const & transID) const; - bool getTransaction (uint256 const & transID, Transaction::pointer & txn, TransactionMetaSet::pointer & txMeta); - bool getTransactionMeta (uint256 const & transID, TransactionMetaSet::pointer & txMeta); + bool getTransaction ( + uint256 const & transID, + Transaction::pointer & txn, TransactionMetaSet::pointer & txMeta); + bool getTransactionMeta ( + uint256 const & transID, TransactionMetaSet::pointer & txMeta); bool getMetaHex (uint256 const & transID, std::string & hex); - static SerializedTransaction::pointer getSTransaction (SHAMapItem::ref, SHAMapTreeNode::TNType); - SerializedTransaction::pointer getSMTransaction (SHAMapItem::ref, SHAMapTreeNode::TNType, - TransactionMetaSet::pointer & txMeta); + static SerializedTransaction::pointer getSTransaction ( + SHAMapItem::ref, SHAMapTreeNode::TNType); + SerializedTransaction::pointer getSMTransaction ( + SHAMapItem::ref, SHAMapTreeNode::TNType, + TransactionMetaSet::pointer & txMeta); // high-level functions bool hasAccount (const RippleAddress & acctID); AccountState::pointer getAccountState (const RippleAddress & acctID); LedgerStateParms writeBack (LedgerStateParms parms, SLE::ref); - SLE::pointer getAccountRoot (const uint160 & accountID); + SLE::pointer getAccountRoot (Account const& accountID); SLE::pointer getAccountRoot (const RippleAddress & naAccountID); void updateSkipList (); - void visitAccountItems (const uint160 & acctID, std::function); + void visitAccountItems ( + Account const& acctID, std::function); void visitStateItems (std::function); // database functions (low-level) static Ledger::pointer loadByIndex (std::uint32_t ledgerIndex); static Ledger::pointer loadByHash (uint256 const & ledgerHash); static uint256 getHashByIndex (std::uint32_t index); - static bool getHashesByIndex (std::uint32_t index, uint256 & ledgerHash, uint256 & parentHash); + static bool getHashesByIndex ( + std::uint32_t index, uint256 & ledgerHash, uint256 & parentHash); static std::map< std::uint32_t, std::pair > getHashesByIndex (std::uint32_t minSeq, std::uint32_t maxSeq); bool pendSaveValidated (bool isSynchronous, bool isCurrent); @@ -296,16 +321,26 @@ public: // uint256 getFirstLedgerIndex (); uint256 getLastLedgerIndex (); - uint256 getNextLedgerIndex (uint256 const & uHash); // first node >hash - uint256 getNextLedgerIndex (uint256 const & uHash, uint256 const & uEnd); // first node >hash, begin + + // first node >hash + uint256 getNextLedgerIndex (uint256 const & uHash); + + // first node >hash, begin + uint256 getPrevLedgerIndex (uint256 const & uHash, uint256 const & uBegin); // Ledger hash table function static uint256 getLedgerHashIndex (); static uint256 getLedgerHashIndex (std::uint32_t desiredLedgerIndex); static int getLedgerHashOffset (std::uint32_t desiredLedgerIndex); - static int getLedgerHashOffset (std::uint32_t desiredLedgerIndex, std::uint32_t currentLedgerIndex); + static int getLedgerHashOffset ( + std::uint32_t desiredLedgerIndex, std::uint32_t currentLedgerIndex); + uint256 getLedgerHash (std::uint32_t ledgerIndex); std::vector< std::pair > getLedgerHashes (); @@ -313,11 +348,13 @@ public: static uint256 getLedgerFeeIndex (); std::vector getLedgerAmendments (); - std::vector getNeededTransactionHashes (int max, SHAMapSyncFilter * filter); - std::vector getNeededAccountStateHashes (int max, SHAMapSyncFilter * filter); + std::vector getNeededTransactionHashes ( + int max, SHAMapSyncFilter* filter); + std::vector getNeededAccountStateHashes ( + int max, SHAMapSyncFilter* filter); // index calculation functions - static uint256 getAccountRootIndex (const uint160 & account); + static uint256 getAccountRootIndex (Account const&); static uint256 getAccountRootIndex (const RippleAddress & account) { @@ -328,9 +365,8 @@ public: // Generator Map functions // - SLE::pointer getGenerator (const uint160 & uGeneratorID); - - static uint256 getGeneratorIndex (const uint160 & uGeneratorID); + SLE::pointer getGenerator (Account const& uGeneratorID); + static uint256 getGeneratorIndex (Account const& uGeneratorID); // // Nickname functions @@ -360,26 +396,29 @@ public: // Order book functions // - // Order book dirs have a base so we can use next to step through them in quality order. - static bool isValidBook (const uint160 & uTakerPaysCurrency, const uint160 & uTakerPaysIssuerID, - const uint160 & uTakerGetsCurrency, const uint160 & uTakerGetsIssuerID); + // Order book dirs have a base so we can use next to step through them in + // quality order. + static bool isValidBook ( + Currency const& uTakerPaysCurrency, Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrency, Account const& uTakerGetsIssuerID); - static uint256 getBookBase (const uint160 & uTakerPaysCurrency, const uint160 & uTakerPaysIssuerID, - const uint160 & uTakerGetsCurrency, const uint160 & uTakerGetsIssuerID); + static uint256 getBookBase ( + Currency const& uTakerPaysCurrency, Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrency, Account const& uTakerGetsIssuerID); // // Offer functions // SLE::pointer getOffer (uint256 const & uIndex); - - SLE::pointer getOffer (const uint160 & account, std::uint32_t uSequence) + SLE::pointer getOffer (Account const & account, std::uint32_t uSequence) { return getOffer (getOfferIndex (account, uSequence)); } // The index of an offer. - static uint256 getOfferIndex (const uint160 & account, std::uint32_t uSequence); + static uint256 getOfferIndex ( + Account const & account, std::uint32_t uSequence); // // Owner functions @@ -389,15 +428,16 @@ public: // into a 256 bit object (I think....need to research this) // // All items controlled by an account are here: offers - static uint256 getOwnerDirIndex (const uint160 & account); + static uint256 getOwnerDirIndex (Account const &account); // // Directory functions // Directories are doubly linked lists of nodes. // Given a directory root and and index compute the index of a node. - static uint256 getDirNodeIndex (uint256 const & uDirRoot, const std::uint64_t uNodeIndex = 0); - static void ownerDirDescriber (SLE::ref, bool, const uint160 & owner); + static uint256 getDirNodeIndex ( + uint256 const & uDirRoot, const std::uint64_t uNodeIndex = 0); + static void ownerDirDescriber (SLE::ref, bool, Account const& owner); // Return a node: root or normal SLE::pointer getDirNode (uint256 const & uNodeIndex); @@ -406,65 +446,76 @@ public: // Quality // - static uint256 getQualityIndex (uint256 const & uBase, const std::uint64_t uNodeDir = 0); - static uint256 getQualityNext (uint256 const & uBase); - static std::uint64_t getQuality (uint256 const & uBase); - static void qualityDirDescriber (SLE::ref, bool, - const uint160 & uTakerPaysCurrency, const uint160 & uTakerPaysIssuer, - const uint160 & uTakerGetsCurrency, const uint160 & uTakerGetsIssuer, - const std::uint64_t & uRate); + static uint256 getQualityIndex ( + uint256 const & uBase, const std::uint64_t uNodeDir = 0); + static uint256 getQualityNext (uint256 const & uBase); + static std::uint64_t getQuality (uint256 const & uBase); + static void qualityDirDescriber ( + SLE::ref, bool, + Currency const& uTakerPaysCurrency, Account const& uTakerPaysIssuer, + Currency const& uTakerGetsCurrency, Account const& uTakerGetsIssuer, + const std::uint64_t & uRate); // // Ripple functions : credit lines // - - // Index of node which is the ripple state between two accounts for a currency. - // VFALCO NOTE Rename these to make it clear they are simple functions that - // don't access global variables. e.g. "calculateKeyFromRippleStateAndAddress" // - static uint256 getRippleStateIndex (const RippleAddress & naA, const RippleAddress & naB, const uint160 & uCurrency); - static uint256 getRippleStateIndex (const uint160 & uiA, const uint160 & uiB, const uint160 & uCurrency) + // Index of node which is the ripple state between two accounts for a + // currency. + // + // VFALCO NOTE Rename these to make it clear they are simple functions that + // don't access global variables. e.g. + // "calculateKeyFromRippleStateAndAddress" + static uint256 getRippleStateIndex ( + const RippleAddress&, const RippleAddress&, Currency const&); + static uint256 getRippleStateIndex ( + Account const& a, Account const& b, Currency const& uCurrency) { - return getRippleStateIndex (RippleAddress::createAccountID (uiA), RippleAddress::createAccountID (uiB), uCurrency); + return getRippleStateIndex ( + RippleAddress::createAccountID (a), + RippleAddress::createAccountID (b), uCurrency); } SLE::pointer getRippleState (uint256 const & uNode); - SLE::pointer getRippleState (const RippleAddress & naA, const RippleAddress & naB, const uint160 & uCurrency) + SLE::pointer getRippleState ( + RippleAddress const& a, RippleAddress const& b, + Currency const& currency) { - return getRippleState (getRippleStateIndex (naA, naB, uCurrency)); + return getRippleState (getRippleStateIndex (a, b, currency)); } - SLE::pointer getRippleState (const uint160 & uiA, const uint160 & uiB, const uint160 & uCurrency) + SLE::pointer getRippleState ( + Account const& a, Account const& b, Currency const& currency) { - return getRippleState (getRippleStateIndex (RippleAddress::createAccountID (uiA), RippleAddress::createAccountID (uiB), uCurrency)); + return getRippleState (getRippleStateIndex ( + RippleAddress::createAccountID (a), + RippleAddress::createAccountID (b), currency)); } std::uint32_t getReferenceFeeUnits () { - if (!mBaseFee) updateFees (); - + updateFees (); return mReferenceFeeUnits; } std::uint64_t getBaseFee () { - if (!mBaseFee) updateFees (); - + updateFees (); return mBaseFee; } std::uint64_t getReserve (int increments) { - if (!mBaseFee) updateFees (); - - return scaleFeeBase (static_cast (increments) * mReserveIncrement + mReserveBase); + updateFees (); + return scaleFeeBase ( + static_cast (increments) * mReserveIncrement + + mReserveBase); } std::uint64_t getReserveInc () { - if (!mBaseFee) updateFees (); - + updateFees (); return mReserveIncrement; } @@ -480,10 +531,11 @@ public: bool assertSane (); protected: - SLE::pointer getASNode (LedgerStateParms & parms, uint256 const & nodeID, LedgerEntryType let); + SLE::pointer getASNode ( + LedgerStateParms& parms, uint256 const& nodeID, LedgerEntryType let); // returned SLE is immutable - SLE::pointer getASNodeI (uint256 const & nodeID, LedgerEntryType let); + SLE::pointer getASNodeI (uint256 const& nodeID, LedgerEntryType let); void saveValidatedLedgerAsync(Job&, bool current) { @@ -491,12 +543,10 @@ protected: } bool saveValidatedLedger (bool current); - void updateFees (); - private: void initializeFees (); + void updateFees (); -private: // The basic Ledger structure, can be opened, closed, or synching uint256 mHash; uint256 mParentHash; @@ -504,35 +554,54 @@ private: uint256 mAccountHash; std::uint64_t mTotCoins; std::uint32_t mLedgerSeq; - std::uint32_t mCloseTime; // when this ledger closed - std::uint32_t mParentCloseTime; // when the previous ledger closed - int mCloseResolution; // the resolution for this ledger close time (2-120 seconds) - std::uint32_t mCloseFlags; // flags indicating how this ledger close took place + + // when this ledger closed + std::uint32_t mCloseTime; + + // when the previous ledger closed + std::uint32_t mParentCloseTime; + + // the resolution for this ledger close time (2-120 seconds) + int mCloseResolution; + + // flags indicating how this ledger close took place + std::uint32_t mCloseFlags; bool mClosed, mValidated, mValidHash, mAccepted, mImmutable; - std::uint32_t mReferenceFeeUnits; // Fee units for the reference transaction - std::uint32_t mReserveBase, mReserveIncrement; // Reserve basse and increment in fee units - std::uint64_t mBaseFee; // Ripple cost of the reference transaction + // Fee units for the reference transaction + std::uint32_t mReferenceFeeUnits; + + // Reserve basse and increment in fee units + std::uint32_t mReserveBase, mReserveIncrement; + + // Ripple cost of the reference transaction + std::uint64_t mBaseFee; SHAMap::pointer mTransactionMap; SHAMap::pointer mAccountStateMap; typedef RippleMutex StaticLockType; typedef std::lock_guard StaticScopedLockType; - // ledgers not fully saved, validated ledger present but DB may not be correct yet + + // Ledgers not fully saved, validated ledger present but DB may not be + // correct yet. static StaticLockType sPendingSaveLock; static std::set sPendingSaves; }; -inline LedgerStateParms operator| (const LedgerStateParms& l1, const LedgerStateParms& l2) +inline LedgerStateParms operator| ( + const LedgerStateParms& l1, const LedgerStateParms& l2) { - return static_cast (static_cast (l1) | static_cast (l2)); + return static_cast ( + static_cast (l1) | static_cast (l2)); } -inline LedgerStateParms operator& (const LedgerStateParms& l1, const LedgerStateParms& l2) +inline LedgerStateParms operator& ( + const LedgerStateParms& l1, const LedgerStateParms& l2) { - return static_cast (static_cast (l1) & static_cast (l2)); + return static_cast ( + static_cast (l1) & static_cast (l2)); } } // ripple diff --git a/src/ripple/module/app/ledger/LedgerEntrySet.cpp b/src/ripple/module/app/ledger/LedgerEntrySet.cpp index 2c1c5feba0..f566514f77 100644 --- a/src/ripple/module/app/ledger/LedgerEntrySet.cpp +++ b/src/ripple/module/app/ledger/LedgerEntrySet.cpp @@ -47,15 +47,6 @@ LedgerEntrySet LedgerEntrySet::duplicate () const return LedgerEntrySet (mLedger, mEntries, mSet, mSeq + 1); } -void LedgerEntrySet::setTo (const LedgerEntrySet& e) -{ - mLedger = e.mLedger; - mEntries = e.mEntries; - mSet = e.mSet; - mParams = e.mParams; - mSeq = e.mSeq; -} - void LedgerEntrySet::swapWith (LedgerEntrySet& e) { std::swap (mLedger, e.mLedger); @@ -979,7 +970,9 @@ bool LedgerEntrySet::dirNext ( if (!sleNext) { // This should never happen - WriteLog (lsFATAL, LedgerEntrySet) << "Corrupt directory: index:" << uRootIndex << " next:" << uNodeNext; + WriteLog (lsFATAL, LedgerEntrySet) + << "Corrupt directory: index:" + << uRootIndex << " next:" << uNodeNext; return false; } @@ -1016,14 +1009,16 @@ uint256 LedgerEntrySet::getNextLedgerIndex (uint256 const& uHash) { // node found in LES, node found in ledger, return earliest if (it->second.mAction != taaDELETE) - return (ledgerNext.isNonZero () && (ledgerNext < it->first)) ? ledgerNext : it->first; + return (ledgerNext.isNonZero () && (ledgerNext < it->first)) ? + ledgerNext : it->first; } // nothing next in LES, return next ledger node return ledgerNext; } -uint256 LedgerEntrySet::getNextLedgerIndex (uint256 const& uHash, uint256 const& uEnd) +uint256 LedgerEntrySet::getNextLedgerIndex ( + uint256 const& uHash, uint256 const& uEnd) { uint256 next = getNextLedgerIndex (uHash); @@ -1033,12 +1028,13 @@ uint256 LedgerEntrySet::getNextLedgerIndex (uint256 const& uHash, uint256 const& return next; } -// If there is a count, adjust the owner count by iAmount. Otherwise, compute the owner count and store it. -void LedgerEntrySet::ownerCountAdjust (const uint160& uOwnerID, int iAmount, SLE::ref sleAccountRoot) +// If there is a count, adjust the owner count by iAmount. Otherwise, compute +// the owner count and store it. +void LedgerEntrySet::ownerCountAdjust ( + Account const& owner, int iAmount, SLE::ref sleAccountRoot) { - SLE::pointer sleHold = sleAccountRoot - ? SLE::pointer () - : entryCache (ltACCOUNT_ROOT, Ledger::getAccountRootIndex (uOwnerID)); + auto sleHold = sleAccountRoot ? SLE::pointer () + : entryCache (ltACCOUNT_ROOT, Ledger::getAccountRootIndex (owner)); SLE::ref sleRoot = sleAccountRoot ? sleAccountRoot @@ -1060,8 +1056,8 @@ void LedgerEntrySet::ownerCountAdjust (const uint160& uOwnerID, int iAmount, SLE TER LedgerEntrySet::offerDelete (SLE::pointer sleOffer) { - uint256 offerIndex = sleOffer->getIndex (); - uint160 uOwnerID = sleOffer->getFieldAccount160 (sfAccount); + auto offerIndex = sleOffer->getIndex (); + auto owner = sleOffer->getFieldAccount160 (sfAccount); // Detect legacy directories. bool bOwnerNode = sleOffer->isFieldPresent (sfOwnerNode); @@ -1071,12 +1067,12 @@ TER LedgerEntrySet::offerDelete (SLE::pointer sleOffer) TER terResult = dirDelete ( false, uOwnerNode, - Ledger::getOwnerDirIndex (uOwnerID), offerIndex, false, !bOwnerNode); + Ledger::getOwnerDirIndex (owner), offerIndex, false, !bOwnerNode); TER terResult2 = dirDelete ( false, uBookNode, uDirectory, offerIndex, true, false); if (tesSUCCESS == terResult) - ownerCountAdjust (uOwnerID, -1); + ownerCountAdjust (owner, -1); entryDelete (sleOffer); @@ -1098,8 +1094,8 @@ TER LedgerEntrySet::offerDelete (uint256 const& offerIndex) // positive: uFromAccountID holds IOUs., // negative: uFromAccountID owes IOUs. STAmount LedgerEntrySet::rippleOwed ( - const uint160& uToAccountID, const uint160& uFromAccountID, - const uint160& currency) + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& currency) { STAmount saBalance; SLE::pointer sleRippleState = entryCache ( @@ -1122,9 +1118,9 @@ STAmount LedgerEntrySet::rippleOwed ( WriteLog (lsDEBUG, LedgerEntrySet) << "rippleOwed:" << " No credit line between " << - RippleAddress::createHumanAccountID (uFromAccountID) << - " and " << RippleAddress::createHumanAccountID (uToAccountID) << - " for " << STAmount::createHumanCurrency (currency); + to_string (uFromAccountID) << + " and " << to_string (uToAccountID) << + " for " << to_string (currency); } return saBalance; @@ -1133,8 +1129,8 @@ STAmount LedgerEntrySet::rippleOwed ( // Maximum amount of IOUs uToAccountID will hold from uFromAccountID. // <-- $amount/currency/uToAccountID. STAmount LedgerEntrySet::rippleLimit ( - const uint160& uToAccountID, const uint160& uFromAccountID, - const uint160& currency) + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& currency) { STAmount saLimit; auto sleRippleState = entryCache ( @@ -1157,7 +1153,7 @@ STAmount LedgerEntrySet::rippleLimit ( } -std::uint32_t LedgerEntrySet::rippleTransferRate (const uint160& issuer) +std::uint32_t LedgerEntrySet::rippleTransferRate (Account const& issuer) { SLE::pointer sleAccount (entryCache ( ltACCOUNT_ROOT, Ledger::getAccountRootIndex (issuer))); @@ -1168,7 +1164,7 @@ std::uint32_t LedgerEntrySet::rippleTransferRate (const uint160& issuer) : QUALITY_ONE; WriteLog (lsTRACE, LedgerEntrySet) << "rippleTransferRate:" << - " issuer=" << RippleAddress::createHumanAccountID (issuer) << + " issuer=" << to_string (issuer) << " account_exists=" << std::boolalpha << !!sleAccount << " transfer_rate=" << (uQuality / 1000000000.0); @@ -1176,9 +1172,9 @@ std::uint32_t LedgerEntrySet::rippleTransferRate (const uint160& issuer) } std::uint32_t -LedgerEntrySet::rippleTransferRate (const uint160& uSenderID, - const uint160& uReceiverID, - const uint160& issuer) +LedgerEntrySet::rippleTransferRate (Account const& uSenderID, + Account const& uReceiverID, + Account const& issuer) { // If calculating the transfer rate from or to the issuer of the currency // no fees are assessed. @@ -1189,10 +1185,9 @@ LedgerEntrySet::rippleTransferRate (const uint160& uSenderID, // XXX Might not need this, might store in nodes on calc reverse. std::uint32_t -LedgerEntrySet::rippleQualityIn (const uint160& uToAccountID, - const uint160& uFromAccountID, - const uint160& uCurrencyID, - SField::ref sfLow, SField::ref sfHigh) +LedgerEntrySet::rippleQualityIn ( + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& uCurrencyID, SField::ref sfLow, SField::ref sfHigh) { std::uint32_t uQuality (QUALITY_ONE); @@ -1221,18 +1216,20 @@ LedgerEntrySet::rippleQualityIn (const uint160& uToAccountID, WriteLog (lsTRACE, LedgerEntrySet) << "rippleQuality: " << (sfLow == sfLowQualityIn ? "in" : "out") << - " uToAccountID=" << RippleAddress::createHumanAccountID (uToAccountID) << - " uFromAccountID=" << RippleAddress::createHumanAccountID (uFromAccountID) << - " uCurrencyID=" << STAmount::createHumanCurrency (uCurrencyID) << + " uToAccountID=" << to_string (uToAccountID) << + " uFromAccountID=" << to_string (uFromAccountID) << + " uCurrencyID=" << to_string (uCurrencyID) << " bLine=" << std::boolalpha << !!sleRippleState << " uQuality=" << (uQuality / 1000000000.0); return uQuality; } -// Return how much of issuer's currency IOUs that account holds. May be negative. +// Return how much of issuer's currency IOUs that account holds. May be +// negative. // <-- IOU's account has of issuer. -STAmount LedgerEntrySet::rippleHolds (const uint160& account, const uint160& currency, const uint160& issuer) +STAmount LedgerEntrySet::rippleHolds ( + Account const& account, Currency const& currency, Account const& issuer) { STAmount saBalance; SLE::pointer sleRippleState = entryCache (ltRIPPLE_STATE, @@ -1263,8 +1260,7 @@ STAmount LedgerEntrySet::rippleHolds (const uint160& account, const uint160& cur // // <-- saAmount: amount of currency held by account. May be negative. STAmount LedgerEntrySet::accountHolds ( - const uint160& account, const uint160& currency, - const uint160& issuer) + Account const& account, Currency const& currency, Account const& issuer) { STAmount saAmount; @@ -1287,7 +1283,7 @@ STAmount LedgerEntrySet::accountHolds ( } WriteLog (lsTRACE, LedgerEntrySet) << "accountHolds:" << - " account=" << RippleAddress::createHumanAccountID (account) << + " account=" << to_string (account) << " saAmount=" << saAmount.getFullText () << " saBalance=" << saBalance.getFullText () << " uReserve=" << uReserve; @@ -1297,7 +1293,7 @@ STAmount LedgerEntrySet::accountHolds ( saAmount = rippleHolds (account, currency, issuer); WriteLog (lsTRACE, LedgerEntrySet) << "accountHolds:" << - " account=" << RippleAddress::createHumanAccountID (account) << + " account=" << to_string (account) << " saAmount=" << saAmount.getFullText (); } @@ -1313,7 +1309,7 @@ STAmount LedgerEntrySet::accountHolds ( // If the issuer is the same as account, funds are unlimited, use result is // saDefault. STAmount LedgerEntrySet::accountFunds ( - const uint160& account, const STAmount& saDefault) + Account const& account, const STAmount& saDefault) { STAmount saFunds; @@ -1322,7 +1318,7 @@ STAmount LedgerEntrySet::accountFunds ( saFunds = saDefault; WriteLog (lsTRACE, LedgerEntrySet) << "accountFunds:" << - " account=" << RippleAddress::createHumanAccountID (account) << + " account=" << to_string (account) << " saDefault=" << saDefault.getFullText () << " SELF-FUNDED"; } @@ -1332,7 +1328,7 @@ STAmount LedgerEntrySet::accountFunds ( account, saDefault.getCurrency (), saDefault.getIssuer ()); WriteLog (lsTRACE, LedgerEntrySet) << "accountFunds:" << - " account=" << RippleAddress::createHumanAccountID (account) << + " account=" << to_string (account) << " saDefault=" << saDefault.getFullText () << " saFunds=" << saFunds.getFullText (); } @@ -1342,9 +1338,9 @@ STAmount LedgerEntrySet::accountFunds ( // Calculate transit fee. STAmount LedgerEntrySet::rippleTransferFee ( - const uint160& uSenderID, - const uint160& uReceiverID, - const uint160& issuer, + Account const& uSenderID, + Account const& uReceiverID, + Account const& issuer, const STAmount& saAmount) { if (uSenderID != issuer && uReceiverID != issuer) @@ -1355,7 +1351,7 @@ STAmount LedgerEntrySet::rippleTransferFee ( { // NIKB use STAmount::saFromRate STAmount saTransitRate ( - CURRENCY_ONE, ACCOUNT_ONE, + noCurrency(), noAccount(), static_cast (uTransitRate), -9); STAmount saTransferTotal = STAmount::multiply ( @@ -1375,44 +1371,44 @@ STAmount LedgerEntrySet::rippleTransferFee ( TER LedgerEntrySet::trustCreate ( const bool bSrcHigh, - const uint160& uSrcAccountID, - const uint160& uDstAccountID, + Account const& uSrcAccountID, + Account const& uDstAccountID, uint256 const& uIndex, // --> ripple state entry SLE::ref sleAccount, // --> the account being set. const bool bAuth, // --> authorize account. const bool bNoRipple, // --> others cannot ripple through const STAmount& saBalance, // --> balance of account being set. - // Issuer should be ACCOUNT_ONE + // Issuer should be noAccount() const STAmount& saLimit, // --> limit for account being set. // Issuer should be the account being set. const std::uint32_t uQualityIn, const std::uint32_t uQualityOut) { - const uint160& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID; - const uint160& uHighAccountID = bSrcHigh ? uSrcAccountID : uDstAccountID; + auto const& uLowAccountID = !bSrcHigh ? uSrcAccountID : uDstAccountID; + auto const& uHighAccountID = bSrcHigh ? uSrcAccountID : uDstAccountID; - SLE::pointer sleRippleState = entryCreate (ltRIPPLE_STATE, uIndex); + SLE::pointer sleRippleState = entryCreate (ltRIPPLE_STATE, uIndex); std::uint64_t uLowNode; std::uint64_t uHighNode; - TER terResult = dirAdd ( - uLowNode, - Ledger::getOwnerDirIndex (uLowAccountID), - sleRippleState->getIndex (), - std::bind (&Ledger::ownerDirDescriber, - std::placeholders::_1, std::placeholders::_2, - uLowAccountID)); + TER terResult = dirAdd ( + uLowNode, + Ledger::getOwnerDirIndex (uLowAccountID), + sleRippleState->getIndex (), + std::bind (&Ledger::ownerDirDescriber, + std::placeholders::_1, std::placeholders::_2, + uLowAccountID)); if (tesSUCCESS == terResult) { - terResult = dirAdd ( - uHighNode, - Ledger::getOwnerDirIndex (uHighAccountID), - sleRippleState->getIndex (), - std::bind (&Ledger::ownerDirDescriber, - std::placeholders::_1, std::placeholders::_2, - uHighAccountID)); + terResult = dirAdd ( + uHighNode, + Ledger::getOwnerDirIndex (uHighAccountID), + sleRippleState->getIndex (), + std::bind (&Ledger::ownerDirDescriber, + std::placeholders::_1, std::placeholders::_2, + uHighAccountID)); } if (tesSUCCESS == terResult) @@ -1463,8 +1459,8 @@ TER LedgerEntrySet::trustCreate ( } TER LedgerEntrySet::trustDelete ( - SLE::ref sleRippleState, const uint160& uLowAccountID, - const uint160& uHighAccountID) + SLE::ref sleRippleState, Account const& uLowAccountID, + Account const& uHighAccountID) { // Detect legacy dirs. bool bLowNode = sleRippleState->isFieldPresent (sfLowNode); @@ -1507,11 +1503,11 @@ TER LedgerEntrySet::trustDelete ( // - Create trust line of needed. // --> bCheckIssuer : normally require issuer to be involved. TER LedgerEntrySet::rippleCredit ( - const uint160& uSenderID, const uint160& uReceiverID, + Account const& uSenderID, Account const& uReceiverID, const STAmount& saAmount, bool bCheckIssuer) { - uint160 issuer = saAmount.getIssuer (); - uint160 currency = saAmount.getCurrency (); + auto issuer = saAmount.getIssuer (); + auto currency = saAmount.getCurrency (); // Make sure issuer is involved. assert ( @@ -1527,19 +1523,19 @@ TER LedgerEntrySet::rippleCredit ( TER terResult; - assert (!!uSenderID && uSenderID != ACCOUNT_ONE); - assert (!!uReceiverID && uReceiverID != ACCOUNT_ONE); + assert (!!uSenderID && uSenderID != noAccount()); + assert (!!uReceiverID && uReceiverID != noAccount()); if (!sleRippleState) { STAmount saReceiverLimit = STAmount (currency, uReceiverID); STAmount saBalance = saAmount; - saBalance.setIssuer (ACCOUNT_ONE); + saBalance.setIssuer (noAccount()); WriteLog (lsDEBUG, LedgerEntrySet) << "rippleCredit: " - "create line: " << RippleAddress::createHumanAccountID (uSenderID) << - " -> " << RippleAddress::createHumanAccountID (uReceiverID) << + "create line: " << to_string (uSenderID) << + " -> " << to_string (uReceiverID) << " : " << saAmount.getFullText (); terResult = trustCreate ( @@ -1565,8 +1561,8 @@ TER LedgerEntrySet::rippleCredit ( saBalance -= saAmount; WriteLog (lsTRACE, LedgerEntrySet) << "rippleCredit: " << - RippleAddress::createHumanAccountID (uSenderID) << - " -> " << RippleAddress::createHumanAccountID (uReceiverID) << + to_string (uSenderID) << + " -> " << to_string (uReceiverID) << " : before=" << saBefore.getFullText () << " amount=" << saAmount.getFullText () << " after=" << saBalance.getFullText (); @@ -1637,17 +1633,17 @@ TER LedgerEntrySet::rippleCredit ( // --> saAmount: Amount/currency/issuer to deliver to reciever. // <-- saActual: Amount actually cost. Sender pay's fees. TER LedgerEntrySet::rippleSend ( - const uint160& uSenderID, const uint160& uReceiverID, + Account const& uSenderID, Account const& uReceiverID, const STAmount& saAmount, STAmount& saActual) { - const uint160 issuer = saAmount.getIssuer (); + auto const issuer = saAmount.getIssuer (); TER terResult; assert (!!uSenderID && !!uReceiverID); assert (uSenderID != uReceiverID); if (uSenderID == issuer || uReceiverID == issuer || - issuer == ACCOUNT_ONE) + issuer == noAccount()) { // Direct send: redeeming IOUs and/or sending own IOUs. terResult = rippleCredit (uSenderID, uReceiverID, saAmount, false); @@ -1668,8 +1664,8 @@ TER LedgerEntrySet::rippleSend ( saActual.setIssuer (issuer); // XXX Make sure this done in + above. WriteLog (lsDEBUG, LedgerEntrySet) << "rippleSend> " << - RippleAddress::createHumanAccountID (uSenderID) << - " - > " << RippleAddress::createHumanAccountID (uReceiverID) << + to_string (uSenderID) << + " - > " << to_string (uReceiverID) << " : deliver=" << saAmount.getFullText () << " fee=" << saTransitFee.getFullText () << " cost=" << saActual.getFullText (); @@ -1684,7 +1680,7 @@ TER LedgerEntrySet::rippleSend ( } TER LedgerEntrySet::accountSend ( - const uint160& uSenderID, const uint160& uReceiverID, + Account const& uSenderID, Account const& uReceiverID, const STAmount& saAmount) { TER terResult = tesSUCCESS; @@ -1717,9 +1713,9 @@ TER LedgerEntrySet::accountSend ( }; WriteLog (lsTRACE, LedgerEntrySet) << "accountSend> " << - RippleAddress::createHumanAccountID (uSenderID) << + to_string (uSenderID) << " (" << get_balance(sleSender) << - ") -> " << RippleAddress::createHumanAccountID (uReceiverID) << + ") -> " << to_string (uReceiverID) << " (" << get_balance(sleReceiver) << ") : " << saAmount.getFullText (); @@ -1749,9 +1745,9 @@ TER LedgerEntrySet::accountSend ( } WriteLog (lsTRACE, LedgerEntrySet) << "accountSend< " << - RippleAddress::createHumanAccountID (uSenderID) << + to_string (uSenderID) << " (" << get_balance(sleSender) << - ") -> " << RippleAddress::createHumanAccountID (uReceiverID) << + ") -> " << to_string (uReceiverID) << " (" << get_balance(sleReceiver) << ") : " << saAmount.getFullText (); } @@ -1760,8 +1756,8 @@ TER LedgerEntrySet::accountSend ( STAmount saActual; WriteLog (lsTRACE, LedgerEntrySet) << "accountSend: " << - RippleAddress::createHumanAccountID (uSenderID) << - " -> " << RippleAddress::createHumanAccountID (uReceiverID) << + to_string (uSenderID) << + " -> " << to_string (uReceiverID) << " : " << saAmount.getFullText (); diff --git a/src/ripple/module/app/ledger/LedgerEntrySet.h b/src/ripple/module/app/ledger/LedgerEntrySet.h index d9f6c67a66..a733503f03 100644 --- a/src/ripple/module/app/ledger/LedgerEntrySet.h +++ b/src/ripple/module/app/ledger/LedgerEntrySet.h @@ -26,16 +26,20 @@ enum TransactionEngineParams { tapNONE = 0x00, - tapNO_CHECK_SIGN = 0x01, // Signature already checked + // Signature already checked + tapNO_CHECK_SIGN = 0x01, - tapOPEN_LEDGER = 0x10, // Transaction is running against an open ledger + // Transaction is running against an open ledger // true = failures are not forwarded, check transaction fee // false = debit ledger for consumed funds + tapOPEN_LEDGER = 0x10, - tapRETRY = 0x20, // This is not the transaction's last pass + // This is not the transaction's last pass // Transaction can be retried, soft failures allowed + tapRETRY = 0x20, - tapADMIN = 0x400, // Transaction came from a privileged source + // Transaction came from a privileged source + tapADMIN = 0x400, }; enum LedgerEntryAction @@ -79,7 +83,8 @@ class LedgerEntrySet public: static char const* getCountedObjectName () { return "LedgerEntrySet"; } - LedgerEntrySet (Ledger::ref ledger, TransactionEngineParams tep, bool immutable = false) : + LedgerEntrySet ( + Ledger::ref ledger, TransactionEngineParams tep, bool immutable = false) : mLedger (ledger), mParams (tep), mSeq (0), mImmutable (immutable) { } @@ -99,11 +104,11 @@ public: return mImmutable; } - LedgerEntrySet duplicate () const; // Make a duplicate of this set + // Make a duplicate of this set. + LedgerEntrySet duplicate () const; - void setTo (const LedgerEntrySet&); // Set this set to have the same contents as another - - void swapWith (LedgerEntrySet&); // Swap the contents of two sets + // Swap the contents of two sets + void swapWith (LedgerEntrySet&); void invalidate () { @@ -181,34 +186,34 @@ public: uint256 getNextLedgerIndex (uint256 const & uHash); uint256 getNextLedgerIndex (uint256 const & uHash, uint256 const & uEnd); - void ownerCountAdjust (uint160 const& uOwnerID, int iAmount, SLE::ref sleAccountRoot = SLE::pointer ()); + void ownerCountAdjust (Account const& uOwnerID, int iAmount, SLE::ref sleAccountRoot = SLE::pointer ()); // Offer functions. TER offerDelete (uint256 const & offerIndex); TER offerDelete (SLE::pointer sleOffer); // Balance functions. - std::uint32_t rippleTransferRate (uint160 const& issuer); + std::uint32_t rippleTransferRate (Account const& issuer); std::uint32_t rippleTransferRate ( - uint160 const& uSenderID, uint160 const& uReceiverID, - uint160 const& issuer); + Account const& uSenderID, Account const& uReceiverID, + Account const& issuer); STAmount rippleOwed ( - uint160 const& uToAccountID, uint160 const& uFromAccountID, - uint160 const& currency); + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& currency); STAmount rippleLimit ( - uint160 const& uToAccountID, uint160 const& uFromAccountID, - uint160 const& currency); + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& currency); std::uint32_t rippleQualityIn ( - uint160 const& uToAccountID, uint160 const& uFromAccountID, - uint160 const& currency, + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& currency, SField::ref sfLow = sfLowQualityIn, SField::ref sfHigh = sfHighQualityIn); std::uint32_t rippleQualityOut ( - uint160 const& uToAccountID, uint160 const& uFromAccountID, - uint160 const& currency) + Account const& uToAccountID, Account const& uFromAccountID, + Currency const& currency) { return rippleQualityIn ( uToAccountID, uFromAccountID, currency, @@ -216,34 +221,34 @@ public: } STAmount rippleHolds ( - uint160 const& account, uint160 const& currency, - uint160 const& issuer); + Account const& account, Currency const& currency, + Account const& issuer); STAmount rippleTransferFee ( - uint160 const& uSenderID, uint160 const& uReceiverID, - uint160 const& issuer, const STAmount & saAmount); + Account const& uSenderID, Account const& uReceiverID, + Account const& issuer, const STAmount & saAmount); TER rippleCredit ( - uint160 const& uSenderID, uint160 const& uReceiverID, + Account const& uSenderID, Account const& uReceiverID, const STAmount & saAmount, bool bCheckIssuer = true); TER rippleSend ( - uint160 const& uSenderID, uint160 const& uReceiverID, + Account const& uSenderID, Account const& uReceiverID, const STAmount & saAmount, STAmount & saActual); STAmount accountHolds ( - uint160 const& account, uint160 const& currency, - uint160 const& issuer); + Account const& account, Currency const& currency, + Account const& issuer); STAmount accountFunds ( - uint160 const& account, const STAmount & saDefault); + Account const& account, const STAmount & saDefault); TER accountSend ( - uint160 const& uSenderID, uint160 const& uReceiverID, + Account const& uSenderID, Account const& uReceiverID, const STAmount & saAmount); TER trustCreate ( const bool bSrcHigh, - uint160 const& uSrcAccountID, - uint160 const& uDstAccountID, + Account const& uSrcAccountID, + Account const& uDstAccountID, uint256 const & uIndex, SLE::ref sleAccount, const bool bAuth, @@ -253,8 +258,8 @@ public: const std::uint32_t uSrcQualityIn = 0, const std::uint32_t uSrcQualityOut = 0); TER trustDelete ( - SLE::ref sleRippleState, uint160 const& uLowAccountID, - uint160 const& uHighAccountID); + SLE::ref sleRippleState, Account const& uLowAccountID, + Account const& uHighAccountID); Json::Value getJson (int) const; void calcRawMeta (Serializer&, TER result, std::uint32_t index); diff --git a/src/ripple/module/app/ledger/LedgerProposal.h b/src/ripple/module/app/ledger/LedgerProposal.h index 58e215b5c4..ed5d61b54c 100644 --- a/src/ripple/module/app/ledger/LedgerProposal.h +++ b/src/ripple/module/app/ledger/LedgerProposal.h @@ -55,7 +55,7 @@ public: return checkSign (mSignature, getSigningHash ()); } - const uint160& getPeerID () const + NodeID const& getPeerID () const { return mPeerID; } @@ -135,7 +135,7 @@ private: uint256 mPreviousLedger, mCurrentHash, mSuppression; std::uint32_t mCloseTime, mProposeSeq; - uint160 mPeerID; + NodeID mPeerID; RippleAddress mPublicKey; RippleAddress mPrivateKey; // If ours diff --git a/src/ripple/module/app/ledger/OrderBookDB.cpp b/src/ripple/module/app/ledger/OrderBookDB.cpp index c25ee4ef64..c649956ccb 100644 --- a/src/ripple/module/app/ledger/OrderBookDB.cpp +++ b/src/ripple/module/app/ledger/OrderBookDB.cpp @@ -23,7 +23,6 @@ OrderBookDB::OrderBookDB (Stoppable& parent) : Stoppable ("OrderBookDB", parent) , mSeq (0) { - } void OrderBookDB::invalidate () @@ -70,10 +69,13 @@ static void updateHelper (SLE::ref entry, if ((entry->getType () == ltDIR_NODE) && (entry->isFieldPresent (sfExchangeRate)) && (entry->getFieldH256 (sfRootIndex) == entry->getIndex())) { - const uint160& ci = entry->getFieldH160 (sfTakerPaysCurrency); - const uint160& co = entry->getFieldH160 (sfTakerGetsCurrency); - const uint160& ii = entry->getFieldH160 (sfTakerPaysIssuer); - const uint160& io = entry->getFieldH160 (sfTakerGetsIssuer); + Currency ci, co; + ci.copyFrom (entry->getFieldH160 (sfTakerPaysCurrency)); + co.copyFrom (entry->getFieldH160 (sfTakerGetsCurrency)); + + Account ii, io; + ii.copyFrom (entry->getFieldH160 (sfTakerPaysIssuer)); + io.copyFrom (entry->getFieldH160 (sfTakerGetsIssuer)); uint256 index = Ledger::getBookBase (ci, ii, co, io); @@ -129,8 +131,8 @@ void OrderBookDB::update (Ledger::pointer ledger) getApp().getLedgerMaster().newOrderBookDB(); } -void OrderBookDB::addOrderBook(const uint160& ci, const uint160& co, - const uint160& ii, const uint160& io) +void OrderBookDB::addOrderBook(Currency const& ci, Currency const& co, + Account const& ii, Account const& io) { bool toXRP = co.isZero(); ScopedLockType sl (mLock); @@ -153,8 +155,7 @@ void OrderBookDB::addOrderBook(const uint160& ci, const uint160& co, } uint256 index = Ledger::getBookBase(ci, ii, co, io); - OrderBook::pointer book = std::make_shared (std::cref (index), - std::cref (ci), std::cref (co), std::cref (ii), std::cref (io)); + auto book = std::make_shared (index, ci, co, ii, io); mSourceMap[RippleAssetRef (ci, ii)].push_back (book); mDestMap[RippleAssetRef (co, io)].push_back (book); @@ -163,7 +164,7 @@ void OrderBookDB::addOrderBook(const uint160& ci, const uint160& co, } // return list of all orderbooks that want this issuerID and currencyID -void OrderBookDB::getBooksByTakerPays (RippleIssuer const& issuerID, RippleCurrency const& currencyID, +void OrderBookDB::getBooksByTakerPays (Account const& issuerID, Currency const& currencyID, std::vector& bookRet) { ScopedLockType sl (mLock); @@ -175,7 +176,7 @@ void OrderBookDB::getBooksByTakerPays (RippleIssuer const& issuerID, RippleCurre bookRet.clear (); } -bool OrderBookDB::isBookToXRP(RippleIssuer const& issuerID, RippleCurrency const& currencyID) +bool OrderBookDB::isBookToXRP(Account const& issuerID, Currency const& currencyID) { ScopedLockType sl (mLock); @@ -183,7 +184,7 @@ bool OrderBookDB::isBookToXRP(RippleIssuer const& issuerID, RippleCurrency const } // return list of all orderbooks that give this issuerID and currencyID -void OrderBookDB::getBooksByTakerGets (RippleIssuer const& issuerID, RippleCurrency const& currencyID, +void OrderBookDB::getBooksByTakerGets (Account const& issuerID, Currency const& currencyID, std::vector& bookRet) { ScopedLockType sl (mLock); @@ -195,8 +196,8 @@ void OrderBookDB::getBooksByTakerGets (RippleIssuer const& issuerID, RippleCurre bookRet.clear (); } -BookListeners::pointer OrderBookDB::makeBookListeners (RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets) +BookListeners::pointer OrderBookDB::makeBookListeners (Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets) { ScopedLockType sl (mLock); BookListeners::pointer ret = getBookListeners (currencyPays, currencyGets, issuerPays, issuerGets); @@ -214,13 +215,13 @@ BookListeners::pointer OrderBookDB::makeBookListeners (RippleCurrency const& cur return ret; } -BookListeners::pointer OrderBookDB::getBookListeners (RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets) +BookListeners::pointer OrderBookDB::getBookListeners (Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets) { BookListeners::pointer ret; ScopedLockType sl (mLock); - MapType::iterator it0 (mListeners.find (RippleBookRef ( + auto it0 (mListeners.find (RippleBookRef ( RippleAssetRef (currencyPays, issuerPays), RippleAssetRef (currencyGets, issuerGets)))); @@ -269,12 +270,12 @@ void OrderBookDB::processTxn (Ledger::ref ledger, const AcceptedLedgerTx& alTx, if (data) { const STAmount& takerGets = data->getFieldAmount (sfTakerGets); - RippleCurrency const& currencyGets = takerGets.getCurrency (); - RippleIssuer const& issuerGets = takerGets.getIssuer (); + Currency const& currencyGets = takerGets.getCurrency (); + Account const& issuerGets = takerGets.getIssuer (); const STAmount& takerPays = data->getFieldAmount (sfTakerPays); - RippleCurrency const& currencyPays = takerPays.getCurrency (); - RippleIssuer const& issuerPays = takerPays.getIssuer (); + Currency const& currencyPays = takerPays.getCurrency (); + Account const& issuerPays = takerPays.getIssuer (); // determine the OrderBook BookListeners::pointer book = diff --git a/src/ripple/module/app/ledger/OrderBookDB.h b/src/ripple/module/app/ledger/OrderBookDB.h index 6cb74c7430..da128f5dd9 100644 --- a/src/ripple/module/app/ledger/OrderBookDB.h +++ b/src/ripple/module/app/ledger/OrderBookDB.h @@ -57,34 +57,36 @@ public: void update (Ledger::pointer ledger); void invalidate (); - void addOrderBook(const uint160& takerPaysCurrency, const uint160& takerGetsCurrency, - const uint160& takerPaysIssuer, const uint160& takerGetsIssuer); + void addOrderBook( + Currency const& takerPaysCurrency, Currency const& takerGetsCurrency, + Account const& takerPaysIssuer, Account const& takerGetsIssuer); // return list of all orderbooks that want this issuerID and currencyID - void getBooksByTakerPays (RippleIssuer const& issuerID, RippleCurrency const& currencyID, + void getBooksByTakerPays (Account const& issuerID, Currency const& currencyID, std::vector& bookRet); - void getBooksByTakerGets (RippleIssuer const& issuerID, RippleCurrency const& currencyID, + void getBooksByTakerGets (Account const& issuerID, Currency const& currencyID, std::vector& bookRet); - bool isBookToXRP (RippleIssuer const& issuerID, RippleCurrency const& currencyID); + bool isBookToXRP (Account const& issuerID, Currency const& currencyID); - BookListeners::pointer getBookListeners (RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets); + BookListeners::pointer getBookListeners (Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets); - BookListeners::pointer makeBookListeners (RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets); + BookListeners::pointer makeBookListeners (Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets); // see if this txn effects any orderbook void processTxn (Ledger::ref ledger, const AcceptedLedgerTx& alTx, Json::Value const& jvObj); private: + typedef ripple::unordered_map > + AssetToOrderBook; + // by ci/ii - ripple::unordered_map > mSourceMap; + AssetToOrderBook mSourceMap; // by co/io - ripple::unordered_map > mDestMap; + AssetToOrderBook mDestMap; // does an order book to XRP exist boost::unordered_set mXRPBooks; @@ -93,9 +95,10 @@ private: typedef std::lock_guard ScopedLockType; LockType mLock; - typedef ripple::unordered_map MapType; + typedef ripple::unordered_map + BookToListenersMap; - MapType mListeners; + BookToListenersMap mListeners; std::uint32_t mSeq; diff --git a/src/ripple/module/app/ledger/OrderBookIterator.cpp b/src/ripple/module/app/ledger/OrderBookIterator.cpp index c4393a48f4..31bcd0f2b9 100644 --- a/src/ripple/module/app/ledger/OrderBookIterator.cpp +++ b/src/ripple/module/app/ledger/OrderBookIterator.cpp @@ -20,10 +20,11 @@ namespace ripple { /** Iterate through the directories in an order book */ -BookDirIterator::BookDirIterator(uint160 const& uInCurrency, uint160 const& uInIssuer, - uint160 const& uOutCurrency, uint160 const& uOutIssuer) +BookDirIterator::BookDirIterator( + Currency const& currencyIn, Account const& issuerIn, + Currency const& currencyOut, Account const& issuerOut) { - mBase = Ledger::getBookBase(uInCurrency, uInIssuer, uOutCurrency, uOutIssuer); + mBase = Ledger::getBookBase(currencyIn, issuerIn, currencyOut, issuerOut); mEnd = Ledger::getQualityNext(mBase); mIndex = mBase; } @@ -85,7 +86,7 @@ bool BookDirIterator::resync (LedgerEntrySet& les) DirectoryEntryIterator BookDirIterator::getOfferIterator () const { - WriteLog (lsTRACE, Ledger) << "BookDirIterator(" << + WriteLog (lsTRACE, Ledger) << "BookDirIterator(" << to_string (mBase) << ") get offer iterator"; return DirectoryEntryIterator (mOfferDir); } diff --git a/src/ripple/module/app/ledger/OrderBookIterator.h b/src/ripple/module/app/ledger/OrderBookIterator.h index 73e77a433a..ce6493688f 100644 --- a/src/ripple/module/app/ledger/OrderBookIterator.h +++ b/src/ripple/module/app/ledger/OrderBookIterator.h @@ -33,8 +33,8 @@ public: } BookDirIterator ( - uint160 const& uInCurrency, uint160 const& uInIssuer, - uint160 const& uOutCurrency, uint160 const& uOutIssuer); + Currency const& currencyIn, Account const& issuerIn, + Currency const& currencyOut, Account const& issuerOut); uint256 const& getBookBase () const { @@ -90,7 +90,6 @@ public: std::uint64_t getRate () const; bool addJson (Json::Value&) const; - bool setJson (Json::Value const&); // Does this iterator currently point to a valid directory @@ -98,17 +97,15 @@ public: operator bool () const { return mOfferDir && (mOfferDir->getIndex() == mIndex); - } + } - bool - operator== (BookDirIterator const& other) const + bool operator== (BookDirIterator const& other) const { assert (! mIndex.isZero() && ! other.mIndex.isZero()); return mIndex == other.mIndex; } - bool - operator!= (BookDirIterator const& other) const + bool operator!= (BookDirIterator const& other) const { return ! (*this == other); } @@ -130,12 +127,12 @@ class OrderBookIterator public: OrderBookIterator ( LedgerEntrySet& set, - uint160 const& uInCurrency, - uint160 const& uInIssuer, - uint160 const& uOutCurrency, - uint160 const& uOutIssuer) : + Currency const& currencyIn, + Account const& issuerIn, + Currency const& currencyOut, + Account const& issuerOut) : mEntrySet (set), - mDirectoryIterator (uInCurrency, uInIssuer, uOutCurrency, uOutIssuer) + mDirectoryIterator (currencyIn, issuerIn, currencyOut, issuerOut) { } diff --git a/src/ripple/module/app/ledger/SerializedValidation.h b/src/ripple/module/app/ledger/SerializedValidation.h index 146e0957dd..24986cc129 100644 --- a/src/ripple/module/app/ledger/SerializedValidation.h +++ b/src/ripple/module/app/ledger/SerializedValidation.h @@ -51,7 +51,7 @@ public: std::uint32_t getSignTime () const; std::uint32_t getFlags () const; RippleAddress getSignerPublic () const; - uint160 getNodeID () const + NodeID getNodeID () const { return mNodeID; } @@ -93,7 +93,7 @@ private: void setNode (); uint256 mPreviousHash; - uint160 mNodeID; + NodeID mNodeID; bool mTrusted; }; diff --git a/src/ripple/module/app/misc/AccountItem.h b/src/ripple/module/app/misc/AccountItem.h index 33c5783073..23d0ca537f 100644 --- a/src/ripple/module/app/misc/AccountItem.h +++ b/src/ripple/module/app/misc/AccountItem.h @@ -42,19 +42,15 @@ public: typedef const pointer& ref; public: - AccountItem () - { } - /** Construct from a flat ledger entry. */ explicit AccountItem (SerializedLedgerEntry::ref ledger); - virtual ~AccountItem () - { - ; - } + AccountItem () {} + virtual ~AccountItem () {} - virtual AccountItem::pointer makeItem (const uint160& accountID, SerializedLedgerEntry::ref ledgerEntry) = 0; + virtual AccountItem::pointer makeItem ( + Account const& accountID, SerializedLedgerEntry::ref ledgerEntry) = 0; // VFALCO TODO Make this const and change derived classes virtual LedgerEntryType getType () = 0; diff --git a/src/ripple/module/app/misc/AccountItems.cpp b/src/ripple/module/app/misc/AccountItems.cpp index 2e16550bef..fad841f735 100644 --- a/src/ripple/module/app/misc/AccountItems.cpp +++ b/src/ripple/module/app/misc/AccountItems.cpp @@ -19,7 +19,7 @@ namespace ripple { -AccountItems::AccountItems (uint160 const& accountID, +AccountItems::AccountItems (Account const& accountID, Ledger::ref ledger, AccountItem::pointer ofType) { @@ -28,7 +28,7 @@ AccountItems::AccountItems (uint160 const& accountID, fillItems (accountID, ledger); } -void AccountItems::fillItems (const uint160& accountID, Ledger::ref ledger) +void AccountItems::fillItems (Account const& accountID, Ledger::ref ledger) { uint256 const rootIndex = Ledger::getOwnerDirIndex (accountID); uint256 currentIndex = rootIndex; @@ -44,32 +44,27 @@ void AccountItems::fillItems (const uint160& accountID, Ledger::ref ledger) if (!ownerDir) return; - BOOST_FOREACH (uint256 const & uNode, ownerDir->getFieldV256 (sfIndexes).peekValue ()) + for (auto const& uNode: ownerDir->getFieldV256 (sfIndexes).peekValue ()) { // VFALCO TODO rename getSLEi() to something legible. SLE::pointer sleCur = ledger->getSLEi (uNode); - if (!sleCur) + if (sleCur) { - // item in directory not in ledger - } - else - { - AccountItem::pointer item = mOfType->makeItem (accountID, sleCur); + // The item in the directory is in ledger + auto item = mOfType->makeItem (accountID, sleCur); - // VFALCO NOTE Under what conditions would makeItem() return nullptr? - // DJS NOTE If the item wasn't one this particular AccountItems was interested in - // (For example, if the owner is only interested in ripple lines and this is an offer) + // makeItem() returns nullptr if the item wasn't one this + // particular AccountItems was interested in - for example, if + // the owner is only interested in ripple lines and this is an + // offer. if (item) - { mItems.push_back (item); - } } } std::uint64_t uNodeNext = ownerDir->getFieldU64 (sfIndexNext); - // VFALCO TODO Rewrite to not return from the middle of the function if (!uNodeNext) return; @@ -81,13 +76,10 @@ Json::Value AccountItems::getJson (int v) { Json::Value ret (Json::arrayValue); - BOOST_FOREACH (AccountItem::ref ai, mItems) - { + for (auto ai: mItems) ret.append (ai->getJson (v)); - } return ret; } } // ripple - diff --git a/src/ripple/module/app/misc/AccountItems.h b/src/ripple/module/app/misc/AccountItems.h index d63593c7b4..2a7e50a232 100644 --- a/src/ripple/module/app/misc/AccountItems.h +++ b/src/ripple/module/app/misc/AccountItems.h @@ -30,8 +30,7 @@ public: typedef std::vector Container; - // VFALCO TODO Create a typedef uint160 AccountID and replace - AccountItems (uint160 const& accountID, + AccountItems (Account const& accountID, Ledger::ref ledger, AccountItem::pointer ofType); @@ -47,7 +46,7 @@ public: Json::Value getJson (int); private: - void fillItems (const uint160& accountID, Ledger::ref ledger); + void fillItems (Account const& accountID, Ledger::ref ledger); private: // VFALCO TODO This looks like its used as an exemplar, rename appropriately diff --git a/src/ripple/module/app/misc/AmendmentTableImpl.cpp b/src/ripple/module/app/misc/AmendmentTableImpl.cpp index 23287a18f4..5e71ba7ca5 100644 --- a/src/ripple/module/app/misc/AmendmentTableImpl.cpp +++ b/src/ripple/module/app/misc/AmendmentTableImpl.cpp @@ -381,10 +381,10 @@ AmendmentTableImpl::reportValidations (const AmendmentSet& set) { AmendmentState& fState = m_amendmentMap[hash]; db->executeSQL (boost::str (boost::format ( - "UPDATE Features SET FirstMajority = %d WHERE Hash = '%s';") % + "UPDATE Features SET FirstMajority = %d WHERE Hash = '%s';") % fState.m_firstMajority % to_string (hash))); db->executeSQL (boost::str (boost::format ( - "UPDATE Features SET LastMajority = %d WHERE Hash = '%s';") % + "UPDATE Features SET LastMajority = %d WHERE Hash = '%s';") % fState.m_lastMajority % to_string(hash))); } db->executeSQL ("END TRANSACTION;"); @@ -476,7 +476,7 @@ AmendmentTableImpl::doVoting (Ledger::ref lastClosedLedger, // Create the transaction to enable the amendment SerializedTransaction trans (ttAMENDMENT); - trans.setFieldAccount (sfAccount, uint160 ()); + trans.setFieldAccount (sfAccount, Account ()); trans.setFieldH256 (sfAmendment, uAmendment); uint256 txID = trans.getTransactionID (); diff --git a/src/ripple/module/app/misc/FeeVoteImpl.cpp b/src/ripple/module/app/misc/FeeVoteImpl.cpp index a8006697bd..918f436205 100644 --- a/src/ripple/module/app/misc/FeeVoteImpl.cpp +++ b/src/ripple/module/app/misc/FeeVoteImpl.cpp @@ -24,12 +24,12 @@ class FeaturesImpl; class FeeVoteImpl : public FeeVote { private: - + template class VotableInteger { public: - VotableInteger (Integer current, Integer target) + VotableInteger (Integer current, Integer target) : mCurrent (current) , mTarget (target) { @@ -103,7 +103,7 @@ public: { if (m_journal.info) m_journal.info << "Voting for base fee of " << mTargetBaseFee; - + baseValidation.setFieldU64 (sfBaseFee, mTargetBaseFee); } @@ -189,7 +189,7 @@ public: "/" << incReserve; SerializedTransaction trans (ttFEE); - trans.setFieldAccount (sfAccount, uint160 ()); + trans.setFieldAccount (sfAccount, Account ()); trans.setFieldU64 (sfBaseFee, baseFee); trans.setFieldU32 (sfReferenceFeeUnits, 10); trans.setFieldU32 (sfReserveBase, baseReserve); @@ -197,8 +197,8 @@ public: uint256 txID = trans.getTransactionID (); - if (m_journal.warning) m_journal.warning << - "Vote: " << txID; + if (m_journal.warning) + m_journal.warning << "Vote: " << txID; Serializer s; trans.add (s, true); diff --git a/src/ripple/module/app/misc/NetworkOPs.cpp b/src/ripple/module/app/misc/NetworkOPs.cpp index 00e0772dc7..341b438219 100644 --- a/src/ripple/module/app/misc/NetworkOPs.cpp +++ b/src/ripple/module/app/misc/NetworkOPs.cpp @@ -187,15 +187,18 @@ public: // Account functions // - AccountState::pointer getAccountState (Ledger::ref lrLedger, const RippleAddress& accountID); - SLE::pointer getGenerator (Ledger::ref lrLedger, const uint160& uGeneratorID); + AccountState::pointer getAccountState ( + Ledger::ref lrLedger, const RippleAddress& accountID); + SLE::pointer getGenerator ( + Ledger::ref lrLedger, Account const& uGeneratorID); // // Directory functions // - STVector256 getDirNodeInfo (Ledger::ref lrLedger, uint256 const& uRootIndex, - std::uint64_t& uNodePrevious, std::uint64_t& uNodeNext); + STVector256 getDirNodeInfo ( + Ledger::ref lrLedger, uint256 const& uRootIndex, + std::uint64_t& uNodePrevious, std::uint64_t& uNodeNext); #if 0 // @@ -216,11 +219,11 @@ public: // void getBookPage (Ledger::pointer lpLedger, - const uint160& uTakerPaysCurrencyID, - const uint160& uTakerPaysIssuerID, - const uint160& uTakerGetsCurrencyID, - const uint160& uTakerGetsIssuerID, - const uint160& uTakerID, + Currency const& uTakerPaysCurrencyID, + Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrencyID, + Account const& uTakerGetsIssuerID, + Account const& uTakerID, const bool bProof, const unsigned int iLimit, const Json::Value& jvMarker, @@ -322,8 +325,7 @@ public: void clearLedgerFetch (); Json::Value getLedgerFetchInfo (); std::uint32_t acceptLedger (); - ripple::unordered_map < uint160, - std::list > & peekStoredProposals () + Proposals & peekStoredProposals () { return mStoredProposals; } @@ -396,11 +398,11 @@ public: bool subServer (InfoSub::ref ispListener, Json::Value& jvResult); bool unsubServer (std::uint64_t uListener); - bool subBook (InfoSub::ref ispListener, RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets); - bool unsubBook (std::uint64_t uListener, RippleCurrency const& currencyPays, - RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets); + bool subBook (InfoSub::ref ispListener, Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets); + bool unsubBook (std::uint64_t uListener, Currency const& currencyPays, + Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets); bool subTransactions (InfoSub::ref ispListener); bool unsubTransactions (std::uint64_t uListener); @@ -432,23 +434,26 @@ private: void setMode (OperatingMode); - Json::Value transJson (const SerializedTransaction& stTxn, TER terResult, bool bValidated, Ledger::ref lpCurrent); + Json::Value transJson ( + const SerializedTransaction& stTxn, TER terResult, bool bValidated, + Ledger::ref lpCurrent); bool haveConsensusObject (); - Json::Value pubBootstrapAccountInfo (Ledger::ref lpAccepted, const RippleAddress& naAccountID); + Json::Value pubBootstrapAccountInfo ( + Ledger::ref lpAccepted, const RippleAddress& naAccountID); - void pubValidatedTransaction (Ledger::ref alAccepted, const AcceptedLedgerTx& alTransaction); - void pubAccountTransaction (Ledger::ref lpCurrent, const AcceptedLedgerTx& alTransaction, bool isAccepted); + void pubValidatedTransaction ( + Ledger::ref alAccepted, const AcceptedLedgerTx& alTransaction); + void pubAccountTransaction ( + Ledger::ref lpCurrent, const AcceptedLedgerTx& alTransaction, bool isAccepted); void pubServer (); private: clock_type& m_clock; - typedef ripple::unordered_map SubInfoMapType; - typedef ripple::unordered_map ::iterator SubInfoMapIterator; - - typedef ripple::unordered_map subRpcMapType; + typedef ripple::unordered_map SubInfoMapType; + typedef ripple::unordered_map subRpcMapType; // XXX Split into more locks. typedef RippleRecursiveMutex LockType; @@ -469,9 +474,8 @@ private: boost::posix_time::ptime mConnectTime; beast::DeadlineTimer m_heartbeatTimer; beast::DeadlineTimer m_clusterTimer; - std::shared_ptr mConsensus; - ripple::unordered_map < uint160, - std::list > mStoredProposals; + std::shared_ptr mConsensus; + NetworkOPs::Proposals mStoredProposals; LedgerMaster& m_ledgerMaster; InboundLedger::pointer mAcquiringLedger; @@ -1056,12 +1060,14 @@ int NetworkOPsImp::findTransactionsByDestination (std::listgetAccountState (accountID); } -SLE::pointer NetworkOPsImp::getGenerator (Ledger::ref lrLedger, const uint160& uGeneratorID) +SLE::pointer NetworkOPsImp::getGenerator ( + Ledger::ref lrLedger, Account const& uGeneratorID) { if (!lrLedger) return SLE::pointer (); @@ -1198,13 +1204,13 @@ class ValidationCount { public: int trustedValidations, nodesUsing; - uint160 highNodeUsing, highValidation; + NodeID highNodeUsing, highValidation; ValidationCount () : trustedValidations (0), nodesUsing (0) { } - bool operator> (const ValidationCount& v) + bool operator> (const ValidationCount& v) const { if (trustedValidations > v.trustedValidations) return true; @@ -1283,9 +1289,9 @@ bool NetworkOPsImp::checkLastClosedLedger (const Overlay::PeerSequence& peerList ripple::unordered_map ledgers; { - ripple::unordered_map current = + ripple::unordered_map current = getApp().getValidations ().getCurrentValidations (closedLedger, prevClosedLedger); - typedef std::map::value_type u256_cvc_pair; + typedef std::map::value_type u256_cvc_pair; BOOST_FOREACH (const u256_cvc_pair & it, current) { ValidationCount& vc = ledgers[it.first]; @@ -1301,7 +1307,8 @@ bool NetworkOPsImp::checkLastClosedLedger (const Overlay::PeerSequence& peerList if (mMode >= omTRACKING) { ++ourVC.nodesUsing; - uint160 ourAddress = getApp().getLocalCredentials ().getNodePublic ().getNodeID (); + auto ourAddress = + getApp().getLocalCredentials ().getNodePublic ().getNodeID (); if (ourAddress > ourVC.highNodeUsing) ourVC.highNodeUsing = ourAddress; @@ -1317,15 +1324,18 @@ bool NetworkOPsImp::checkLastClosedLedger (const Overlay::PeerSequence& peerList { ValidationCount& vc = ledgers[peerLedger]; - if ((vc.nodesUsing == 0) || (peer->getNodePublic ().getNodeID () > vc.highNodeUsing)) + if (vc.nodesUsing == 0 || + peer->getNodePublic ().getNodeID () > vc.highNodeUsing) + { vc.highNodeUsing = peer->getNodePublic ().getNodeID (); + } ++vc.nodesUsing; - } - catch (...) - { - // Peer is likely not connected anymore - } + } + catch (...) + { + // Peer is likely not connected anymore + } } } @@ -1334,25 +1344,25 @@ bool NetworkOPsImp::checkLastClosedLedger (const Overlay::PeerSequence& peerList // 3) Is there a network ledger we'd like to switch to? If so, do we have it? bool switchLedgers = false; - for (ripple::unordered_map::iterator it = ledgers.begin (), end = ledgers.end (); - it != end; ++it) + for (auto const& it: ledgers) { - m_journal.debug << "L: " << it->first << " t=" << it->second.trustedValidations << - ", n=" << it->second.nodesUsing; + m_journal.debug << "L: " << it.first + << " t=" << it.second.trustedValidations + << ", n=" << it.second.nodesUsing; // Temporary logging to make sure tiebreaking isn't broken - if (it->second.trustedValidations > 0) - m_journal.trace << " TieBreakTV: " << it->second.highValidation; + if (it.second.trustedValidations > 0) + m_journal.trace << " TieBreakTV: " << it.second.highValidation; else { - if (it->second.nodesUsing > 0) - m_journal.trace << " TieBreakNU: " << it->second.highNodeUsing; + if (it.second.nodesUsing > 0) + m_journal.trace << " TieBreakNU: " << it.second.highNodeUsing; } - if (it->second > bestVC) + if (it.second > bestVC) { - bestVC = it->second; - closedLedger = it->first; + bestVC = it.second; + closedLedger = it.first; switchLedgers = true; } } @@ -1573,7 +1583,7 @@ void NetworkOPsImp::processTrustedProposal (LedgerProposal::pointer proposal, // Must be called while holding the master lock SHAMap::pointer NetworkOPsImp::getTXMap (uint256 const& hash) { - std::map >::iterator it = mRecentPositions.find (hash); + auto it = mRecentPositions.find (hash); if (it != mRecentPositions.end ()) return it->second.second; @@ -2531,13 +2541,13 @@ void NetworkOPsImp::pubAccountTransaction (Ledger::ref lpCurrent, const Accepted if (!mSubAccount.empty () || (!mSubRTAccount.empty ()) ) { - BOOST_FOREACH (const RippleAddress & affectedAccount, alTx.getAffected ()) + for (auto const& affectedAccount: alTx.getAffected ()) { - SubInfoMapIterator simiIt = mSubRTAccount.find (affectedAccount.getAccountID ()); + auto simiIt = mSubRTAccount.find (affectedAccount.getAccountID ()); if (simiIt != mSubRTAccount.end ()) { - NetworkOPsImp::SubMapType::const_iterator it = simiIt->second.begin (); + auto it = simiIt->second.begin (); while (it != simiIt->second.end ()) { @@ -2675,8 +2685,8 @@ void NetworkOPsImp::unsubAccount (std::uint64_t uSeq, } } -bool NetworkOPsImp::subBook (InfoSub::ref isrListener, RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets) +bool NetworkOPsImp::subBook (InfoSub::ref isrListener, Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets) { BookListeners::pointer listeners = getApp().getOrderBookDB ().makeBookListeners (currencyPays, currencyGets, issuerPays, issuerGets); @@ -2689,7 +2699,7 @@ bool NetworkOPsImp::subBook (InfoSub::ref isrListener, RippleCurrency const& cur } bool NetworkOPsImp::unsubBook (std::uint64_t uSeq, - RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, RippleIssuer const& issuerPays, RippleIssuer const& issuerGets) + Currency const& currencyPays, Currency const& currencyGets, Account const& issuerPays, Account const& issuerGets) { BookListeners::pointer listeners = getApp().getOrderBookDB ().getBookListeners (currencyPays, currencyGets, issuerPays, issuerGets); @@ -2716,9 +2726,10 @@ std::uint32_t NetworkOPsImp::acceptLedger () return m_ledgerMaster.getCurrentLedger ()->getLedgerSeq (); } -void NetworkOPsImp::storeProposal (LedgerProposal::ref proposal, const RippleAddress& peerPublic) +void NetworkOPsImp::storeProposal ( + LedgerProposal::ref proposal, const RippleAddress& peerPublic) { - std::list& props = mStoredProposals[peerPublic.getNodeID ()]; + auto& props = mStoredProposals[peerPublic.getNodeID ()]; if (props.size () >= (unsigned) (mLastCloseProposers + 10)) props.pop_front (); @@ -2727,7 +2738,8 @@ void NetworkOPsImp::storeProposal (LedgerProposal::ref proposal, const RippleAdd } #if 0 -void NetworkOPsImp::subAccountChanges (InfoSub* isrListener, const uint256 uLedgerHash) +void NetworkOPsImp::subAccountChanges ( + InfoSub* isrListener, const uint256 uLedgerHash) { } @@ -2846,12 +2858,25 @@ InfoSub::pointer NetworkOPsImp::addRpcSub (const std::string& strUrl, InfoSub::r // work, but it demonstrated poor performance. // // FIXME : support iLimit. -void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTakerPaysCurrencyID, const uint160& uTakerPaysIssuerID, const uint160& uTakerGetsCurrencyID, const uint160& uTakerGetsIssuerID, const uint160& uTakerID, const bool bProof, const unsigned int iLimit, const Json::Value& jvMarker, Json::Value& jvResult) +void NetworkOPsImp::getBookPage ( + Ledger::pointer lpLedger, + Currency const& uTakerPaysCurrencyID, + Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrencyID, + Account const& uTakerGetsIssuerID, + Account const& uTakerID, + bool const bProof, + const unsigned int iLimit, + const Json::Value& jvMarker, + Json::Value& jvResult) { // CAUTION: This is the old get book page logic - Json::Value& jvOffers = (jvResult[jss::offers] = Json::Value (Json::arrayValue)); + Json::Value& jvOffers = + (jvResult[jss::offers] = Json::Value (Json::arrayValue)); - std::map umBalance; - const uint256 uBookBase = Ledger::getBookBase (uTakerPaysCurrencyID, uTakerPaysIssuerID, uTakerGetsCurrencyID, uTakerGetsIssuerID); + std::map umBalance; + const uint256 uBookBase = Ledger::getBookBase ( + uTakerPaysCurrencyID, uTakerPaysIssuerID, + uTakerGetsCurrencyID, uTakerGetsIssuerID); const uint256 uBookEnd = Ledger::getQualityNext (uBookBase); uint256 uTipIndex = uBookBase; @@ -2859,14 +2884,14 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker { m_journal.trace << "getBookPage:" << " uTakerPaysCurrencyID=" << - STAmount::createHumanCurrency (uTakerPaysCurrencyID) << + to_string (uTakerPaysCurrencyID) << " uTakerPaysIssuerID=" << - RippleAddress::createHumanAccountID (uTakerPaysIssuerID); + to_string (uTakerPaysIssuerID); m_journal.trace << "getBookPage:" << " uTakerGetsCurrencyID=" << - STAmount::createHumanCurrency (uTakerGetsCurrencyID) << + to_string (uTakerGetsCurrencyID) << " uTakerGetsIssuerID=" << - RippleAddress::createHumanAccountID (uTakerGetsIssuerID); + to_string (uTakerGetsIssuerID); m_journal.trace << "getBookPage: uBookBase=" << uBookBase; m_journal.trace << "getBookPage: uBookEnd=" << uBookEnd; m_journal.trace << "getBookPage: uTipIndex=" << uTipIndex; @@ -2918,14 +2943,17 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker if (!bDone) { - SLE::pointer sleOffer = lesActive.entryCache (ltOFFER, offerIndex); + auto sleOffer = lesActive.entryCache (ltOFFER, offerIndex); if (sleOffer) { - const uint160 uOfferOwnerID = sleOffer->getFieldAccount160 (sfAccount); - const STAmount& saTakerGets = sleOffer->getFieldAmount (sfTakerGets); - const STAmount& saTakerPays = sleOffer->getFieldAmount (sfTakerPays); - STAmount saOwnerFunds; + auto const uOfferOwnerID = + sleOffer->getFieldAccount160 (sfAccount); + auto const& saTakerGets = + sleOffer->getFieldAmount (sfTakerGets); + auto const& saTakerPays = + sleOffer->getFieldAmount (sfTakerPays); + STAmount saOwnerFunds; if (uTakerGetsIssuerID == uOfferOwnerID) { @@ -2934,22 +2962,25 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker } else { - std::map::const_iterator umBalanceEntry = umBalance.find (uOfferOwnerID); - + auto umBalanceEntry = umBalance.find (uOfferOwnerID); if (umBalanceEntry != umBalance.end ()) { // Found in running balance table. saOwnerFunds = umBalanceEntry->second; - // m_journal.info << boost::str(boost::format("getBookPage: saOwnerFunds=%s (cached)") % saOwnerFunds.getFullText()); + // m_journal.info << "getBookPage: saOwnerFunds=%s + // (cached)") % saOwnerFunds.getFullText()); } else { // Did not find balance in table. - saOwnerFunds = lesActive.accountHolds (uOfferOwnerID, uTakerGetsCurrencyID, uTakerGetsIssuerID); + saOwnerFunds = lesActive.accountHolds ( + uOfferOwnerID, uTakerGetsCurrencyID, + uTakerGetsIssuerID); - // m_journal.info << boost::str(boost::format("getBookPage: saOwnerFunds=%s (new)") % saOwnerFunds.getFullText()); + // m_journal.info << boost::format(getBookPage: + // saOwnerFunds=%s (new)") % saOwnerFunds.getFullText()); if (saOwnerFunds < zero) { // Treat negative funds as zero. @@ -2972,7 +3003,10 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker { // Need to charge a transfer fee to offer owner. uOfferRate = uTransferRate; - saOwnerFundsLimit = STAmount::divide (saOwnerFunds, STAmount (CURRENCY_ONE, ACCOUNT_ONE, uOfferRate, -9)); + saOwnerFundsLimit = STAmount::divide ( + saOwnerFunds, STAmount (noCurrency(), noAccount(), + uOfferRate, -9)); + // TODO(tom): why -9? } else { @@ -2987,20 +3021,14 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker } else { - // m_journal.info << boost::str(boost::format("getBookPage: saTakerGets=%s") % saTakerGets.getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: saTakerPays=%s") % saTakerPays.getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: saOwnerFunds=%s") % saOwnerFunds.getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: saDirRate=%s") % saDirRate.getText()); - // m_journal.info << boost::str(boost::format("getBookPage: multiply=%s") % STAmount::multiply(saTakerGetsFunded, saDirRate).getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: multiply=%s") % STAmount::multiply(saTakerGetsFunded, saDirRate, saTakerPays).getFullText()); - // Only provide, if not fully funded. saTakerGetsFunded = saOwnerFundsLimit; saTakerGetsFunded.setJson (jvOffer[jss::taker_gets_funded]); - std::min (saTakerPays, - STAmount::multiply (saTakerGetsFunded, saDirRate, saTakerPays)).setJson + std::min ( + saTakerPays, STAmount::multiply ( + saTakerGetsFunded, saDirRate, saTakerPays)).setJson (jvOffer[jss::taker_pays_funded]); } @@ -3010,7 +3038,8 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker saOwnerFunds, STAmount::multiply ( saTakerGetsFunded, - STAmount (CURRENCY_ONE, ACCOUNT_ONE, uOfferRate, -9))); + STAmount (noCurrency(), noAccount(), + uOfferRate, -9))); umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays; @@ -3048,21 +3077,33 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker // It has temporarily been disabled // FIXME : support iLimit. -void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTakerPaysCurrencyID, const uint160& uTakerPaysIssuerID, const uint160& uTakerGetsCurrencyID, const uint160& uTakerGetsIssuerID, const uint160& uTakerID, const bool bProof, const unsigned int iLimit, const Json::Value& jvMarker, Json::Value& jvResult) +void NetworkOPsImp::getBookPage ( + Ledger::pointer lpLedger, + Currency const& uTakerPaysCurrencyID, + Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrencyID, + Account const& uTakerGetsIssuerID, + Account const& uTakerID, + bool const bProof, + const unsigned int iLimit, + const Json::Value& jvMarker, + Json::Value& jvResult) { - Json::Value& jvOffers = (jvResult[jss::offers] = Json::Value (Json::arrayValue)); + auto& jvOffers = (jvResult[jss::offers] = Json::Value (Json::arrayValue)); - std::map umBalance; + std::map umBalance; LedgerEntrySet lesActive (lpLedger, tapNONE, true); - OrderBookIterator obIterator (lesActive, uTakerPaysCurrencyID, uTakerPaysIssuerID, uTakerGetsCurrencyID, uTakerGetsIssuerID); + OrderBookIterator obIterator ( + lesActive, uTakerPaysCurrencyID, uTakerPaysIssuerID, + uTakerGetsCurrencyID, uTakerGetsIssuerID); - unsigned int iLeft = iLimit; + unsigned int iLeft = iLimit; if ((iLeft == 0) || (iLeft > 300)) iLeft = 300; - std::uint32_t uTransferRate = lesActive.rippleTransferRate (uTakerGetsIssuerID); + auto uTransferRate = lesActive.rippleTransferRate (uTakerGetsIssuerID); while ((--iLeft > 0) && obIterator.nextOffer ()) { @@ -3070,11 +3111,11 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker SLE::pointer sleOffer = obIterator.getCurrentOffer(); if (sleOffer) { - const uint160 uOfferOwnerID = sleOffer->getFieldAccount160 (sfAccount); - const STAmount& saTakerGets = sleOffer->getFieldAmount (sfTakerGets); - const STAmount& saTakerPays = sleOffer->getFieldAmount (sfTakerPays); - STAmount saDirRate = obIterator.getCurrentRate (); - STAmount saOwnerFunds; + auto const uOfferOwnerID = sleOffer->getFieldAccount160 (sfAccount); + auto const& saTakerGets = sleOffer->getFieldAmount (sfTakerGets); + auto const& saTakerPays = sleOffer->getFieldAmount (sfTakerPays); + STAmount saDirRate = obIterator.getCurrentRate (); + STAmount saOwnerFunds; if (uTakerGetsIssuerID == uOfferOwnerID) { @@ -3083,22 +3124,21 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker } else { - std::map::const_iterator umBalanceEntry = umBalance.find (uOfferOwnerID); + auto umBalanceEntry = umBalance.find (uOfferOwnerID); if (umBalanceEntry != umBalance.end ()) { // Found in running balance table. saOwnerFunds = umBalanceEntry->second; - // m_journal.info << boost::str(boost::format("getBookPage: saOwnerFunds=%s (cached)") % saOwnerFunds.getFullText()); } else { // Did not find balance in table. - saOwnerFunds = lesActive.accountHolds (uOfferOwnerID, uTakerGetsCurrencyID, uTakerGetsIssuerID); + saOwnerFunds = lesActive.accountHolds ( + uOfferOwnerID, uTakerGetsCurrencyID, uTakerGetsIssuerID); - // m_journal.info << boost::str(boost::format("getBookPage: saOwnerFunds=%s (new)") % saOwnerFunds.getFullText()); if (saOwnerFunds.isNegative ()) { // Treat negative funds as zero. @@ -3115,13 +3155,18 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker std::uint32_t uOfferRate; - if (uTransferRate != QUALITY_ONE // Have a tranfer fee. - && uTakerID != uTakerGetsIssuerID // Not taking offers of own IOUs. - && uTakerGetsIssuerID != uOfferOwnerID) // Offer owner not issuing ownfunds + if (uTransferRate != QUALITY_ONE + // Have a tranfer fee. + && uTakerID != uTakerGetsIssuerID + // Not taking offers of own IOUs. + && uTakerGetsIssuerID != uOfferOwnerID) + // Offer owner not issuing ownfunds { // Need to charge a transfer fee to offer owner. - uOfferRate = uTransferRate; - saOwnerFundsLimit = STAmount::divide (saOwnerFunds, STAmount (CURRENCY_ONE, ACCOUNT_ONE, uOfferRate, -9)); + uOfferRate = uTransferRate; + // TODO(tom): where does -9 come from?! + STAmount amount (noCurrency(), noAccount(), uOfferRate, -9); + saOwnerFundsLimit = STAmount::divide (saOwnerFunds, amount); } else { @@ -3136,24 +3181,25 @@ void NetworkOPsImp::getBookPage (Ledger::pointer lpLedger, const uint160& uTaker } else { - // m_journal.info << boost::str(boost::format("getBookPage: saTakerGets=%s") % saTakerGets.getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: saTakerPays=%s") % saTakerPays.getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: saOwnerFunds=%s") % saOwnerFunds.getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: saDirRate=%s") % saDirRate.getText()); - // m_journal.info << boost::str(boost::format("getBookPage: multiply=%s") % STAmount::multiply(saTakerGetsFunded, saDirRate).getFullText()); - // m_journal.info << boost::str(boost::format("getBookPage: multiply=%s") % STAmount::multiply(saTakerGetsFunded, saDirRate, saTakerPays).getFullText()); - // Only provide, if not fully funded. - saTakerGetsFunded = saOwnerFundsLimit; saTakerGetsFunded.setJson (jvOffer[jss::taker_gets_funded]); - std::min (saTakerPays, STAmount::multiply (saTakerGetsFunded, saDirRate, saTakerPays)).setJson (jvOffer[jss::taker_pays_funded]); + + // TOOD(tom): The result of this expression is not used - what's + // going on here? + std::min (saTakerPays, STAmount::multiply ( + saTakerGetsFunded, saDirRate, saTakerPays)).setJson ( + jvOffer[jss::taker_pays_funded]); } - STAmount saOwnerPays = (QUALITY_ONE == uOfferRate) - ? saTakerGetsFunded - : std::min (saOwnerFunds, STAmount::multiply (saTakerGetsFunded, STAmount (CURRENCY_ONE, ACCOUNT_ONE, uOfferRate, -9))); + STAmount saOwnerPays = (uOfferRate == QUALITY_ONE) + ? saTakerGetsFunded + : std::min (saOwnerFunds, + STAmount::multiply ( + saTakerGetsFunded, STAmount ( + noCurrency(), noAccount(), uOfferRate, + -9))); umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays; diff --git a/src/ripple/module/app/misc/NetworkOPs.h b/src/ripple/module/app/misc/NetworkOPs.h index 080f049efe..2e357579cb 100644 --- a/src/ripple/module/app/misc/NetworkOPs.h +++ b/src/ripple/module/app/misc/NetworkOPs.h @@ -164,7 +164,7 @@ public: virtual AccountState::pointer getAccountState (Ledger::ref lrLedger, const RippleAddress& accountID) = 0; virtual SLE::pointer getGenerator (Ledger::ref lrLedger, - uint160 const& uGeneratorID) = 0; + Account const& uGeneratorID) = 0; //-------------------------------------------------------------------------- // @@ -190,12 +190,12 @@ public: virtual void getBookPage ( Ledger::pointer lpLedger, - const uint160& uTakerPaysCurrencyID, - const uint160& uTakerPaysIssuerID, - const uint160& uTakerGetsCurrencyID, - const uint160& uTakerGetsIssuerID, - const uint160& uTakerID, - const bool bProof, + Currency const& uTakerPaysCurrencyID, + Account const& uTakerPaysIssuerID, + Currency const& uTakerGetsCurrencyID, + Account const& uTakerGetsIssuerID, + Account const& uTakerID, + bool const bProof, const unsigned int iLimit, const Json::Value& jvMarker, Json::Value& jvResult) = 0; @@ -215,16 +215,16 @@ public: const std::string& source) = 0; virtual void takePosition (int seq, SHAMap::ref position) = 0; - + virtual SHAMap::pointer getTXMap (uint256 const& hash) = 0; virtual bool hasTXSet (const std::shared_ptr& peer, uint256 const& set, protocol::TxSetStatus status) = 0; virtual void mapComplete (uint256 const& hash, SHAMap::ref map) = 0; - + virtual bool stillNeedTXSet (uint256 const& hash) = 0; - + // Fetch packs virtual void makeFetchPack (Job&, std::weak_ptr peer, std::shared_ptr request, @@ -241,7 +241,7 @@ public: virtual void endConsensus (bool correctLCL) = 0; virtual void setStandAlone () = 0; virtual void setStateTimer () = 0; - + virtual void newLCL (int proposers, int convergeTime, uint256 const& ledgerHash) = 0; // VFALCO TODO rename to setNeedNetworkLedger virtual void needNetworkLedger () = 0; @@ -265,14 +265,15 @@ public: virtual Json::Value getLedgerFetchInfo () = 0; virtual std::uint32_t acceptLedger () = 0; - typedef ripple::unordered_map > Proposals; + typedef ripple::unordered_map > + Proposals; virtual Proposals& peekStoredProposals () = 0; virtual void storeProposal (LedgerProposal::ref proposal, const RippleAddress& peerPublic) = 0; virtual uint256 getConsensusLCL () = 0; - + virtual void reportFeeChange () = 0; virtual void updateLocalTx (Ledger::ref newValidLedger) = 0; diff --git a/src/ripple/module/app/misc/Offer.cpp b/src/ripple/module/app/misc/Offer.cpp index 2c0162b931..2c70887ed7 100644 --- a/src/ripple/module/app/misc/Offer.cpp +++ b/src/ripple/module/app/misc/Offer.cpp @@ -19,7 +19,8 @@ namespace ripple { -AccountItem::pointer Offer::makeItem (const uint160& , SerializedLedgerEntry::ref ledgerEntry) +AccountItem::pointer Offer::makeItem ( + Account const& , SerializedLedgerEntry::ref ledgerEntry) { if (!ledgerEntry || ledgerEntry->getType () != ltOFFER) return (AccountItem::pointer ()); diff --git a/src/ripple/module/app/misc/Offer.h b/src/ripple/module/app/misc/Offer.h index 9e373f6d0c..cbcd512f21 100644 --- a/src/ripple/module/app/misc/Offer.h +++ b/src/ripple/module/app/misc/Offer.h @@ -29,7 +29,8 @@ public: virtual ~Offer () {} - AccountItem::pointer makeItem (const uint160&, SerializedLedgerEntry::ref ledgerEntry); + AccountItem::pointer makeItem ( + Account const&, SerializedLedgerEntry::ref ledgerEntry); LedgerEntryType getType () { diff --git a/src/ripple/module/app/misc/OrderBook.cpp b/src/ripple/module/app/misc/OrderBook.cpp index 6433876353..222b62de20 100644 --- a/src/ripple/module/app/misc/OrderBook.cpp +++ b/src/ripple/module/app/misc/OrderBook.cpp @@ -20,10 +20,10 @@ namespace ripple { OrderBook::OrderBook (uint256 const& index, - uint160 const& currencyIn, - uint160 const& currencyOut, - uint160 const& issuerIn, - uint160 const& issuerOut) + Currency const& currencyIn, + Currency const& currencyOut, + Account const& issuerIn, + Account const& issuerOut) : mBookBase (index) , mCurrencyIn (currencyIn) , mCurrencyOut (currencyOut) diff --git a/src/ripple/module/app/misc/OrderBook.h b/src/ripple/module/app/misc/OrderBook.h index d484f66fa0..1c381ce4dc 100644 --- a/src/ripple/module/app/misc/OrderBook.h +++ b/src/ripple/module/app/misc/OrderBook.h @@ -27,7 +27,6 @@ class OrderBook : beast::LeakChecked { public: typedef std::shared_ptr pointer; - typedef std::shared_ptr const& ref; public: @@ -42,44 +41,42 @@ public: // VFALCO NOTE what is the meaning of the index parameter? // VFALCO TODO Replace with RippleAsset OrderBook (uint256 const& index, - uint160 const& currencyIn, - uint160 const& currencyOut, - uint160 const& issuerIn, - uint160 const& issuerOut); + Currency const& currencyIn, + Currency const& currencyOut, + Account const& issuerIn, + Account const& issuerOut); uint256 const& getBookBase () const { return mBookBase; } - uint160 const& getCurrencyIn () const + Currency const& getCurrencyIn () const { return mCurrencyIn; } - uint160 const& getCurrencyOut () const + Currency const& getCurrencyOut () const { return mCurrencyOut; } - uint160 const& getIssuerIn () const + Account const& getIssuerIn () const { return mIssuerIn; } - uint160 const& getIssuerOut () const + Account const& getIssuerOut () const { return mIssuerOut; } - private: - // VFALCO TODO Replace these with RippleAsset uint256 const mBookBase; - uint160 const mCurrencyIn; - uint160 const mCurrencyOut; - uint160 const mIssuerIn; - uint160 const mIssuerOut; + Currency const mCurrencyIn; + Currency const mCurrencyOut; + Account const mIssuerIn; + Account const mIssuerOut; }; } // ripple diff --git a/src/ripple/module/app/misc/SerializedLedger.cpp b/src/ripple/module/app/misc/SerializedLedger.cpp index 45d3abcb7d..926be6871d 100644 --- a/src/ripple/module/app/misc/SerializedLedger.cpp +++ b/src/ripple/module/app/misc/SerializedLedger.cpp @@ -183,15 +183,15 @@ RippleAddress SerializedLedgerEntry::getSecondOwner () std::vector SerializedLedgerEntry::getOwners () { std::vector owners; - uint160 account; + Account account; for (int i = 0, fields = getCount (); i < fields; ++i) { - SField::ref fc = getFieldSType (i); + auto const& fc = getFieldSType (i); if ((fc == sfAccount) || (fc == sfOwner)) { - const STAccount* entry = dynamic_cast (peekAtPIndex (i)); + auto entry = dynamic_cast (peekAtPIndex (i)); if ((entry != nullptr) && entry->getValueH160 (account)) owners.push_back (Ledger::getAccountRootIndex (account)); @@ -199,11 +199,11 @@ std::vector SerializedLedgerEntry::getOwners () if ((fc == sfLowLimit) || (fc == sfHighLimit)) { - const STAmount* entry = dynamic_cast (peekAtPIndex (i)); + auto entry = dynamic_cast (peekAtPIndex (i)); if ((entry != nullptr)) { - uint160 issuer = entry->getIssuer (); + auto issuer = entry->getIssuer (); if (issuer.isNonZero ()) owners.push_back (Ledger::getAccountRootIndex (issuer)); diff --git a/src/ripple/module/app/misc/SerializedTransaction.cpp b/src/ripple/module/app/misc/SerializedTransaction.cpp index 0add87fa48..47c71b07c9 100644 --- a/src/ripple/module/app/misc/SerializedTransaction.cpp +++ b/src/ripple/module/app/misc/SerializedTransaction.cpp @@ -133,7 +133,7 @@ std::vector SerializedTransaction::getMentionedAccounts () const if (sam) { - uint160 issuer = sam->getIssuer (); + auto issuer = sam->getIssuer (); if (issuer.isNonZero ()) { diff --git a/src/ripple/module/app/misc/Validations.cpp b/src/ripple/module/app/misc/Validations.cpp index f0fdcdcec1..72feea05e0 100644 --- a/src/ripple/module/app/misc/Validations.cpp +++ b/src/ripple/module/app/misc/Validations.cpp @@ -21,11 +21,6 @@ namespace ripple { -class ValidationsImp; - -typedef std::map::value_type u160_val_pair; -typedef std::shared_ptr VSpointer; - class ValidationsImp : public Validations { private: @@ -34,16 +29,16 @@ private: typedef beast::GenericScopedUnlock ScopedUnlockType; LockType mLock; - TaggedCache mValidations; - ripple::unordered_map mCurrentValidations; - std::vector mStaleValidations; + TaggedCache mValidations; + ValidationSet mCurrentValidations; + ValidationVector mStaleValidations; bool mWriting; private: std::shared_ptr findCreateSet (uint256 const& ledgerHash) { - VSpointer j = mValidations.fetch (ledgerHash); + auto j = mValidations.fetch (ledgerHash); if (!j) { @@ -91,8 +86,8 @@ private: ", hash=" << val->getLedgerHash () << ", shash=" << val->getSigningHash () << " src=" << source; } - uint256 hash = val->getLedgerHash (); - uint160 node = signer.getNodeID (); + auto hash = val->getLedgerHash (); + auto node = signer.getNodeID (); if (val->isTrusted () && isCurrent) { @@ -151,7 +146,7 @@ private: { { ScopedLockType sl (mLock); - VSpointer set = findSet (ledger); + auto set = findSet (ledger); if (set) return *set; @@ -163,12 +158,12 @@ private: { trusted = untrusted = 0; ScopedLockType sl (mLock); - VSpointer set = findSet (ledger); + auto set = findSet (ledger); if (set) { std::uint32_t now = getApp().getOPs ().getNetworkTimeNC (); - BOOST_FOREACH (u160_val_pair & it, *set) + for (auto& it: *set) { bool isTrusted = it.second->isTrusted (); @@ -198,11 +193,11 @@ private: { full = partial = 0; ScopedLockType sl (mLock); - VSpointer set = findSet (ledger); + auto set = findSet (ledger); if (set) { - BOOST_FOREACH (u160_val_pair & it, *set) + for (auto& it:*set) { if (it.second->isTrusted ()) { @@ -222,11 +217,11 @@ private: { int trusted = 0; ScopedLockType sl (mLock); - VSpointer set = findSet (ledger); + auto set = findSet (ledger); if (set) { - BOOST_FOREACH (u160_val_pair & it, *set) + for (auto& it: *set) { if (it.second->isTrusted ()) ++trusted; @@ -242,11 +237,11 @@ private: fee = 0; ScopedLockType sl (mLock); - VSpointer set = findSet (ledger); + auto set = findSet (ledger); if (set) { - BOOST_FOREACH (u160_val_pair & it, *set) + for (auto& it: *set) { if (it.second->isTrusted ()) { @@ -271,7 +266,7 @@ private: // Number of trusted nodes that have moved past this ledger int count = 0; ScopedLockType sl (mLock); - BOOST_FOREACH (u160_val_pair & it, mCurrentValidations) + for (auto& it: mCurrentValidations) { if (it.second->isTrusted () && it.second->isPreviousHash (ledger)) ++count; @@ -286,7 +281,7 @@ private: int badNodes = overLoaded ? 0 : 1; { ScopedLockType sl (mLock); - BOOST_FOREACH (u160_val_pair & it, mCurrentValidations) + for (auto& it: mCurrentValidations) { if (it.second->isTrusted ()) { @@ -307,7 +302,7 @@ private: std::list ret; ScopedLockType sl (mLock); - ripple::unordered_map::iterator it = mCurrentValidations.begin (); + auto it = mCurrentValidations.begin (); while (it != mCurrentValidations.end ()) { @@ -334,17 +329,17 @@ private: return ret; } - ripple::unordered_map - getCurrentValidations (uint256 currentLedger, uint256 priorLedger) + LedgerToValidationCounter getCurrentValidations ( + uint256 currentLedger, uint256 priorLedger) { std::uint32_t cutoff = getApp().getOPs ().getNetworkTimeNC () - LEDGER_VAL_INTERVAL; bool valCurrentLedger = currentLedger.isNonZero (); bool valPriorLedger = priorLedger.isNonZero (); - ripple::unordered_map ret; + LedgerToValidationCounter ret; ScopedLockType sl (mLock); - ripple::unordered_map::iterator it = mCurrentValidations.begin (); + auto it = mCurrentValidations.begin (); while (it != mCurrentValidations.end ()) { @@ -371,9 +366,9 @@ private: WriteLog (lsTRACE, Validations) << "Counting for " << currentLedger << " not " << it->second->getLedgerHash (); } - currentValidationCount& p = countPreferred ? ret[currentLedger] : ret[it->second->getLedgerHash ()]; + ValidationCounter& p = countPreferred ? ret[currentLedger] : ret[it->second->getLedgerHash ()]; ++ (p.first); - uint160 ni = it->second->getNodeID (); + auto ni = it->second->getNodeID (); if (ni > p.second) p.second = ni; @@ -391,7 +386,7 @@ private: WriteLog (lsINFO, Validations) << "Flushing validations"; ScopedLockType sl (mLock); - BOOST_FOREACH (u160_val_pair & it, mCurrentValidations) + for (auto& it: mCurrentValidations) { if (it.second) mStaleValidations.push_back (it.second); @@ -434,7 +429,7 @@ private: while (!mStaleValidations.empty ()) { - std::vector vector; + ValidationVector vector; vector.reserve (512); mStaleValidations.swap (vector); @@ -446,7 +441,7 @@ private: Serializer s (1024); db->executeSQL ("BEGIN TRANSACTION;"); - BOOST_FOREACH (SerializedValidation::ref it, vector) + for (auto it: vector) { s.erase (); it->add (s); diff --git a/src/ripple/module/app/misc/Validations.h b/src/ripple/module/app/misc/Validations.h index 585e36b575..15b49547ac 100644 --- a/src/ripple/module/app/misc/Validations.h +++ b/src/ripple/module/app/misc/Validations.h @@ -23,8 +23,13 @@ namespace ripple { // VFALCO TODO rename and move these typedefs into the Validations interface -typedef ripple::unordered_map ValidationSet; -typedef std::pair currentValidationCount; // nodes validating and highest node ID validating + +// nodes validating and highest node ID validating +typedef unordered_map ValidationSet; + +typedef std::pair ValidationCounter; +typedef unordered_map LedgerToValidationCounter; +typedef std::vector ValidationVector; class Validations : beast::LeakChecked { @@ -37,21 +42,26 @@ public: virtual ValidationSet getValidations (uint256 const& ledger) = 0; - virtual void getValidationCount (uint256 const& ledger, bool currentOnly, int& trusted, int& untrusted) = 0; - virtual void getValidationTypes (uint256 const& ledger, int& full, int& partial) = 0; + virtual void getValidationCount ( + uint256 const& ledger, bool currentOnly, int& trusted, + int& untrusted) = 0; + virtual void getValidationTypes ( + uint256 const& ledger, int& full, int& partial) = 0; virtual int getTrustedValidationCount (uint256 const& ledger) = 0; - virtual int getFeeAverage(uint256 const& ledger, std::uint64_t ref, std::uint64_t& fee) = 0; + virtual int getFeeAverage( + uint256 const& ledger, std::uint64_t ref, std::uint64_t& fee) = 0; virtual int getNodesAfter (uint256 const& ledger) = 0; virtual int getLoadRatio (bool overLoaded) = 0; // VFALCO TODO make a typedef for this ugly return value! - virtual ripple::unordered_map getCurrentValidations ( + virtual LedgerToValidationCounter getCurrentValidations ( uint256 currentLedger, uint256 previousLedger) = 0; - virtual std::list getCurrentTrustedValidations () = 0; + virtual std::list + getCurrentTrustedValidations () = 0; virtual void tune (int size, int age) = 0; diff --git a/src/ripple/module/app/paths/CalcNodeAdvance.cpp b/src/ripple/module/app/paths/CalcNodeAdvance.cpp index fb34d4b01e..284d78fbf3 100644 --- a/src/ripple/module/app/paths/CalcNodeAdvance.cpp +++ b/src/ripple/module/app/paths/CalcNodeAdvance.cpp @@ -67,21 +67,22 @@ TER nodeAdvance ( bool bDirectDirDirty = false; - if (!node.uDirectTip) + if (!node.currentDirectory_) { // Need to initialize current node. - node.uDirectTip = Ledger::getBookBase ( + node.currentDirectory_.copyFrom(Ledger::getBookBase ( previousNode.currency_, previousNode.issuer_, node.currency_, - node.issuer_); - node.uDirectEnd = Ledger::getQualityNext (node.uDirectTip); + node.issuer_)); + node.nextDirectory_.copyFrom( + Ledger::getQualityNext (node.currentDirectory_)); // TODO(tom): it seems impossible that any actual offers with // quality == 0 could occur - we should disallow them, and clear // sleDirectDir without the database call in the next line. - node.sleDirectDir = rippleCalc.mActiveLedger.entryCache ( - ltDIR_NODE, node.uDirectTip); + node.sleDirectDir = rippleCalc.mActiveLedger.entryCache ( + ltDIR_NODE, node.currentDirectory_); // Associated vars are dirty, if found it. bDirectDirDirty = !!node.sleDirectDir; @@ -93,8 +94,8 @@ TER nodeAdvance ( WriteLog (lsTRACE, RippleCalc) << "nodeAdvance: Initialize node:" - << " node.uDirectTip=" << node.uDirectTip - <<" node.uDirectEnd=" << node.uDirectEnd + << " node.currentDirectory_=" << node.currentDirectory_ + <<" node.nextDirectory_=" << node.nextDirectory_ << " node.bDirectAdvance=" << node.bDirectAdvance; } @@ -105,23 +106,23 @@ TER nodeAdvance ( { // This works because the Merkel radix tree is ordered by key so // we can go to the next one in O(1). - node.uDirectTip = rippleCalc.mActiveLedger.getNextLedgerIndex ( - node.uDirectTip, node.uDirectEnd); + node.currentDirectory_ = rippleCalc.mActiveLedger.getNextLedgerIndex ( + node.currentDirectory_, node.nextDirectory_); } bDirectDirDirty = true; node.bDirectAdvance = false; node.bDirectRestart = false; - if (node.uDirectTip != zero) + if (node.currentDirectory_ != zero) { // We didn't run off the end of this order book and found // another quality directory. WriteLog (lsTRACE, RippleCalc) - << "nodeAdvance: Quality advance: node.uDirectTip=" - << node.uDirectTip; + << "nodeAdvance: Quality advance: node.currentDirectory_=" + << node.currentDirectory_; - node.sleDirectDir = rippleCalc.mActiveLedger.entryCache (ltDIR_NODE, node.uDirectTip); + node.sleDirectDir = rippleCalc.mActiveLedger.entryCache (ltDIR_NODE, node.currentDirectory_); } else if (bReverse) { @@ -148,7 +149,7 @@ TER nodeAdvance ( { // Our quality changed since last iteration. // Use the rate from the directory. - node.saOfrRate = STAmount::setRate (Ledger::getQuality (node.uDirectTip)); + node.saOfrRate = STAmount::setRate (Ledger::getQuality (node.currentDirectory_)); // For correct ratio node.uEntry = 0; node.bEntryAdvance = true; @@ -182,7 +183,7 @@ TER nodeAdvance ( } } else if (!rippleCalc.mActiveLedger.dirNext ( - node.uDirectTip, node.sleDirectDir, node.uEntry, node.offerIndex_)) + node.currentDirectory_, node.sleDirectDir, node.uEntry, node.offerIndex_)) // This is the only place that offerIndex_ changes. { // Failed to find an entry in directory. @@ -239,7 +240,7 @@ TER nodeAdvance ( WriteLog (lsTRACE, RippleCalc) << "nodeAdvance: offerOwnerAccount_=" - << RippleAddress::createHumanAccountID (node.offerOwnerAccount_) + << to_string (node.offerOwnerAccount_) << " node.saTakerPays=" << node.saTakerPays << " node.saTakerGets=" << node.saTakerGets << " node.offerIndex_=" << node.offerIndex_; @@ -393,11 +394,11 @@ TER nodeAdvance ( // Consider source mentioned by current path state. WriteLog (lsTRACE, RippleCalc) << "nodeAdvance: remember=" - << RippleAddress::createHumanAccountID (node.offerOwnerAccount_) + << to_string (node.offerOwnerAccount_) << "/" - << STAmount::createHumanCurrency (node.currency_) + << to_string (node.currency_) << "/" - << RippleAddress::createHumanAccountID (node.issuer_); + << to_string (node.issuer_); pathState.reverse().insert (std::make_pair (asLine, nodeIndex)); } diff --git a/src/ripple/module/app/paths/CalcNodeDeliverFwd.cpp b/src/ripple/module/app/paths/CalcNodeDeliverFwd.cpp index 45ff46cdb4..8e0fa40ca0 100644 --- a/src/ripple/module/app/paths/CalcNodeDeliverFwd.cpp +++ b/src/ripple/module/app/paths/CalcNodeDeliverFwd.cpp @@ -36,7 +36,7 @@ TER nodeDeliverFwd ( const unsigned int nodeIndex, // 0 < nodeIndex < lastNodeIndex PathState& pathState, const bool bMultiQuality, - const uint160& uInAccountID, // --> Input owner's account. + Account const& uInAccountID, // --> Input owner's account. const STAmount& saInReq, // --> Amount to deliver. STAmount& saInAct, // <-- Amount delivered, this invokation. STAmount& saInFees) // <-- Fees charged, this invokation. @@ -50,7 +50,7 @@ TER nodeDeliverFwd ( // Don't deliver more than wanted. // Zeroed in reverse pass. if (bMultiQuality) - node.uDirectTip = 0; // Restart book searching. + node.currentDirectory_ = 0; // Restart book searching. else node.bDirectRestart = true; // Restart at same quality. @@ -200,9 +200,9 @@ TER nodeDeliverFwd ( WriteLog (lsTRACE, RippleCalc) << "nodeDeliverFwd: ? --> OFFER --> account:" << " offerOwnerAccount_=" - << RippleAddress::createHumanAccountID (node.offerOwnerAccount_) + << to_string (node.offerOwnerAccount_) << " nextNode.account_=" - << RippleAddress::createHumanAccountID (nextNode.account_) + << to_string (nextNode.account_) << " saOutPassAct=" << saOutPassAct << " saOutFunded=%s" << saOutFunded; @@ -264,7 +264,7 @@ TER nodeDeliverFwd ( // Do outbound debiting. // Send to issuer/limbo total amount including fees (issuer gets // fees). - auto id = !!node.currency_ ? Account(node.issuer_) : XRP_ACCOUNT; + auto id = !!node.currency_ ? Account(node.issuer_) : xrpIssuer(); auto outPassTotal = saOutPassAct + saOutPassFees; rippleCalc.mActiveLedger.accountSend (node.offerOwnerAccount_, id, outPassTotal); @@ -295,7 +295,8 @@ TER nodeDeliverFwd ( if (!previousNode.currency_ || uInAccountID != node.offerOwnerAccount_) { - auto id = !!previousNode.currency_ ? uInAccountID : ACCOUNT_XRP; + auto id = !isXRP(previousNode.currency_) ? + uInAccountID : xrpIssuer(); resultCode = rippleCalc.mActiveLedger.accountSend ( id, node.offerOwnerAccount_, saInPassAct); diff --git a/src/ripple/module/app/paths/CalcNodeDeliverRev.cpp b/src/ripple/module/app/paths/CalcNodeDeliverRev.cpp index d311dd7b41..52b8083191 100644 --- a/src/ripple/module/app/paths/CalcNodeDeliverRev.cpp +++ b/src/ripple/module/app/paths/CalcNodeDeliverRev.cpp @@ -40,7 +40,7 @@ TER nodeDeliverRev ( PathState& pathState, const bool bMultiQuality, // True, if not constrained to the same // or better quality. - const uint160& uOutAccountID, // --> Output owner's account. + Account const& uOutAccountID, // --> Output owner's account. const STAmount& saOutReq, // --> Funds requested to be // delivered for an increment. STAmount& saOutAct) // <-- Funds actually delivered for an @@ -48,20 +48,12 @@ TER nodeDeliverRev ( { TER resultCode = tesSUCCESS; - auto& previousNode = pathState.nodes()[nodeIndex - 1]; - auto& node = pathState.nodes()[nodeIndex]; + auto& previousNode = pathState.nodes()[nodeIndex - 1]; + auto& node = pathState.nodes()[nodeIndex]; + + STAmount& saPrvDlvReq = previousNode.saRevDeliver; - STAmount& saPrvDlvReq = previousNode.saRevDeliver; // Accumulation of what the previous node must deliver. - - uint256& uDirectTip = node.uDirectTip; - bool& bDirectRestart = node.bDirectRestart; - - if (bMultiQuality) - uDirectTip = 0; // Restart book searching. - else - bDirectRestart = true; // Restart at same quality. - // Possible optimization: Note this gets zeroed on each increment, ideally // only on first increment, then it could be a limit on the forward pass. saOutAct.clear (saOutReq); @@ -115,11 +107,11 @@ TER nodeDeliverRev ( WriteLog (lsTRACE, RippleCalc) << "nodeDeliverRev:" << " offerOwnerAccount_=" - << RippleAddress::createHumanAccountID (node.offerOwnerAccount_) + << to_string (node.offerOwnerAccount_) << " uOutAccountID=" - << RippleAddress::createHumanAccountID (uOutAccountID) + << to_string (uOutAccountID) << " node.issuer_=" - << RippleAddress::createHumanAccountID (node.issuer_) + << to_string (node.issuer_) << " node.transferRate_=" << node.transferRate_ << " saOutFeeRate=" << saOutFeeRate; diff --git a/src/ripple/module/app/paths/Calculators.h b/src/ripple/module/app/paths/Calculators.h index 089c5cb8b8..a7d5e3c724 100644 --- a/src/ripple/module/app/paths/Calculators.h +++ b/src/ripple/module/app/paths/Calculators.h @@ -121,7 +121,7 @@ TER nodeDeliverRev ( const unsigned int nodeIndex, PathState& pathState, const bool bMultiQuality, - const uint160& uOutAccountID, + Account const& uOutAccountID, const STAmount& saOutReq, STAmount& saOutAct); @@ -130,7 +130,7 @@ TER nodeDeliverFwd ( const unsigned int nodeIndex, PathState& pathState, const bool bMultiQuality, - const uint160& uInAccountID, + Account const& uInAccountID, const STAmount& saInReq, STAmount& saInAct, STAmount& saInFees); diff --git a/src/ripple/module/app/paths/ComputeAccountLiquidityForward.cpp b/src/ripple/module/app/paths/ComputeAccountLiquidityForward.cpp index 30c95739d0..9d859ad4f5 100644 --- a/src/ripple/module/app/paths/ComputeAccountLiquidityForward.cpp +++ b/src/ripple/module/app/paths/ComputeAccountLiquidityForward.cpp @@ -57,10 +57,10 @@ TER computeForwardLiquidityForAccount ( const bool previousNodeIsAccount = previousNode.isAccount(); const bool nextNodeIsAccount = nextNode.isAccount(); - const uint160& previousAccountID + Account const& previousAccountID = previousNodeIsAccount ? previousNode.account_ : node.account_; // Offers are always issue. - const uint160& nextAccountID + Account const& nextAccountID = nextNodeIsAccount ? nextNode.account_ : node.account_; std::uint32_t uQualityIn = nodeIndex @@ -153,9 +153,9 @@ TER computeForwardLiquidityForAccount ( WriteLog (lsTRACE, RippleCalc) << "computeForwardLiquidityForAccount: account --> ACCOUNT --> $ :" << " previousAccountID=" - << RippleAddress::createHumanAccountID (previousAccountID) + << to_string (previousAccountID) << " node.account_=" - << RippleAddress::createHumanAccountID (node.account_) + << to_string (node.account_) << " previousNode.saFwdRedeem:" << previousNode.saFwdRedeem << " previousNode.saFwdIssue:" << previousNode.saFwdIssue; @@ -167,7 +167,7 @@ TER computeForwardLiquidityForAccount ( ? previousNode.saFwdIssue // No fee. : STAmount::mulRound ( previousNode.saFwdIssue, - STAmount (CURRENCY_ONE, ACCOUNT_ONE, uQualityIn, -9), + STAmount (noCurrency(), noAccount(), uQualityIn, -9), true); // Amount to credit. // Amount to credit. Credit for less than received as a surcharge. @@ -329,7 +329,7 @@ TER computeForwardLiquidityForAccount ( node.saFwdDeliver = std::min ( node.saFwdDeliver, rippleCalc.mActiveLedger.accountHolds ( - node.account_, XRP_CURRENCY, XRP_ACCOUNT)); + node.account_, xrpCurrency(), xrpIssuer())); } @@ -360,7 +360,7 @@ TER computeForwardLiquidityForAccount ( // Deliver XRP to limbo. resultCode = rippleCalc.mActiveLedger.accountSend ( - node.account_, XRP_ACCOUNT, node.saFwdDeliver); + node.account_, xrpIssuer(), node.saFwdDeliver); } } } diff --git a/src/ripple/module/app/paths/ComputeAccountLiquidityReverse.cpp b/src/ripple/module/app/paths/ComputeAccountLiquidityReverse.cpp index b538dc6b8a..46ec8dfec5 100644 --- a/src/ripple/module/app/paths/ComputeAccountLiquidityReverse.cpp +++ b/src/ripple/module/app/paths/ComputeAccountLiquidityReverse.cpp @@ -60,9 +60,9 @@ TER computeReverseLiquidityForAccount ( const bool previousNodeIsAccount = !nodeIndex || previousNode.isAccount(); const bool nextNodeIsAccount = isFinalNode || nextNode.isAccount(); - const uint160& previousAccountID = previousNodeIsAccount + Account const& previousAccountID = previousNodeIsAccount ? previousNode.account_ : node.account_; - const uint160& nextAccountID = nextNodeIsAccount ? nextNode.account_ + Account const& nextAccountID = nextNodeIsAccount ? nextNode.account_ : node.account_; // Offers are always issue. // This is the quality from from the previous node to this one. diff --git a/src/ripple/module/app/paths/ComputeLiquidity.cpp b/src/ripple/module/app/paths/ComputeLiquidity.cpp index edabb86ff4..0dc42db6fc 100644 --- a/src/ripple/module/app/paths/ComputeLiquidity.cpp +++ b/src/ripple/module/app/paths/ComputeLiquidity.cpp @@ -96,7 +96,7 @@ TER computeReverseLiqudity ( WriteLog (lsTRACE, RippleCalc) << "computeReverseLiqudity>" << " nodeIndex=" << nodeIndex - << " issuer_=" << RippleAddress::createHumanAccountID (node.issuer_) + << " issuer_=" << to_string (node.issuer_) << " transferRate_=" << node.transferRate_; auto resultCode = node.isAccount() diff --git a/src/ripple/module/app/paths/ComputeRippleLiquidity.cpp b/src/ripple/module/app/paths/ComputeRippleLiquidity.cpp index 1eb3a52df3..a620a68b52 100644 --- a/src/ripple/module/app/paths/ComputeRippleLiquidity.cpp +++ b/src/ripple/module/app/paths/ComputeRippleLiquidity.cpp @@ -134,8 +134,8 @@ void computeRippleLiquidity ( // If the next rate is at least as good as the current rate, process. if (!uRateMax || uRate <= uRateMax) { - const uint160 currency = saCur.getCurrency (); - const uint160 uCurIssuerID = saCur.getIssuer (); + auto currency = saCur.getCurrency (); + auto uCurIssuerID = saCur.getIssuer (); // current actual = current request * (quality out / quality in). auto numerator = STAmount::mulRound ( diff --git a/src/ripple/module/app/paths/Node.cpp b/src/ripple/module/app/paths/Node.cpp index f4c67550ce..78a20bd68a 100644 --- a/src/ripple/module/app/paths/Node.cpp +++ b/src/ripple/module/app/paths/Node.cpp @@ -64,13 +64,13 @@ Json::Value Node::getJson () const jvNode["flags"] = jvFlags; if (!!account_) - jvNode["account"] = RippleAddress::createHumanAccountID (account_); + jvNode["account"] = to_string (account_); if (!!currency_) - jvNode["currency"] = STAmount::createHumanCurrency (currency_); + jvNode["currency"] = to_string (currency_); if (!!issuer_) - jvNode["issuer"] = RippleAddress::createHumanAccountID (issuer_); + jvNode["issuer"] = to_string (issuer_); if (saRevRedeem) jvNode["rev_redeem"] = saRevRedeem.getFullText (); diff --git a/src/ripple/module/app/paths/Node.h b/src/ripple/module/app/paths/Node.h index 554f78afe2..ca6e21d16d 100644 --- a/src/ripple/module/app/paths/Node.h +++ b/src/ripple/module/app/paths/Node.h @@ -21,6 +21,7 @@ #define RIPPLE_APP_PATH_NODE_H #include +#include namespace ripple { namespace path { @@ -77,12 +78,14 @@ struct Node // https://ripple.com/wiki/Ledger_Format#Prioritizing_a_continuous_key_space // Current directory - the last 64 bits of this are the quality. - uint256 uDirectTip; + uint256 currentDirectory_; // Start of the next order book - one past the worst quality possible for // the current order book. - uint256 uDirectEnd; + uint256 nextDirectory_; + // TODO(tom): currentDirectory_ and nextDirectory_ should be of type + // Directory. bool bDirectAdvance; // Need to advance directory. bool bDirectRestart; // Need to restart directory. diff --git a/src/ripple/module/app/paths/PathRequest.cpp b/src/ripple/module/app/paths/PathRequest.cpp index 6488486ebc..a675a2e6ee 100644 --- a/src/ripple/module/app/paths/PathRequest.cpp +++ b/src/ripple/module/app/paths/PathRequest.cpp @@ -20,6 +20,7 @@ #include #include +#include #include namespace ripple { @@ -43,14 +44,18 @@ const std::shared_ptr& subscriber, int id, PathRequests& owner, ptCreated = boost::posix_time::microsec_clock::universal_time (); } -static std::string const get_milli_diff (boost::posix_time::ptime const& after, boost::posix_time::ptime const& before) +static std::string const get_milli_diff ( + boost::posix_time::ptime const& after, boost::posix_time::ptime + const& before) { - return beast::lexicalCastThrow (static_cast ((after - before).total_milliseconds())); + return beast::lexicalCastThrow ( + static_cast ((after - before).total_milliseconds())); } static std::string const get_milli_diff (boost::posix_time::ptime const& before) { - return get_milli_diff(boost::posix_time::microsec_clock::universal_time(), before); + return get_milli_diff( + boost::posix_time::microsec_clock::universal_time(), before); } PathRequest::~PathRequest() @@ -165,11 +170,11 @@ bool PathRequest::isValid (RippleLineCache::ref crCache) bool const disallowXRP ( asDst->peekSLE ().getFlags() & lsfDisallowXRP); - boost::unordered_set usDestCurrID = + CurrencySet usDestCurrID = usAccountDestCurrencies (raDstAccount, crCache, !disallowXRP); for (auto const& currency : usDestCurrID) - jvDestCur.append (STAmount::createHumanCurrency (currency)); + jvDestCur.append (to_string (currency)); jvStatus["destination_tag"] = (asDst->peekSLE ().getFlags () & lsfRequireDestTag) != 0; } @@ -256,7 +261,7 @@ int PathRequest::parseJson (const Json::Value& jvParams, bool complete) { if (!saDstAmount.bSetJson (jvParams["destination_amount"]) || (saDstAmount.getCurrency ().isZero () && saDstAmount.getIssuer ().isNonZero ()) || - (saDstAmount.getCurrency () == CURRENCY_BAD) || + (saDstAmount.getCurrency () == badCurrency()) || saDstAmount <= zero) { jvStatus = rpcError (rpcDST_AMT_MALFORMED); @@ -284,15 +289,18 @@ int PathRequest::parseJson (const Json::Value& jvParams, bool complete) for (unsigned i = 0; i < jvSrcCur.size (); ++i) { const Json::Value& jvCur = jvSrcCur[i]; - uint160 uCur, uIss; + Currency uCur; + Account uIss; - if (!jvCur.isObject() || !jvCur.isMember ("currency") || !STAmount::currencyFromString (uCur, jvCur["currency"].asString ())) + if (!jvCur.isObject() || !jvCur.isMember ("currency") || + !to_currency (uCur, jvCur["currency"].asString ())) { jvStatus = rpcError (rpcSRC_CUR_MALFORMED); return PFR_PJ_INVALID; } - if (jvCur.isMember ("issuer") && !STAmount::issuerFromString (uIss, jvCur["issuer"].asString ())) + if (jvCur.isMember ("issuer") && + !to_issuer (uIss, jvCur["issuer"].asString ())) { jvStatus = rpcError (rpcSRC_ISR_MALFORMED); } @@ -303,7 +311,7 @@ int PathRequest::parseJson (const Json::Value& jvParams, bool complete) return PFR_PJ_INVALID; } - sciSourceCurrencies.insert (currIssuer_t (uCur, uIss)); + sciSourceCurrencies.insert ({uCur, uIss}); } } @@ -341,19 +349,19 @@ Json::Value PathRequest::doUpdate (RippleLineCache::ref cache, bool fast) return jvStatus; jvStatus = Json::objectValue; - std::set sourceCurrencies (sciSourceCurrencies); + auto sourceCurrencies = sciSourceCurrencies; if (sourceCurrencies.empty ()) { - boost::unordered_set usCurrencies = - usAccountSourceCurrencies (raSrcAccount, cache, true); + auto usCurrencies = + usAccountSourceCurrencies (raSrcAccount, cache, true); bool sameAccount = raSrcAccount == raDstAccount; - BOOST_FOREACH (const uint160 & c, usCurrencies) + for (auto const& c: usCurrencies) { if (!sameAccount || (c != saDstAmount.getCurrency ())) { if (c.isZero ()) - sourceCurrencies.insert (std::make_pair (c, XRP_ACCOUNT)); + sourceCurrencies.insert (std::make_pair (c, xrpIssuer())); else sourceCurrencies.insert (std::make_pair (c, raSrcAccount.getAccountID ())); } @@ -387,7 +395,8 @@ Json::Value PathRequest::doUpdate (RippleLineCache::ref cache, bool fast) } else if (bLastSuccess) { // decrement, if possible - if ((iLevel > getConfig().PATH_SEARCH) || (loaded && (iLevel > getConfig().PATH_SEARCH_FAST))) + if (iLevel > getConfig().PATH_SEARCH || + (loaded && (iLevel > getConfig().PATH_SEARCH_FAST))) --iLevel; } else @@ -402,18 +411,23 @@ Json::Value PathRequest::doUpdate (RippleLineCache::ref cache, bool fast) bool found = false; - BOOST_FOREACH (const currIssuer_t & currIssuer, sourceCurrencies) + for (auto const& currIssuer: sourceCurrencies) { { STAmount test (currIssuer.first, currIssuer.second, 1); if (m_journal.debug) - m_journal.debug << iIdentifier << " Trying to find paths: " << test.getFullText (); + { + m_journal.debug + << iIdentifier + << " Trying to find paths: " << test.getFullText (); + } } bool valid; STPathSet& spsPaths = mContext[currIssuer]; Pathfinder pf (cache, raSrcAccount, raDstAccount, currIssuer.first, currIssuer.second, saDstAmount, valid); - CondLog (!valid, lsDEBUG, PathRequest) << iIdentifier << " PF request not valid"; + CondLog (!valid, lsDEBUG, PathRequest) + << iIdentifier << " PF request not valid"; STPath extraPath; if (valid && pf.findPaths (iLevel, 4, spsPaths, extraPath)) @@ -422,28 +436,34 @@ Json::Value PathRequest::doUpdate (RippleLineCache::ref cache, bool fast) PathState::List pathStateList; STAmount saMaxAmountAct; STAmount saDstAmountAct; - STAmount saMaxAmount (currIssuer.first, - currIssuer.second.isNonZero () ? currIssuer.second : - (currIssuer.first.isZero () ? ACCOUNT_XRP : - raSrcAccount.getAccountID ()), 1); + STAmount saMaxAmount ( + currIssuer.first, + currIssuer.second.isNonZero () ? Account(currIssuer.second) : + (currIssuer.first.isZero () ? xrpIssuer() : + raSrcAccount.getAccountID ()), 1); + saMaxAmount.negate (); m_journal.debug << iIdentifier << " Paths found, calling rippleCalc"; - TER resultCode = path::rippleCalculate (lesSandbox, saMaxAmountAct, saDstAmountAct, - pathStateList, saMaxAmount, saDstAmount, - raDstAccount.getAccountID (), raSrcAccount.getAccountID (), - spsPaths, false, false, false, true); - + TER resultCode = path::rippleCalculate ( + lesSandbox, saMaxAmountAct, saDstAmountAct, + pathStateList, saMaxAmount, saDstAmount, + raDstAccount.getAccountID (), raSrcAccount.getAccountID (), + spsPaths, false, false, false, true); if ((extraPath.size() > 0) && ((resultCode == terNO_LINE) || (resultCode == tecPATH_PARTIAL))) { - m_journal.debug << iIdentifier << " Trying with an extra path element"; + m_journal.debug + << iIdentifier << " Trying with an extra path element"; spsPaths.addPath(extraPath); pathStateList.clear (); - resultCode = path::rippleCalculate (lesSandbox, saMaxAmountAct, saDstAmountAct, - pathStateList, saMaxAmount, saDstAmount, - raDstAccount.getAccountID (), raSrcAccount.getAccountID (), - spsPaths, false, false, false, true); - m_journal.debug << iIdentifier << " Extra path element gives " << transHuman (resultCode); + resultCode = path::rippleCalculate ( + lesSandbox, saMaxAmountAct, saDstAmountAct, + pathStateList, saMaxAmount, saDstAmount, + raDstAccount.getAccountID (), raSrcAccount.getAccountID (), + spsPaths, false, false, false, true); + m_journal.debug + << iIdentifier << " Extra path element gives " + << transHuman (resultCode); } if (resultCode == tesSUCCESS) @@ -456,7 +476,8 @@ Json::Value PathRequest::doUpdate (RippleLineCache::ref cache, bool fast) } else { - m_journal.debug << iIdentifier << " rippleCalc returns " << transHuman (resultCode); + m_journal.debug << iIdentifier << " rippleCalc returns " + << transHuman (resultCode); } } else diff --git a/src/ripple/module/app/paths/PathRequest.h b/src/ripple/module/app/paths/PathRequest.h index 3c94b7e241..bd79fde673 100644 --- a/src/ripple/module/app/paths/PathRequest.h +++ b/src/ripple/module/app/paths/PathRequest.h @@ -44,7 +44,9 @@ public: typedef std::shared_ptr pointer; typedef const pointer& ref; typedef const wptr& wref; - typedef std::pair currIssuer_t; + + // TODO(tom): Use RippleAsset instead! + typedef std::pair CurrencyIssuer; public: // VFALCO TODO Break the cyclic dependency on InfoSub @@ -88,9 +90,9 @@ private: RippleAddress raSrcAccount; RippleAddress raDstAccount; STAmount saDstAmount; - std::set sciSourceCurrencies; + std::set sciSourceCurrencies; // std::vector vjvBridges; - std::map mContext; + std::map mContext; bool bValid; diff --git a/src/ripple/module/app/paths/PathState.cpp b/src/ripple/module/app/paths/PathState.cpp index 79a7a494a7..5d92a9e5fb 100644 --- a/src/ripple/module/app/paths/PathState.cpp +++ b/src/ripple/module/app/paths/PathState.cpp @@ -78,7 +78,7 @@ TER PathState::pushImpliedNodes ( if (nodes_.back ().currency_ != currency) { // Currency is different, need to convert via an offer from an order - // book. XRP_ACCOUNT does double duty as signaling "this is an order + // book. xrpIssuer() does double duty as signaling "this is an order // book". // Corresponds to "Implies an offer directory" in the diagram, currently @@ -88,8 +88,8 @@ TER PathState::pushImpliedNodes ( : STPathElement::typeCurrency | STPathElement::typeIssuer; // The offer's output is what is now wanted. - // XRP_ACCOUNT is a placeholder for offers. - resultCode = pushNode (type, XRP_ACCOUNT, currency, issuer); + // xrpIssuer() is a placeholder for offers. + resultCode = pushNode (type, xrpIssuer(), currency, issuer); } @@ -193,7 +193,7 @@ TER PathState::pushNode ( ? issuer : !!node.currency_ // Not XRP. ? account - : XRP_ACCOUNT; + : xrpIssuer(); // Zero value - for accounts. node.saRevRedeem = STAmount (node.currency_, account); node.saRevIssue = node.saRevRedeem; @@ -220,7 +220,7 @@ TER PathState::pushNode ( resultCode = pushImpliedNodes ( node.account_, node.currency_, - isXRP(node.currency_) ? XRP_ACCOUNT : account); + isXRP(node.currency_) ? xrpIssuer() : account); // Note: previousNode may no longer be the immediately previous node. } @@ -322,7 +322,7 @@ TER PathState::pushNode ( ? Account(previousNode.issuer_) // Default to previous issuer : Account(previousNode.account_) // Or previous account if no previous issuer. - : XRP_ACCOUNT; + : xrpIssuer(); node.saRateMax = saZero; node.saRevDeliver = STAmount (node.currency_, node.issuer_); node.saFwdDeliver = node.saRevDeliver; @@ -345,7 +345,7 @@ TER PathState::pushNode ( // Insert intermediary issuer account if needed. resultCode = pushImpliedNodes ( - XRP_ACCOUNT, // Rippling, but offers don't have an account. + xrpIssuer(), // Rippling, but offers don't have an account. previousNode.currency_, previousNode.issuer_); } @@ -386,10 +386,10 @@ void PathState::expandPath ( const Currency uMaxCurrencyID = saInReq.getCurrency (); const Account uMaxIssuerID = saInReq.getIssuer (); - const Currency uOutCurrencyID = saOutReq.getCurrency (); - const Account uOutIssuerID = saOutReq.getIssuer (); + const Currency currencyOutID = saOutReq.getCurrency (); + const Account issuerOutID = saOutReq.getIssuer (); const Account uSenderIssuerID - = isXRP(uMaxCurrencyID) ? XRP_ACCOUNT : uSenderID; + = isXRP(uMaxCurrencyID) ? xrpIssuer() : uSenderID; // Sender is always issuer for non-XRP. WriteLog (lsTRACE, RippleCalc) @@ -401,7 +401,7 @@ void PathState::expandPath ( // XRP with issuer is malformed. if ((!uMaxCurrencyID && !!uMaxIssuerID) - || (!uOutCurrencyID && !!uOutIssuerID)) + || (!currencyOutID && !!issuerOutID)) { terStatus = temBAD_PATH; } @@ -439,18 +439,18 @@ void PathState::expandPath ( const auto uNxtCurrencyID = spSourcePath.size () ? Currency(spSourcePath.getElement (0).getCurrency ()) // Use next node. - : uOutCurrencyID; + : currencyOutID; // Use send. // TODO(tom): complexify this next logic further in case someone // understands it. const auto nextAccountID = spSourcePath.size () ? Account(spSourcePath.getElement (0).getAccountID ()) - : !isXRP(uOutCurrencyID) - ? (uOutIssuerID == uReceiverID) + : !isXRP(currencyOutID) + ? (issuerOutID == uReceiverID) ? Account(uReceiverID) - : Account(uOutIssuerID) // Use implied node. - : XRP_ACCOUNT; + : Account(issuerOutID) // Use implied node. + : xrpIssuer(); WriteLog (lsDEBUG, RippleCalc) << "expandPath: implied check:" @@ -500,28 +500,28 @@ void PathState::expandPath ( auto const& previousNode = nodes_.back (); if (terStatus == tesSUCCESS - && !isXRP(uOutCurrencyID) // Next is not XRP - && uOutIssuerID != uReceiverID // Out issuer is not receiver - && (previousNode.currency_ != uOutCurrencyID + && !isXRP(currencyOutID) // Next is not XRP + && issuerOutID != uReceiverID // Out issuer is not receiver + && (previousNode.currency_ != currencyOutID // Previous will be an offer. - || previousNode.account_ != uOutIssuerID)) + || previousNode.account_ != issuerOutID)) // Need the implied issuer. { // Add implied account. WriteLog (lsDEBUG, RippleCalc) << "expandPath: receiver implied:" - << " account=" << uOutIssuerID - << " currency=" << uOutCurrencyID - << " issuer=" << uOutIssuerID; + << " account=" << issuerOutID + << " currency=" << currencyOutID + << " issuer=" << issuerOutID; terStatus = pushNode ( - !isXRP(uOutCurrencyID) + !isXRP(currencyOutID) ? STPathElement::typeAccount | STPathElement::typeCurrency | STPathElement::typeIssuer : STPathElement::typeAccount | STPathElement::typeCurrency, - uOutIssuerID, - uOutCurrencyID, - uOutIssuerID); + issuerOutID, + currencyOutID, + issuerOutID); } if (terStatus == tesSUCCESS) @@ -530,12 +530,12 @@ void PathState::expandPath ( // Last node is always an account. terStatus = pushNode ( - !isXRP(uOutCurrencyID) + !isXRP(currencyOutID) ? STPathElement::typeAccount | STPathElement::typeCurrency | STPathElement::typeIssuer : STPathElement::typeAccount | STPathElement::typeCurrency, uReceiverID, // Receive to output - uOutCurrencyID, // Desired currency + currencyOutID, // Desired currency uReceiverID); } @@ -568,8 +568,8 @@ void PathState::expandPath ( << "expandPath:" << " in=" << uMaxCurrencyID << "/" << uMaxIssuerID - << " out=" << uOutCurrencyID - << "/" << uOutIssuerID + << " out=" << currencyOutID + << "/" << issuerOutID << ": " << getJson (); } @@ -679,14 +679,14 @@ void PathState::checkNoRipple ( // Loop through all nodes that have a prior node and successor nodes // These are the nodes whose no ripple constratints could be violated - for (int i = 1; i < nodes_.size() - 1; ++i) + for (auto i = 1; i < nodes_.size() - 1; ++i) { if (nodes_[i - 1].isAccount() && nodes_[i].isAccount() && nodes_[i + 1].isAccount()) { // Two consecutive account-to-account links - uint160 const& currencyID = nodes_[i].currency_; + auto const& currencyID = nodes_[i].currency_; if ((nodes_[i-1].currency_ != currencyID) || (nodes_[i+1].currency_ != currencyID)) { diff --git a/src/ripple/module/app/paths/PathState.h b/src/ripple/module/app/paths/PathState.h index 6ee567a62e..04a2d3eec0 100644 --- a/src/ripple/module/app/paths/PathState.h +++ b/src/ripple/module/app/paths/PathState.h @@ -32,9 +32,6 @@ class PathState : public CountedObject typedef std::vector OfferIndexList; typedef std::vector> List; - typedef path::Account Account; - typedef path::Currency Currency; - PathState (const STAmount& saSend, const STAmount& saSendMax) : saInReq (saSendMax) , saOutReq (saSend) diff --git a/src/ripple/module/app/paths/Pathfinder.cpp b/src/ripple/module/app/paths/Pathfinder.cpp index 8e0cd30944..f9ac5870fc 100644 --- a/src/ripple/module/app/paths/Pathfinder.cpp +++ b/src/ripple/module/app/paths/Pathfinder.cpp @@ -28,7 +28,8 @@ we just need to find a succession of the highest quality paths there until we fi Don't do branching within each path -We have a list of paths we are working on but how do we compare the ones that are terminating in a different currency? +We have a list of paths we are working on but how do we compare the ones that +are terminating in a different currency? Loops @@ -81,8 +82,12 @@ static bool bQualityCmp (const path_LQ_t& a, const path_LQ_t& b) return std::get<3> (a) > std::get<3> (b); } -typedef std::pair candidate_t; -static bool candCmp (std::uint32_t seq, const candidate_t& first, const candidate_t& second) +typedef std::pair AccountCandidate; +typedef std::vector AccountCandidates; + +static bool candCmp ( + std::uint32_t seq, + const AccountCandidate& first, const AccountCandidate& second) { if (first.first < second.first) return false; @@ -93,9 +98,14 @@ static bool candCmp (std::uint32_t seq, const candidate_t& first, const candidat return (first.first ^ seq) < (second.first ^ seq); } -Pathfinder::Pathfinder (RippleLineCache::ref cache, - const RippleAddress& uSrcAccountID, const RippleAddress& uDstAccountID, - const uint160& uSrcCurrencyID, const uint160& uSrcIssuerID, const STAmount& saDstAmount, bool& bValid) +Pathfinder::Pathfinder ( + RippleLineCache::ref cache, + const RippleAddress& uSrcAccountID, + const RippleAddress& uDstAccountID, + Currency const& uSrcCurrencyID, + Account const& uSrcIssuerID, + const STAmount& saDstAmount, + bool& bValid) : mSrcAccountID (uSrcAccountID.getAccountID ()), mDstAccountID (uDstAccountID.getAccountID ()), mDstAmount (saDstAmount), @@ -105,7 +115,8 @@ Pathfinder::Pathfinder (RippleLineCache::ref cache, mLedger (cache->getLedger ()), mRLCache (cache) { - if ((mSrcAccountID == mDstAccountID && mSrcCurrencyID == mDstAmount.getCurrency ()) || mDstAmount == zero) + if ((mSrcAccountID == mDstAccountID && + mSrcCurrencyID == mDstAmount.getCurrency ()) || mDstAmount == zero) { // no need to send to same account with same currency, must send non-zero bValid = false; @@ -115,26 +126,37 @@ Pathfinder::Pathfinder (RippleLineCache::ref cache, bValid = true; - m_loadEvent = getApp().getJobQueue ().getLoadEvent (jtPATH_FIND, "FindPath"); - - bool bIssuer = mSrcCurrencyID.isNonZero() && mSrcIssuerID.isNonZero() && (mSrcIssuerID != mSrcAccountID); - mSource = STPathElement( // Where does an empty path start? - bIssuer ? mSrcIssuerID : mSrcAccountID, // On the source account or issuer account - mSrcCurrencyID, // In the source currency - mSrcCurrencyID.isZero() ? uint160() : (bIssuer ? mSrcIssuerID : mSrcAccountID)); + m_loadEvent = getApp().getJobQueue ().getLoadEvent ( + jtPATH_FIND, "FindPath"); + bool bIssuer = mSrcCurrencyID.isNonZero() && + mSrcIssuerID.isNonZero() && + (mSrcIssuerID != mSrcAccountID); + mSource = STPathElement( + // Where does an empty path start? + bIssuer ? mSrcIssuerID : mSrcAccountID, + // On the source account or issuer account + mSrcCurrencyID, + // In the source currency + mSrcCurrencyID.isZero() ? Account() : + (bIssuer ? mSrcIssuerID : mSrcAccountID)); } -bool Pathfinder::findPaths (int iLevel, const unsigned int iMaxPaths, STPathSet& pathsOut, STPath& extraPath) -{ // pathsOut contains only non-default paths without source or destiation -// On input, pathsOut contains any paths you want to ensure are included if still good +bool Pathfinder::findPaths ( + int iLevel, const unsigned int iMaxPaths, + STPathSet& pathsOut, STPath& extraPath) +{ + // pathsOut contains only non-default paths without source or + // destination. On input, pathsOut contains any paths you want to ensure are + // included if still good. - WriteLog (lsTRACE, Pathfinder) << "findPaths>" - " mSrcAccountID=" << RippleAddress::createHumanAccountID (mSrcAccountID) << - " mDstAccountID=" << RippleAddress::createHumanAccountID (mDstAccountID) << - " mDstAmount=" << mDstAmount.getFullText () << - " mSrcCurrencyID=" << STAmount::createHumanCurrency (mSrcCurrencyID) << - " mSrcIssuerID=" << RippleAddress::createHumanAccountID (mSrcIssuerID); + WriteLog (lsTRACE, Pathfinder) + << "findPaths>" + << " mSrcAccountID=" << mSrcAccountID + << " mDstAccountID=" << mDstAccountID + << " mDstAmount=" << mDstAmount.getFullText () + << " mSrcCurrencyID=" << mSrcCurrencyID + << " mSrcIssuerID=" << mSrcIssuerID; if (!mLedger) { @@ -146,11 +168,11 @@ bool Pathfinder::findPaths (int iLevel, const unsigned int iMaxPaths, STPathSet& bool bSrcXrp = mSrcCurrencyID.isZero(); bool bDstXrp = mDstAmount.getCurrency().isZero(); - SLE::pointer sleSrc = mLedger->getSLEi(Ledger::getAccountRootIndex(mSrcAccountID)); + auto sleSrc = mLedger->getSLEi(Ledger::getAccountRootIndex(mSrcAccountID)); if (!sleSrc) return false; - SLE::pointer sleDest = mLedger->getSLEi(Ledger::getAccountRootIndex(mDstAccountID)); + auto sleDest = mLedger->getSLEi(Ledger::getAccountRootIndex(mDstAccountID)); if (!sleDest && (!bDstXrp || (mDstAmount < mLedger->getReserve(0)))) return false; @@ -199,7 +221,8 @@ bool Pathfinder::findPaths (int iLevel, const unsigned int iMaxPaths, STPathSet& } } - WriteLog (lsDEBUG, Pathfinder) << mCompletePaths.size() << " complete paths found"; + WriteLog (lsDEBUG, Pathfinder) + << mCompletePaths.size() << " complete paths found"; BOOST_FOREACH(const STPath& path, pathsOut) { // make sure no paths were lost @@ -226,7 +249,9 @@ bool Pathfinder::findPaths (int iLevel, const unsigned int iMaxPaths, STPathSet& else pathsOut = mCompletePaths; - return true; // Even if we find no paths, default paths may work, and we don't check them currently + // Even if we find no paths, default paths may work, and we don't check them + // currently. + return true; } STPathSet Pathfinder::filterPaths(int iMaxPaths, STPath& extraPath) @@ -260,12 +285,14 @@ STPathSet Pathfinder::filterPaths(int iMaxPaths, STPath& extraPath) if (tesSUCCESS == result) { - WriteLog (lsDEBUG, Pathfinder) << "Default path contributes: " << saDstAmountAct; + WriteLog (lsDEBUG, Pathfinder) + << "Default path contributes: " << saDstAmountAct; remaining -= saDstAmountAct; } else { - WriteLog (lsDEBUG, Pathfinder) << "Default path fails: " << transToken (result); + WriteLog (lsDEBUG, Pathfinder) + << "Default path fails: " << transToken (result); } } catch (...) @@ -276,7 +303,8 @@ STPathSet Pathfinder::filterPaths(int iMaxPaths, STPath& extraPath) std::vector vMap; // Ignore paths that move only very small amounts - STAmount saMinDstAmount = STAmount::divide(mDstAmount, STAmount(iMaxPaths + 2), mDstAmount); + auto saMinDstAmount = STAmount::divide( + mDstAmount, STAmount(iMaxPaths + 2), mDstAmount); // Build map of quality to entry. for (int i = mCompletePaths.size (); i--;) @@ -296,24 +324,24 @@ STPathSet Pathfinder::filterPaths(int iMaxPaths, STPath& extraPath) LedgerEntrySet lesSandbox (mLedger, tapNONE); resultCode = path::rippleCalculate ( - lesSandbox, - saMaxAmountAct, // --> computed input - saDstAmountAct, // --> computed output - pathStateList, - mSrcAmount, // --> amount to send max. - mDstAmount, // --> amount to deliver. - mDstAccountID, - mSrcAccountID, - spsPaths, - true, // --> bPartialPayment: Allow, it might contribute. - false, // --> bLimitQuality: Assume normal transaction. - true, // --> bNoRippleDirect: Providing the only path. - true); // --> bStandAlone: Don't need to delete unfundeds. + lesSandbox, + saMaxAmountAct, // --> computed input + saDstAmountAct, // --> computed output + pathStateList, + mSrcAmount, // --> amount to send max. + mDstAmount, // --> amount to deliver. + mDstAccountID, + mSrcAccountID, + spsPaths, + true, // --> bPartialPayment: Allow, it might contribute. + false, // --> bLimitQuality: Assume normal transaction. + true, // --> bNoRippleDirect: Providing the only path. + true); // --> bStandAlone: Don't need to delete unfundeds. } catch (const std::exception& e) { - WriteLog (lsINFO, Pathfinder) << "findPaths: Caught throw: " << e.what (); - + WriteLog (lsINFO, Pathfinder) + << "findPaths: Caught throw: " << e.what (); resultCode = tefEXCEPTION; } @@ -347,22 +375,25 @@ STPathSet Pathfinder::filterPaths(int iMaxPaths, STPath& extraPath) if (vMap.size()) { - std::sort (vMap.begin (), vMap.end (), bQualityCmp); // Lower is better and should be first. + // Lower is better and should be first. + std::sort (vMap.begin (), vMap.end (), bQualityCmp); for (int i = 0, iPathsLeft = iMaxPaths; - ((iPathsLeft > 0) || (extraPath.size() == 0)) && (i < vMap.size ()); ++i) + (iPathsLeft > 0 || extraPath.empty()) && i < vMap.size (); ++i) { path_LQ_t& lqt = vMap[i]; - if ((iPathsLeft > 1) || ((iPathsLeft > 0) && (std::get<2> (lqt) >= remaining))) + if (iPathsLeft > 1 || + (iPathsLeft > 0 && std::get<2> (lqt) >= remaining)) { // last path must fill --iPathsLeft; remaining -= std::get<2> (lqt); spsDst.addPath (mCompletePaths[std::get<3> (lqt)]); } - else if ((iPathsLeft == 0) && (std::get<2>(lqt) >= mDstAmount) && (extraPath.size() == 0)) + else if (iPathsLeft == 0 && std::get<2>(lqt) >= mDstAmount && + extraPath.empty()) { // found an extra path that can move the whole amount extraPath = mCompletePaths[std::get<3>(lqt)]; @@ -395,51 +426,54 @@ STPathSet Pathfinder::filterPaths(int iMaxPaths, STPath& extraPath) return spsDst; } -boost::unordered_set usAccountSourceCurrencies ( +CurrencySet usAccountSourceCurrencies ( const RippleAddress& raAccountID, RippleLineCache::ref lrCache, bool includeXRP) { - boost::unordered_set usCurrencies; + CurrencySet usCurrencies; // YYY Only bother if they are above reserve if (includeXRP) - usCurrencies.insert (uint160 (XRP_CURRENCY)); + usCurrencies.insert (xrpCurrency()); // List of ripple lines. - AccountItems& rippleLines (lrCache->getRippleLines (raAccountID.getAccountID ())); + auto& rippleLines (lrCache->getRippleLines (raAccountID.getAccountID ())); - BOOST_FOREACH (AccountItem::ref item, rippleLines.getItems ()) + for (auto item: rippleLines.getItems ()) { RippleState* rspEntry = (RippleState*) item.get (); const STAmount& saBalance = rspEntry->getBalance (); // Filter out non - if (saBalance > zero // Have IOUs to send. - || (rspEntry->getLimitPeer () // Peer extends credit. - && ((-saBalance) < rspEntry->getLimitPeer ()))) // Credit left. + if (saBalance > zero + // Have IOUs to send. + || (rspEntry->getLimitPeer () + // Peer extends credit. + && ((-saBalance) < rspEntry->getLimitPeer ()))) // Credit left. { usCurrencies.insert (saBalance.getCurrency ()); } } - usCurrencies.erase (CURRENCY_BAD); + usCurrencies.erase (badCurrency()); return usCurrencies; } -boost::unordered_set usAccountDestCurrencies ( +CurrencySet usAccountDestCurrencies ( const RippleAddress& raAccountID, RippleLineCache::ref lrCache, bool includeXRP) { - boost::unordered_set usCurrencies; + CurrencySet usCurrencies; if (includeXRP) - usCurrencies.insert (uint160 (XRP_CURRENCY)); // Even if account doesn't exist + usCurrencies.insert (xrpCurrency()); + // Even if account doesn't exist // List of ripple lines. - AccountItems& rippleLines (lrCache->getRippleLines (raAccountID.getAccountID ())); + auto& rippleLines (lrCache->getRippleLines (raAccountID.getAccountID ())); - BOOST_FOREACH (AccountItem::ref item, rippleLines.getItems ()) + for (auto item: rippleLines.getItems ()) { RippleState* rspEntry = (RippleState*) item.get (); const STAmount& saBalance = rspEntry->getBalance (); @@ -448,11 +482,11 @@ boost::unordered_set usAccountDestCurrencies ( usCurrencies.insert (saBalance.getCurrency ()); } - usCurrencies.erase (CURRENCY_BAD); + usCurrencies.erase (badCurrency()); return usCurrencies; } -bool Pathfinder::matchesOrigin (const uint160& currency, const uint160& issuer) +bool Pathfinder::matchesOrigin (Currency const& currency, Account const& issuer) { if (currency != mSrcCurrencyID) return false; @@ -463,22 +497,22 @@ bool Pathfinder::matchesOrigin (const uint160& currency, const uint160& issuer) return (issuer == mSrcIssuerID) || (issuer == mSrcAccountID); } -// VFALCO TODO Use RippleCurrency, RippleAccount, et. al. in argument list here -int Pathfinder::getPathsOut (RippleCurrency const& currencyID, const uint160& accountID, - bool isDstCurrency, const uint160& dstAccount) +// VFALCO TODO Use Currency, RippleAccount, et. al. in argument list here +int Pathfinder::getPathsOut ( + Currency const& currencyID, Account const& accountID, + bool isDstCurrency, Account const& dstAccount) { // VFALCO TODO Use RippleAsset here - std::pair accountCurrency (currencyID, accountID); - // VFALCO TODO Use RippleAsset here - ripple::unordered_map, int>::iterator it = mPOMap.find (accountCurrency); + auto currencyAccount = std::make_pair(currencyID, accountID); + auto it = mPOMap.find (currencyAccount); if (it != mPOMap.end ()) return it->second; - SLE::pointer sleAccount = mLedger->getSLEi(Ledger::getAccountRootIndex(accountID)); + auto sleAccount = mLedger->getSLEi(Ledger::getAccountRootIndex(accountID)); if (!sleAccount) { - mPOMap[accountCurrency] = 0; + mPOMap[currencyAccount] = 0; return 0; } @@ -510,7 +544,7 @@ int Pathfinder::getPathsOut (RippleCurrency const& currencyID, const uint160& ac else ++count; } - mPOMap[accountCurrency] = count; + mPOMap[currencyAccount] = count; return count; } @@ -593,7 +627,8 @@ STPathSet& Pathfinder::getPaths(PathType_t const& type, bool addComplete) return pathsOut; } -bool Pathfinder::isNoRipple (const uint160& setByID, const uint160& setOnID, const uint160& currencyID) +bool Pathfinder::isNoRipple ( + Account const& setByID, Account const& setOnID, Currency const& currencyID) { SLE::pointer sleRipple = mLedger->getSLEi ( Ledger::getRippleStateIndex (setByID, setOnID, currencyID)); @@ -617,7 +652,7 @@ bool Pathfinder::isNoRippleOut (const STPath& currentPath) return false; // What account are we leaving? - uint160 const& fromAccount = + auto const& fromAccount = (currentPath.size() == 1) ? mSrcAccountID : (currentPath.end() - 2)->mAccountID; return isNoRipple (endElement.mAccountID, fromAccount, endElement.mCurrencyID); @@ -629,9 +664,9 @@ void Pathfinder::addLink( int addFlags) { STPathElement const& pathEnd = currentPath.isEmpty() ? mSource : currentPath.mPath.back (); - uint160 const& uEndCurrency = pathEnd.mCurrencyID; - uint160 const& uEndIssuer = pathEnd.mIssuerID; - uint160 const& uEndAccount = pathEnd.mAccountID; + auto const& uEndCurrency = pathEnd.mCurrencyID; + auto const& uEndIssuer = pathEnd.mIssuerID; + auto const& uEndAccount = pathEnd.mAccountID; bool const bOnXRP = uEndCurrency.isZero(); WriteLog (lsTRACE, Pathfinder) << "addLink< flags=" << addFlags << " onXRP=" << bOnXRP; @@ -649,34 +684,44 @@ void Pathfinder::addLink( } else { // search for accounts to add - SLE::pointer sleEnd = mLedger->getSLEi(Ledger::getAccountRootIndex(uEndAccount)); + auto sleEnd = mLedger->getSLEi( + Ledger::getAccountRootIndex(uEndAccount)); if (sleEnd) { - bool const bRequireAuth (sleEnd->getFieldU32(sfFlags) & lsfRequireAuth); - bool const bIsEndCurrency (uEndCurrency == mDstAmount.getCurrency()); - bool const bIsNoRippleOut (isNoRippleOut (currentPath)); + bool const bRequireAuth ( + sleEnd->getFieldU32(sfFlags) & lsfRequireAuth); + bool const bIsEndCurrency ( + uEndCurrency == mDstAmount.getCurrency()); + bool const bIsNoRippleOut ( + isNoRippleOut (currentPath)); - AccountItems& rippleLines (mRLCache->getRippleLines(uEndAccount)); + auto& rippleLines (mRLCache->getRippleLines(uEndAccount)); - std::vector< std::pair > candidates; + AccountCandidates candidates; candidates.reserve(rippleLines.getItems().size()); - for(auto item : rippleLines.getItems()) + for(auto const& item : rippleLines.getItems()) { - RippleState const& rspEntry = * reinterpret_cast(item.get()); - uint160 const& acctID = rspEntry.getAccountIDPeer(); + auto* rs = dynamic_cast (item.get()); + if (!rs) + { + WriteLog (lsERROR, Pathfinder) + << "Couldn't decipher RippleState"; + continue; + } + auto const& acctID = rs->getAccountIDPeer(); - if ((uEndCurrency == rspEntry.getLimit().getCurrency()) && + if ((uEndCurrency == rs->getLimit().getCurrency()) && !currentPath.hasSeen(acctID, uEndCurrency, acctID)) { // path is for correct currency and has not been seen - if (rspEntry.getBalance() <= zero - && (!rspEntry.getLimitPeer() - || -rspEntry.getBalance() >= rspEntry.getLimitPeer() - || (bRequireAuth && !rspEntry.getAuth()))) + if (rs->getBalance() <= zero + && (!rs->getLimitPeer() + || -rs->getBalance() >= rs->getLimitPeer() + || (bRequireAuth && !rs->getAuth()))) { // path has no credit } - else if (bIsNoRippleOut && rspEntry.getNoRipple()) + else if (bIsNoRippleOut && rs->getNoRipple()) { // Can't leave on this path } @@ -686,7 +731,9 @@ void Pathfinder::addLink( { // this is a complete path if (!currentPath.isEmpty()) { - WriteLog (lsTRACE, Pathfinder) << "complete path found ae: " << currentPath.getJson(0); + WriteLog (lsTRACE, Pathfinder) + << "complete path found ae: " + << currentPath.getJson(0); mCompletePaths.addUniquePath(currentPath); } } @@ -721,7 +768,7 @@ void Pathfinder::addLink( else if (count > 50) count = 50; - std::vector< std::pair >::const_iterator it = candidates.begin(); + auto it = candidates.begin(); while (count-- != 0) { // Add accounts to incompletePaths incompletePaths.assembleAdd(currentPath, STPathElement(STPathElement::typeAccount, it->second, uEndCurrency, it->second)); @@ -744,7 +791,7 @@ void Pathfinder::addLink( { STPathElement pathElement( STPathElement::typeCurrency, - XRP_ACCOUNT, XRP_CURRENCY, XRP_ACCOUNT); + xrpIssuer(), xrpCurrency(), xrpIssuer()); incompletePaths.assembleAdd(currentPath, pathElement); } } @@ -757,7 +804,7 @@ void Pathfinder::addLink( BOOST_FOREACH(OrderBook::ref book, books) { if (!currentPath.hasSeen ( - XRP_ACCOUNT, + xrpIssuer(), book->getCurrencyOut(), book->getIssuerOut()) && !matchesOrigin( @@ -774,7 +821,7 @@ void Pathfinder::addLink( // add the order book itself newPath.addElement(STPathElement( STPathElement::typeCurrency, - XRP_ACCOUNT, XRP_CURRENCY, XRP_ACCOUNT)); + xrpIssuer(), xrpCurrency(), xrpIssuer())); if (mDstAmount.getCurrency().isZero()) { // destination is XRP, add account and path is complete @@ -788,7 +835,7 @@ void Pathfinder::addLink( { // Don't want the book if we've already seen the issuer // add the order book itself newPath.addElement(STPathElement(STPathElement::typeCurrency | STPathElement::typeIssuer, - XRP_ACCOUNT, book->getCurrencyOut(), book->getIssuerOut())); + xrpIssuer(), book->getCurrencyOut(), book->getIssuerOut())); if ((book->getIssuerOut() == mDstAccountID) && book->getCurrencyOut() == mDstAmount.getCurrency()) { // with the destination account, this path is complete diff --git a/src/ripple/module/app/paths/Pathfinder.h b/src/ripple/module/app/paths/Pathfinder.h index ff0ca2c028..31b4b8fa6d 100644 --- a/src/ripple/module/app/paths/Pathfinder.h +++ b/src/ripple/module/app/paths/Pathfinder.h @@ -38,13 +38,14 @@ public: STPath mPath; bool mCorrectCurrency; // for the sorting - uint160 mCurrencyID; // what currency we currently have at the end of the path - uint160 mCurrentAccount; // what account is at the end of the path + Currency mCurrencyID; // what currency we currently have at the end of the path + Account mCurrentAccount; // what account is at the end of the path int mTotalCost; // in send currency STAmount mMinWidth; // in dest currency float mQuality; - PathOption (uint160& srcAccount, uint160& srcCurrencyID, const uint160& dstCurrencyID); + PathOption (Account& srcAccount, Currency& srcCurrencyID, + Currency const& dstCurrencyID); PathOption (PathOption::pointer other); }; #endif @@ -58,12 +59,18 @@ public: class Pathfinder { public: - Pathfinder (RippleLineCache::ref cache, - const RippleAddress& srcAccountID, const RippleAddress& dstAccountID, - const uint160& srcCurrencyID, const uint160& srcIssuerID, const STAmount& dstAmount, bool& bValid); + Pathfinder ( + RippleLineCache::ref cache, + const RippleAddress& srcAccountID, + const RippleAddress& dstAccountID, + Currency const& srcCurrencyID, + Account const& srcIssuerID, + const STAmount& dstAmount, bool& bValid); static void initPathTable(); - bool findPaths (int iLevel, const unsigned int iMaxPaths, STPathSet& spsDst, STPath& spExtraPath); + bool findPaths ( + int iLevel, const unsigned int iMaxPaths, + STPathSet& spsDst, STPath& spExtraPath); private: @@ -95,29 +102,34 @@ private: static std::string pathTypeToString(PathType_t const&); - bool matchesOrigin (const uint160& currency, const uint160& issuer); + bool matchesOrigin (Currency const& currency, Account const& issuer); - int getPathsOut (const uint160& currency, const uint160& accountID, - bool isDestCurrency, const uint160& dest); + int getPathsOut (Currency const& currency, Account const& accountID, + bool isDestCurrency, Account const& dest); + + void addLink( + const STPath& currentPath, STPathSet& incompletePaths, int addFlags); + void addLink( + const STPathSet& currentPaths, STPathSet& incompletePaths, int addFlags); - void addLink(const STPath& currentPath, STPathSet& incompletePaths, int addFlags); - void addLink(const STPathSet& currentPaths, STPathSet& incompletePaths, int addFlags); STPathSet& getPaths(const PathType_t& type, bool addComplete = true); STPathSet filterPaths(int iMaxPaths, STPath& extraPath); bool isNoRippleOut (const STPath& currentPath); - bool isNoRipple (uint160 const& setByID, uint160 const& setOnID, uint160 const& currencyID); + bool isNoRipple ( + Account const& setByID, Account const& setOnID, + Currency const& currencyID); // Our main table of paths static std::map mPathTable; static PathType_t makePath(char const*); - uint160 mSrcAccountID; - uint160 mDstAccountID; + Account mSrcAccountID; + Account mDstAccountID; STAmount mDstAmount; - uint160 mSrcCurrencyID; - uint160 mSrcIssuerID; + Currency mSrcCurrencyID; + Account mSrcIssuerID; STAmount mSrcAmount; Ledger::pointer mLedger; @@ -128,22 +140,30 @@ private: STPathSet mCompletePaths; std::map< PathType_t, STPathSet > mPaths; - ripple::unordered_map mRLMap; - ripple::unordered_map, int> mPOMap; + ripple::unordered_map, int> mPOMap; - static const std::uint32_t afADD_ACCOUNTS = 0x001; // Add ripple paths - static const std::uint32_t afADD_BOOKS = 0x002; // Add order books - static const std::uint32_t afOB_XRP = 0x010; // Add order book to XRP only - static const std::uint32_t afOB_LAST = 0x040; // Must link to destination currency - static const std::uint32_t afAC_LAST = 0x080; // Destination account only + // Add ripple paths + static const std::uint32_t afADD_ACCOUNTS = 0x001; + + // Add order books + static const std::uint32_t afADD_BOOKS = 0x002; + + // Add order book to XRP only + static const std::uint32_t afOB_XRP = 0x010; + + // Must link to destination currency + static const std::uint32_t afOB_LAST = 0x040; + + // Destination account only + static const std::uint32_t afAC_LAST = 0x080; }; -boost::unordered_set usAccountDestCurrencies +CurrencySet usAccountDestCurrencies (const RippleAddress& raAccountID, RippleLineCache::ref cache, bool includeXRP); -boost::unordered_set usAccountSourceCurrencies +CurrencySet usAccountSourceCurrencies (const RippleAddress& raAccountID, RippleLineCache::ref lrLedger, bool includeXRP); diff --git a/src/ripple/module/app/paths/RippleCalc.cpp b/src/ripple/module/app/paths/RippleCalc.cpp index ecd6d56761..bfe7421b24 100644 --- a/src/ripple/module/app/paths/RippleCalc.cpp +++ b/src/ripple/module/app/paths/RippleCalc.cpp @@ -29,7 +29,6 @@ #include #include #include -#include namespace ripple { @@ -56,19 +55,19 @@ TER rippleCalculate ( PathState::List& pathStateList, // Issuer: - // XRP: XRP_ACCOUNT + // XRP: xrpIssuer() // non-XRP: uSrcAccountID (for any issuer) or another account with trust // node. const STAmount& saMaxAmountReq, // --> -1 = no limit. // Issuer: - // XRP: XRP_ACCOUNT + // XRP: xrpIssuer() // non-XRP: uDstAccountID (for any issuer) or another account with trust // node. const STAmount& saDstAmountReq, - const uint160& uDstAccountID, - const uint160& uSrcAccountID, + Account const& uDstAccountID, + Account const& uSrcAccountID, // A set of paths that are included in the transaction that we'll explore // for liquidity. @@ -162,9 +161,9 @@ TER rippleCalculate ( << " saDstAmountReq:" << saDstAmountReq << " saMaxAmountReq:" << saMaxAmountReq << " uDstAccountID:" - << RippleAddress::createHumanAccountID (uDstAccountID) + << to_string (uDstAccountID) << " uSrcAccountID:" - << RippleAddress::createHumanAccountID (uSrcAccountID); + << to_string (uSrcAccountID); pspExpanded->expandPath ( activeLedger, spPath, uDstAccountID, uSrcAccountID); diff --git a/src/ripple/module/app/paths/RippleCalc.h b/src/ripple/module/app/paths/RippleCalc.h index c03849747e..085e0d181e 100644 --- a/src/ripple/module/app/paths/RippleCalc.h +++ b/src/ripple/module/app/paths/RippleCalc.h @@ -36,8 +36,8 @@ TER rippleCalculate ( PathState::List& pathStateList, const STAmount& saDstAmountReq, const STAmount& saMaxAmountReq, - const uint160& uDstAccountID, - const uint160& uSrcAccountID, + Account const& uDstAccountID, + Account const& uSrcAccountID, const STPathSet& spsPaths, const bool bPartialPayment, const bool bLimitQuality, diff --git a/src/ripple/module/app/paths/RippleLineCache.cpp b/src/ripple/module/app/paths/RippleLineCache.cpp index a131f9bd4b..526c92ddde 100644 --- a/src/ripple/module/app/paths/RippleLineCache.cpp +++ b/src/ripple/module/app/paths/RippleLineCache.cpp @@ -24,16 +24,18 @@ RippleLineCache::RippleLineCache (Ledger::ref l) { } -AccountItems& RippleLineCache::getRippleLines (const uint160& accountID) +AccountItems& RippleLineCache::getRippleLines (Account const& accountID) { ScopedLockType sl (mLock); - ripple::unordered_map ::iterator it = mRLMap.find (accountID); + auto it = mRLMap.find (accountID); if (it == mRLMap.end ()) + { it = mRLMap.insert (std::make_pair (accountID, std::make_shared - (std::cref (accountID), std::cref (mLedger), AccountItem::pointer (new RippleState ())))).first; - + (accountID, mLedger, + AccountItem::pointer (new RippleState ())))).first; + } return *it->second; } diff --git a/src/ripple/module/app/paths/RippleLineCache.h b/src/ripple/module/app/paths/RippleLineCache.h index c255da8edb..58adf9d82e 100644 --- a/src/ripple/module/app/paths/RippleLineCache.h +++ b/src/ripple/module/app/paths/RippleLineCache.h @@ -36,16 +36,16 @@ public: return mLedger; } - AccountItems& getRippleLines (const uint160& accountID); + AccountItems& getRippleLines (Account const& accountID); private: typedef RippleMutex LockType; typedef std::lock_guard ScopedLockType; LockType mLock; - + Ledger::pointer mLedger; - - ripple::unordered_map mRLMap; + + ripple::unordered_map mRLMap; }; } // ripple diff --git a/src/ripple/module/app/paths/RippleState.cpp b/src/ripple/module/app/paths/RippleState.cpp index c87c48adf5..a32ccabc4e 100644 --- a/src/ripple/module/app/paths/RippleState.cpp +++ b/src/ripple/module/app/paths/RippleState.cpp @@ -19,7 +19,8 @@ namespace ripple { -AccountItem::pointer RippleState::makeItem (const uint160& accountID, SerializedLedgerEntry::ref ledgerEntry) +AccountItem::pointer RippleState::makeItem ( + Account const& accountID, SerializedLedgerEntry::ref ledgerEntry) { if (!ledgerEntry || ledgerEntry->getType () != ltRIPPLE_STATE) return AccountItem::pointer (); @@ -30,7 +31,8 @@ AccountItem::pointer RippleState::makeItem (const uint160& accountID, Serialized return AccountItem::pointer (rs); } -RippleState::RippleState (SerializedLedgerEntry::ref ledgerEntry) : AccountItem (ledgerEntry), +RippleState::RippleState (SerializedLedgerEntry::ref ledgerEntry) + : AccountItem (ledgerEntry), mValid (false), mViewLowest (true), @@ -53,7 +55,7 @@ RippleState::RippleState (SerializedLedgerEntry::ref ledgerEntry) : AccountItem mValid = true; } -void RippleState::setViewAccount (const uint160& accountID) +void RippleState::setViewAccount (Account const& accountID) { bool bViewLowestNew = mLowID == accountID; diff --git a/src/ripple/module/app/paths/RippleState.h b/src/ripple/module/app/paths/RippleState.h index d5e1462456..194b507783 100644 --- a/src/ripple/module/app/paths/RippleState.h +++ b/src/ripple/module/app/paths/RippleState.h @@ -37,21 +37,22 @@ public: virtual ~RippleState () { } - AccountItem::pointer makeItem (const uint160& accountID, SerializedLedgerEntry::ref ledgerEntry); + AccountItem::pointer makeItem ( + Account const& accountID, SerializedLedgerEntry::ref ledgerEntry); LedgerEntryType getType () { return ltRIPPLE_STATE; } - void setViewAccount (const uint160& accountID); + void setViewAccount (Account const& accountID); - const uint160& getAccountID () const + Account const& getAccountID () const { return mViewLowest ? mLowID : mHighID; } - - const uint160& getAccountIDPeer () const + + Account const& getAccountIDPeer () const { return !mViewLowest ? mLowID : mHighID; } @@ -97,7 +98,7 @@ public: return ((std::uint32_t) (mViewLowest ? mLowQualityIn : mHighQualityIn)); return ((std::uint32_t) (mViewLowest ? mLowQualityIn : mHighQualityIn)); } - + std::uint32_t getQualityOut () const { return ((std::uint32_t) (mViewLowest ? mLowQualityOut : mHighQualityOut)); @@ -107,17 +108,17 @@ public: { return mLedgerEntry; } - + const SerializedLedgerEntry& peekSLE () const { return *mLedgerEntry; } - + SerializedLedgerEntry& peekSLE () { return *mLedgerEntry; } - + Json::Value getJson (int); Blob getRaw () const; @@ -134,8 +135,8 @@ private: STAmount mLowLimit; STAmount mHighLimit; - uint160 mLowID; - uint160 mHighID; + Account mLowID; + Account mHighID; std::uint64_t mLowQualityIn; std::uint64_t mLowQualityOut; diff --git a/src/ripple/module/app/paths/Types.cpp b/src/ripple/module/app/paths/Types.cpp deleted file mode 100644 index f217b70a69..0000000000 --- a/src/ripple/module/app/paths/Types.cpp +++ /dev/null @@ -1,27 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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 - -namespace ripple { - -const path::Account XRP_ACCOUNT(0); -const path::Currency XRP_CURRENCY(0); - -} // ripple diff --git a/src/ripple/module/app/paths/Types.h b/src/ripple/module/app/paths/Types.h index 7b6d90b5f3..2de6e7130a 100644 --- a/src/ripple/module/app/paths/Types.h +++ b/src/ripple/module/app/paths/Types.h @@ -23,22 +23,12 @@ namespace ripple { // account id, currency id, issuer id. -typedef std::tuple AccountCurrencyIssuer; +typedef std::tuple AccountCurrencyIssuer; // Map of account, currency, issuer to node index. typedef ripple::unordered_map AccountCurrencyIssuerToNodeIndex; -namespace path { - -typedef core::Account Account; -typedef core::Currency Currency; - -} // path - -extern const path::Account XRP_ACCOUNT; -extern const path::Currency XRP_CURRENCY; - } // ripple #endif diff --git a/src/ripple/module/app/transactors/AddWallet.cpp b/src/ripple/module/app/transactors/AddWallet.cpp index 1bc378b316..98d6761b68 100644 --- a/src/ripple/module/app/transactors/AddWallet.cpp +++ b/src/ripple/module/app/transactors/AddWallet.cpp @@ -34,14 +34,15 @@ TER AddWallet::doApply () Blob const vucPubKey = mTxn.getFieldVL (sfPublicKey); Blob const vucSignature = mTxn.getFieldVL (sfSignature); - uint160 const uAuthKeyID (mTxn.getFieldAccount160 (sfRegularKey)); - RippleAddress const naMasterPubKey ( - RippleAddress::createAccountPublic (vucPubKey)); - uint160 const uDstAccountID (naMasterPubKey.getAccountID ()); + auto const uAuthKeyID = mTxn.getFieldAccount160 (sfRegularKey); + auto const naMasterPubKey = + RippleAddress::createAccountPublic (vucPubKey); + auto const uDstAccountID = naMasterPubKey.getAccountID (); - // FIXME: This should be moved to the transaction's signature check logic and cached + // FIXME: This should be moved to the transaction's signature check logic + // and cached. if (!naMasterPubKey.accountPublicVerify ( - Serializer::getSHA512Half (uAuthKeyID.begin (), uAuthKeyID.size ()), + Serializer::getSHA512Half (uAuthKeyID.begin (), uAuthKeyID.size ()), vucSignature, ECDSA::not_strict)) { m_journal.trace << @@ -66,7 +67,7 @@ TER AddWallet::doApply () STAmount const saSrcBalance = mTxnAccount->getFieldAmount (sfBalance); std::uint32_t const uOwnerCount = mTxnAccount->getFieldU32 (sfOwnerCount); std::uint64_t const uReserve = mEngine->getLedger ()->getReserve (uOwnerCount); - + // Make sure have enough reserve to send. Allow final spend to use reserve // for fee. diff --git a/src/ripple/module/app/transactors/CancelOffer.cpp b/src/ripple/module/app/transactors/CancelOffer.cpp index 8111109a68..7e9670b1ef 100644 --- a/src/ripple/module/app/transactors/CancelOffer.cpp +++ b/src/ripple/module/app/transactors/CancelOffer.cpp @@ -62,7 +62,7 @@ TER CancelOffer::doApply () m_journal.warning << "OfferCancel: offer not found: " << - RippleAddress::createHumanAccountID (mTxnAccountID) << + to_string (mTxnAccountID) << " : " << uOfferSequence << " : " << to_string (offerIndex); diff --git a/src/ripple/module/app/transactors/CreateOffer.cpp b/src/ripple/module/app/transactors/CreateOffer.cpp index 335dd01c8b..80bd2d2fd3 100644 --- a/src/ripple/module/app/transactors/CreateOffer.cpp +++ b/src/ripple/module/app/transactors/CreateOffer.cpp @@ -56,7 +56,7 @@ CreateOffer::checkAcceptAsset(core::AssetRef asset) const { if (m_journal.warning) m_journal.warning << "delay: can't receive IOUs from non-existent issuer: " << - RippleAddress::createHumanAccountID (asset.issuer); + to_string (asset.issuer); return (mParams & tapRETRY) ? terNO_ACCOUNT @@ -117,11 +117,11 @@ CreateOffer::doApply () if (!saTakerPays.isLegalNet () || !saTakerGets.isLegalNet ()) return temBAD_AMOUNT; - uint160 const& uPaysIssuerID = saTakerPays.getIssuer (); - uint160 const& uPaysCurrency = saTakerPays.getCurrency (); + auto const& uPaysIssuerID = saTakerPays.getIssuer (); + auto const& uPaysCurrency = saTakerPays.getCurrency (); - uint160 const& uGetsIssuerID = saTakerGets.getIssuer (); - uint160 const& uGetsCurrency = saTakerGets.getCurrency (); + auto const& uGetsIssuerID = saTakerGets.getIssuer (); + auto const& uGetsCurrency = saTakerGets.getCurrency (); bool const bHaveExpiration (mTxn.isFieldPresent (sfExpiration)); bool const bHaveCancel (mTxn.isFieldPresent (sfOfferSequence)); @@ -216,7 +216,7 @@ CreateOffer::doApply () terResult = temREDUNDANT; } // We don't allow a non-native currency to use the currency code XRP. - else if (CURRENCY_BAD == uPaysCurrency || CURRENCY_BAD == uGetsCurrency) + else if (badCurrency() == uPaysCurrency || badCurrency() == uGetsCurrency) { m_journal.warning << "Malformed offer: Bad currency."; @@ -295,7 +295,7 @@ CreateOffer::doApply () { // We reverse gets and pays because during offer crossing we are taking. core::Amounts const taker_amount (saTakerGets, saTakerPays); - + // The amount of the offer that we will need to place, after we finish // offer crossing processing. It may be equal to the original amount, // empty (fully crossed), or something in-between. @@ -324,10 +324,10 @@ CreateOffer::doApply () if (terResult == tesSUCCESS) { - m_journal.debug << + m_journal.debug << " takerPays: " << saTakerPays.getFullText () << " -> " << place_offer.out.getFullText (); - m_journal.debug << + m_journal.debug << " takerGets: " << saTakerGets.getFullText () << " -> " << place_offer.in.getFullText (); } @@ -354,7 +354,7 @@ CreateOffer::doApply () "takeOffers: saTakerGets=" << saTakerGets.getFullText (); m_journal.debug << "takeOffers: mTxnAccountID=" << - RippleAddress::createHumanAccountID (mTxnAccountID); + to_string (mTxnAccountID); m_journal.debug << "takeOffers: FUNDS=" << view.accountFunds (mTxnAccountID, saTakerGets).getFullText (); @@ -432,9 +432,9 @@ CreateOffer::doApply () if (m_journal.debug) m_journal.debug << "adding to book: " << to_string (uBookBase) << " : " << saTakerPays.getHumanCurrency () << - "/" << RippleAddress::createHumanAccountID (saTakerPays.getIssuer ()) << + "/" << to_string (saTakerPays.getIssuer ()) << " -> " << saTakerGets.getHumanCurrency () << - "/" << RippleAddress::createHumanAccountID (saTakerGets.getIssuer ()); + "/" << to_string (saTakerGets.getIssuer ()); // We use the original rate to place the offer. uDirectory = Ledger::getQualityIndex (uBookBase, uRate); @@ -453,13 +453,13 @@ CreateOffer::doApply () { m_journal.debug << "sfAccount=" << - RippleAddress::createHumanAccountID (mTxnAccountID); + to_string (mTxnAccountID); m_journal.debug << "uPaysIssuerID=" << - RippleAddress::createHumanAccountID (uPaysIssuerID); + to_string (uPaysIssuerID); m_journal.debug << "uGetsIssuerID=" << - RippleAddress::createHumanAccountID (uGetsIssuerID); + to_string (uGetsIssuerID); m_journal.debug << "saTakerPays.isNative()=" << saTakerPays.isNative (); @@ -518,11 +518,11 @@ std::unique_ptr make_CreateOffer ( #else STAmount const& amount_in = txn.getFieldAmount (sfTakerPays); STAmount const& amount_out = txn.getFieldAmount (sfTakerGets); - + // Autobridging is only in effect when an offer does not involve XRP if (!amount_in.isNative() && !amount_out.isNative ()) return std::make_unique (txn, params, engine); - + return std::make_unique (txn, params, engine); #endif } diff --git a/src/ripple/module/app/transactors/CreateOfferBridged.cpp b/src/ripple/module/app/transactors/CreateOfferBridged.cpp index b163d635be..0b227a3249 100644 --- a/src/ripple/module/app/transactors/CreateOfferBridged.cpp +++ b/src/ripple/module/app/transactors/CreateOfferBridged.cpp @@ -52,7 +52,7 @@ CreateOfferBridged::crossOffers ( core::OfferStream offers_leg1 (view, view_cancel, core::Book (asset_in, xrp_asset ()), when, m_journal); - + core::OfferStream offers_leg2 (view, view_cancel, core::Book (xrp_asset (), asset_out), when, m_journal); @@ -86,7 +86,7 @@ CreateOfferBridged::crossOffers ( // Logic: // We calculate the qualities of any direct and bridged offers at the // tip of the order book, and choose the best one of the two. - + if (have_direct) { core::Quality const direct_quality (offers_direct.tip ().quality ()); @@ -188,4 +188,3 @@ CreateOfferBridged::crossOffers ( } } - diff --git a/src/ripple/module/app/transactors/CreateOfferDirect.cpp b/src/ripple/module/app/transactors/CreateOfferDirect.cpp index 84a9718e8a..b22192cf4c 100644 --- a/src/ripple/module/app/transactors/CreateOfferDirect.cpp +++ b/src/ripple/module/app/transactors/CreateOfferDirect.cpp @@ -45,14 +45,16 @@ CreateOfferDirect::crossOffers ( mEngine->getLedger ()->getParentCloseTimeNC ()); core::LedgerView view_cancel (view.duplicate()); - core::OfferStream offers (view, view_cancel, + core::OfferStream offers (view, view_cancel, core::Book ( core::AssetRef ( - taker_amount.in.getCurrency(), taker_amount.in.getIssuer()), + taker_amount.in.getCurrency(), taker_amount.in.getIssuer()), core::AssetRef ( - taker_amount.out.getCurrency(), taker_amount.out.getIssuer())), + taker_amount.out.getCurrency(), taker_amount.out.getIssuer())), when, m_journal); - core::Taker taker (offers.view(), mTxnAccountID, taker_amount, options); + Account& account = mTxnAccountID; + // TODO(tom): why is that last line needed? + core::Taker taker (offers.view(), account, taker_amount, options); TER cross_result (tesSUCCESS); diff --git a/src/ripple/module/app/transactors/CreateOfferLegacy.cpp b/src/ripple/module/app/transactors/CreateOfferLegacy.cpp index 9e9379ebcd..9bd72689a3 100644 --- a/src/ripple/module/app/transactors/CreateOfferLegacy.cpp +++ b/src/ripple/module/app/transactors/CreateOfferLegacy.cpp @@ -24,12 +24,12 @@ namespace ripple { */ bool CreateOfferLegacy::isValidOffer ( SLE::ref sleOffer, - uint160 const& uOfferOwnerID, + Account const& uOfferOwnerID, STAmount const& saOfferPays, STAmount const& saOfferGets, - uint160 const& uTakerAccountID, - std::unordered_set>& usOfferUnfundedBecame, - std::unordered_set>& usAccountTouched, + Account const& uTakerAccountID, + HardenedOfferSet& usOfferUnfundedBecame, + HardenedAccountSet& usAccountTouched, STAmount& saOfferFunds) { if (sleOffer->isFieldPresent (sfExpiration) && @@ -208,7 +208,7 @@ bool CreateOfferLegacy::applyOffer ( // Limit offerer funds available, by transfer fees. STAmount saOfferFundsAvailable = QUALITY_ONE == uOfferPaysRate ? saOfferFunds // As is. - : STAmount::divide (saOfferFunds, STAmount (CURRENCY_ONE, ACCOUNT_ONE, uOfferPaysRate, -9)); // Reduce by offer fees. + : STAmount::divide (saOfferFunds, STAmount (noCurrency(), noAccount(), uOfferPaysRate, -9)); // Reduce by offer fees. m_journal.info << "applyOffer: uOfferPaysRate=" << uOfferPaysRate; m_journal.info << "applyOffer: saOfferFundsAvailable=" << saOfferFundsAvailable.getFullText (); @@ -216,9 +216,9 @@ bool CreateOfferLegacy::applyOffer ( // Limit taker funds available, by transfer fees. STAmount saTakerFundsAvailable = QUALITY_ONE == uTakerPaysRate ? saTakerFunds // As is. - : STAmount::divide (saTakerFunds, STAmount (CURRENCY_ONE, ACCOUNT_ONE, uTakerPaysRate, -9)); // Reduce by taker fees. + : STAmount::divide (saTakerFunds, STAmount (noCurrency(), noAccount(), uTakerPaysRate, -9)); // Reduce by taker fees. - m_journal.info << "applyOffer: TAKER_FEES=" << STAmount (CURRENCY_ONE, ACCOUNT_ONE, uTakerPaysRate, -9).getFullText (); + m_journal.info << "applyOffer: TAKER_FEES=" << STAmount (noCurrency(), noAccount(), uTakerPaysRate, -9).getFullText (); m_journal.info << "applyOffer: uTakerPaysRate=" << uTakerPaysRate; m_journal.info << "applyOffer: saTakerFundsAvailable=" << saTakerFundsAvailable.getFullText (); @@ -280,7 +280,7 @@ bool CreateOfferLegacy::applyOffer ( { // Compute fees in a rounding safe way. - STAmount transferRate (CURRENCY_ONE, ACCOUNT_ONE, uTakerPaysRate, -9); + STAmount transferRate (noCurrency(), noAccount(), uTakerPaysRate, -9); m_journal.info << "applyOffer: transferRate=" << transferRate.getFullText (); @@ -310,7 +310,7 @@ bool CreateOfferLegacy::applyOffer ( { // Compute fees in a rounding safe way. STAmount saOfferCost = STAmount::mulRound ( - saTakerGot, STAmount (CURRENCY_ONE, ACCOUNT_ONE, uOfferPaysRate, -9), + saTakerGot, STAmount (noCurrency(), noAccount(), uOfferPaysRate, -9), true); saOfferIssuerFee = saOfferCost > saOfferFunds @@ -343,7 +343,7 @@ TER CreateOfferLegacy::takeOffers ( const bool bPassive, const bool bSell, uint256 const& uBookBase, - const uint160& uTakerAccountID, + Account const& uTakerAccountID, SLE::ref sleTakerAccount, const STAmount& saTakerPays, const STAmount& saTakerGets, @@ -367,15 +367,15 @@ TER CreateOfferLegacy::takeOffers ( LedgerEntrySet& lesActive = mEngine->view (); std::uint64_t const uTakeQuality = STAmount::getRate (saTakerGets, saTakerPays); STAmount saTakerRate = STAmount::setRate (uTakeQuality); - uint160 const uTakerPaysAccountID = saTakerPays.getIssuer (); - uint160 const uTakerGetsAccountID = saTakerGets.getIssuer (); + auto const uTakerPaysAccountID = saTakerPays.getIssuer (); + auto const uTakerGetsAccountID = saTakerGets.getIssuer (); TER terResult = temUNCERTAIN; // Offers that became unfunded. - std::unordered_set> usOfferUnfundedBecame; + HardenedOfferSet usOfferUnfundedBecame; // Accounts touched. - std::unordered_set> usAccountTouched; + HardenedAccountSet usAccountTouched; saTakerPaid = STAmount ( saTakerPays.getCurrency (), saTakerPays.getIssuer ()); @@ -430,7 +430,7 @@ TER CreateOfferLegacy::takeOffers ( "takeOffers: considering offer : " << sleOffer->getJson (0); - uint160 const& uOfferOwnerID = sleOffer->getFieldAccount160 (sfAccount); + auto const& uOfferOwnerID = sleOffer->getFieldAccount160 (sfAccount); STAmount saOfferPays = sleOffer->getFieldAmount (sfTakerGets); STAmount saOfferGets = sleOffer->getFieldAmount (sfTakerPays); @@ -704,8 +704,8 @@ TER CreateOfferLegacy::doApply () "saTakerPays=" << saTakerPays.getFullText () << " saTakerGets=" << saTakerGets.getFullText (); - uint160 const uPaysIssuerID = saTakerPays.getIssuer (); - uint160 const uGetsIssuerID = saTakerGets.getIssuer (); + auto const uPaysIssuerID = saTakerPays.getIssuer (); + auto const uGetsIssuerID = saTakerGets.getIssuer (); bool const bHaveExpiration (mTxn.isFieldPresent (sfExpiration)); bool const bHaveCancel (mTxn.isFieldPresent (sfOfferSequence)); @@ -726,8 +726,8 @@ TER CreateOfferLegacy::doApply () "Creating offer node: " << to_string (uLedgerIndex) << " uSequence=" << uSequence; - const uint160 uPaysCurrency = saTakerPays.getCurrency (); - const uint160 uGetsCurrency = saTakerGets.getCurrency (); + auto const uPaysCurrency = saTakerPays.getCurrency (); + auto const uGetsCurrency = saTakerGets.getCurrency (); const std::uint64_t uRate = STAmount::getRate (saTakerGets, saTakerPays); TER terResult = tesSUCCESS; @@ -785,7 +785,7 @@ TER CreateOfferLegacy::doApply () terResult = temREDUNDANT; } // FIXME: XRP is not a bad currency, not not allowed as IOU - else if (CURRENCY_BAD == uPaysCurrency || CURRENCY_BAD == uGetsCurrency) + else if (badCurrency() == uPaysCurrency || badCurrency() == uGetsCurrency) { m_journal.warning << "Malformed offer: Bad currency."; @@ -838,7 +838,7 @@ TER CreateOfferLegacy::doApply () if (m_journal.warning) m_journal.warning << "offer not found: " << - RippleAddress::createHumanAccountID (mTxnAccountID) << + to_string (mTxnAccountID) << " : " << uCancelSequence << " : " << to_string (uCancelIndex); } @@ -863,7 +863,7 @@ TER CreateOfferLegacy::doApply () { m_journal.warning << "delay: can't receive IOUs from non-existent issuer: " << - RippleAddress::createHumanAccountID (uPaysIssuerID); + to_string (uPaysIssuerID); terResult = (mParams & tapRETRY) ? terNO_ACCOUNT : tecNO_ISSUER; } @@ -962,7 +962,7 @@ TER CreateOfferLegacy::doApply () "takeOffers: saTakerGets=" << saTakerGets.getFullText (); m_journal.debug << "takeOffers: mTxnAccountID=" << - RippleAddress::createHumanAccountID (mTxnAccountID); + to_string (mTxnAccountID); m_journal.debug << "takeOffers: FUNDS=" << lesActive.accountFunds (mTxnAccountID, saTakerGets).getFullText (); @@ -1057,9 +1057,9 @@ TER CreateOfferLegacy::doApply () if (m_journal.trace) m_journal.trace << "adding to book: " << to_string (uBookBase) << " : " << saTakerPays.getHumanCurrency () << - "/" << RippleAddress::createHumanAccountID (saTakerPays.getIssuer ()) << + "/" << to_string (saTakerPays.getIssuer ()) << " -> " << saTakerGets.getHumanCurrency () << - "/" << RippleAddress::createHumanAccountID (saTakerGets.getIssuer ()); + "/" << to_string (saTakerGets.getIssuer ()); uDirectory = Ledger::getQualityIndex (uBookBase, uRate); // Use original rate. @@ -1077,13 +1077,13 @@ TER CreateOfferLegacy::doApply () { m_journal.debug << "sfAccount=" << - RippleAddress::createHumanAccountID (mTxnAccountID); + to_string (mTxnAccountID); m_journal.debug << "uPaysIssuerID=" << - RippleAddress::createHumanAccountID (uPaysIssuerID); + to_string (uPaysIssuerID); m_journal.debug << "uGetsIssuerID=" << - RippleAddress::createHumanAccountID (uGetsIssuerID); + to_string (uGetsIssuerID); m_journal.debug << "saTakerPays.isNative()=" << saTakerPays.isNative (); diff --git a/src/ripple/module/app/transactors/CreateOfferLegacy.h b/src/ripple/module/app/transactors/CreateOfferLegacy.h index 42cd47c1c2..498cae7a31 100644 --- a/src/ripple/module/app/transactors/CreateOfferLegacy.h +++ b/src/ripple/module/app/transactors/CreateOfferLegacy.h @@ -50,14 +50,20 @@ public: } private: + typedef std::unordered_set> + HardenedAccountSet; + + typedef std::unordered_set> + HardenedOfferSet; + bool isValidOffer ( SLE::ref sleOfferDir, - uint160 const& uOfferOwnerID, + Account const& uOfferOwnerID, STAmount const& saOfferPays, STAmount const& saOfferGets, - uint160 const& uTakerAccountID, - std::unordered_set>& usOfferUnfundedBecame, - std::unordered_set>& usAccountTouched, + Account const& uTakerAccountID, + HardenedOfferSet& usOfferUnfundedBecame, + HardenedAccountSet& usAccountTouched, STAmount& saOfferFunds); bool applyOffer ( @@ -79,13 +85,13 @@ private: bool isPassive, bool& isUnfunded, TER& terResult) const; - + TER takeOffers ( bool const bOpenLedger, bool const bPassive, bool const bSell, uint256 const& uBookBase, - uint160 const& uTakerAccountID, + Account const& uTakerAccountID, SLE::ref sleTakerAccount, STAmount const& saTakerPays, STAmount const& saTakerGets, @@ -94,7 +100,7 @@ private: bool& bUnfunded); // Offers found unfunded. - std::unordered_set> usOfferUnfundedFound; + HardenedOfferSet usOfferUnfundedFound; typedef std::pair missingOffer_t; std::set usMissingOffers; diff --git a/src/ripple/module/app/transactors/Payment.cpp b/src/ripple/module/app/transactors/Payment.cpp index 9c5b7f63d5..6e505b36eb 100644 --- a/src/ripple/module/app/transactors/Payment.cpp +++ b/src/ripple/module/app/transactors/Payment.cpp @@ -30,7 +30,7 @@ TER Payment::doApply () bool const bNoRippleDirect (uTxFlags & tfNoRippleDirect); bool const bPaths = mTxn.isFieldPresent (sfPaths); bool const bMax = mTxn.isFieldPresent (sfSendMax); - uint160 const uDstAccountID = mTxn.getFieldAccount160 (sfDestination); + Account const& uDstAccountID = mTxn.getFieldAccount160 (sfDestination); STAmount const saDstAmount = mTxn.getFieldAmount (sfAmount); STAmount maxSourceAmount; if (bMax) @@ -41,8 +41,8 @@ TER Payment::doApply () maxSourceAmount = STAmount ( saDstAmount.getCurrency (), mTxnAccountID, saDstAmount.getMantissa (), saDstAmount.getExponent (), saDstAmount < zero); - uint160 const uSrcCurrency = maxSourceAmount.getCurrency (); - uint160 const uDstCurrency = saDstAmount.getCurrency (); + auto const& uSrcCurrency = maxSourceAmount.getCurrency (); + auto const& uDstCurrency = saDstAmount.getCurrency (); // isZero() is XRP. FIX! bool const bXRPDirect = uSrcCurrency.isZero () && uDstCurrency.isZero (); @@ -82,7 +82,7 @@ TER Payment::doApply () return temBAD_AMOUNT; } - else if (CURRENCY_BAD == uSrcCurrency || CURRENCY_BAD == uDstCurrency) + else if (badCurrency() == uSrcCurrency || badCurrency() == uDstCurrency) { m_journal.trace << "Malformed transaction: Bad currency."; diff --git a/src/ripple/module/app/transactors/SetRegularKey.cpp b/src/ripple/module/app/transactors/SetRegularKey.cpp index 883bdbae59..2d062152df 100644 --- a/src/ripple/module/app/transactors/SetRegularKey.cpp +++ b/src/ripple/module/app/transactors/SetRegularKey.cpp @@ -52,7 +52,7 @@ TER SetRegularKey::doApply () if (mTxn.isFieldPresent (sfRegularKey)) { - uint160 uAuthKeyID = mTxn.getFieldAccount160 (sfRegularKey); + Account uAuthKeyID = mTxn.getFieldAccount160 (sfRegularKey); mTxnAccount->setFieldAccount (sfRegularKey, uAuthKeyID); } else diff --git a/src/ripple/module/app/transactors/SetTrust.cpp b/src/ripple/module/app/transactors/SetTrust.cpp index 55b0b68ba8..49a9400124 100644 --- a/src/ripple/module/app/transactors/SetTrust.cpp +++ b/src/ripple/module/app/transactors/SetTrust.cpp @@ -27,8 +27,8 @@ TER SetTrust::doApply () bool const bQualityIn (mTxn.isFieldPresent (sfQualityIn)); bool const bQualityOut (mTxn.isFieldPresent (sfQualityOut)); - uint160 const currency (saLimitAmount.getCurrency ()); - uint160 uDstAccountID (saLimitAmount.getIssuer ()); + Currency const currency (saLimitAmount.getCurrency ()); + Account uDstAccountID (saLimitAmount.getIssuer ()); // true, iff current is high account. bool const bHigh = mTxnAccountID > uDstAccountID; @@ -81,7 +81,7 @@ TER SetTrust::doApply () } // Check if destination makes sense. - if (!uDstAccountID || uDstAccountID == ACCOUNT_ONE) + if (!uDstAccountID || uDstAccountID == noAccount()) { m_journal.trace << "Malformed transaction: Destination account not specified."; @@ -145,8 +145,8 @@ TER SetTrust::doApply () std::uint32_t uLowQualityOut; std::uint32_t uHighQualityIn; std::uint32_t uHighQualityOut; - const uint160& uLowAccountID = !bHigh ? mTxnAccountID : uDstAccountID; - const uint160& uHighAccountID = bHigh ? mTxnAccountID : uDstAccountID; + auto const& uLowAccountID = !bHigh ? mTxnAccountID : uDstAccountID; + auto const& uHighAccountID = bHigh ? mTxnAccountID : uDstAccountID; SLE::ref sleLowAccount = !bHigh ? mTxnAccount : sleDst; SLE::ref sleHighAccount = bHigh ? mTxnAccount : sleDst; @@ -310,7 +310,7 @@ TER SetTrust::doApply () if (uFlagsIn != uFlagsOut) sleRippleState->setFieldU32 (sfFlags, uFlagsOut); - if (bDefault || CURRENCY_BAD == currency) + if (bDefault || badCurrency() == currency) { // Delete. @@ -350,14 +350,14 @@ TER SetTrust::doApply () // Another transaction could create the account and then this transaction would succeed. terResult = tecNO_LINE_INSUF_RESERVE; } - else if (CURRENCY_BAD == currency) + else if (badCurrency() == currency) { terResult = temBAD_CURRENCY; } else { // Zero balance in currency. - STAmount saBalance (STAmount (currency, ACCOUNT_ONE)); + STAmount saBalance (STAmount (currency, noAccount())); uint256 index (Ledger::getRippleStateIndex ( mTxnAccountID, uDstAccountID, currency)); diff --git a/src/ripple/module/app/transactors/Transactor.h b/src/ripple/module/app/transactors/Transactor.h index 4ca1fe66e7..908d05be5f 100644 --- a/src/ripple/module/app/transactors/Transactor.h +++ b/src/ripple/module/app/transactors/Transactor.h @@ -37,7 +37,7 @@ protected: TransactionEngine* mEngine; TransactionEngineParams mParams; - uint160 mTxnAccountID; + Account mTxnAccountID; STAmount mFeeDue; STAmount mPriorBalance; // Balance before fees. STAmount mSourceBalance; // Balance after fees. @@ -47,7 +47,7 @@ protected: RippleAddress mSigningPubKey; beast::Journal m_journal; - + virtual TER preCheck (); virtual TER checkSeq (); virtual TER payFee (); @@ -61,7 +61,7 @@ protected: virtual TER doApply () = 0; Transactor ( - const SerializedTransaction& txn, + const SerializedTransaction& txn, TransactionEngineParams params, TransactionEngine* engine, beast::Journal journal = beast::Journal ()); diff --git a/src/ripple/module/app/tx/TransactionAcquire.cpp b/src/ripple/module/app/tx/TransactionAcquire.cpp index 9944f96061..657b71493e 100644 --- a/src/ripple/module/app/tx/TransactionAcquire.cpp +++ b/src/ripple/module/app/tx/TransactionAcquire.cpp @@ -28,9 +28,6 @@ enum TX_ACQUIRE_TIMEOUT = 250 }; -typedef std::map::value_type u160_prop_pair; -typedef std::map::value_type u256_lct_pair; - TransactionAcquire::TransactionAcquire (uint256 const& hash, clock_type& clock) : PeerSet (hash, TX_ACQUIRE_TIMEOUT, true, clock, deprecatedLogs().journal("TransactionAcquire")) diff --git a/src/ripple/module/app/tx/TransactionEngine.h b/src/ripple/module/app/tx/TransactionEngine.h index a569090310..1cb07688e1 100644 --- a/src/ripple/module/app/tx/TransactionEngine.h +++ b/src/ripple/module/app/tx/TransactionEngine.h @@ -39,21 +39,11 @@ private: TER setAuthorized (const SerializedTransaction & txn, bool bMustSetGenerator); TER checkSig (const SerializedTransaction & txn); - TER takeOffers ( - bool bPassive, - uint256 const & uBookBase, - const uint160 & uTakerAccountID, - SLE::ref sleTakerAccount, - const STAmount & saTakerPays, - const STAmount & saTakerGets, - STAmount & saTakerPaid, - STAmount & saTakerGot); - protected: Ledger::pointer mLedger; int mTxnSeq; - uint160 mTxnAccountID; + Account mTxnAccountID; SLE::pointer mTxnAccount; void txnWrite (); diff --git a/src/ripple/module/app/tx/TransactionMeta.cpp b/src/ripple/module/app/tx/TransactionMeta.cpp index 1643f28957..b07cb12b6d 100644 --- a/src/ripple/module/app/tx/TransactionMeta.cpp +++ b/src/ripple/module/app/tx/TransactionMeta.cpp @@ -113,7 +113,7 @@ std::vector TransactionMetaSet::getAffectedAccounts () if (lim != nullptr) { - uint160 issuer = lim->getIssuer (); + auto issuer = lim->getIssuer (); if (issuer.isNonZero ()) { diff --git a/src/ripple/module/data/protocol/FieldNames.cpp b/src/ripple/module/data/protocol/FieldNames.cpp index 453344f87a..2a3abe2873 100644 --- a/src/ripple/module/data/protocol/FieldNames.cpp +++ b/src/ripple/module/data/protocol/FieldNames.cpp @@ -31,14 +31,16 @@ SField::StaticLockType& SField::getMutex () return mutex; } -SField sfInvalid (-1), sfGeneric (0); -SField sfLedgerEntry (STI_LEDGERENTRY, 1, "LedgerEntry"); -SField sfTransaction (STI_TRANSACTION, 1, "Transaction"); -SField sfValidation (STI_VALIDATION, 1, "Validation"); -SField sfHash (STI_HASH256, 257, "hash"); -SField sfIndex (STI_HASH256, 258, "index"); +const SField sfInvalid (-1), sfGeneric (0); +const SField sfLedgerEntry (STI_LEDGERENTRY, 1, "LedgerEntry"); +const SField sfTransaction (STI_TRANSACTION, 1, "Transaction"); +const SField sfValidation (STI_VALIDATION, 1, "Validation"); +const SField sfHash (STI_HASH256, 257, "hash"); +const SField sfIndex (STI_HASH256, 258, "index"); -#define FIELD(name, type, index) SField sf##name(FIELD_CODE(STI_##type, index), STI_##type, index, #name); +// TODO(tom): Remove this horrorr. +#define FIELD(name, type, index) \ + SField sf##name(FIELD_CODE(STI_##type, index), STI_##type, index, #name); #define TYPE(name, type, index) #include #undef FIELD @@ -58,11 +60,15 @@ static int initFields () return 0; } -static const int f = initFields (); +static const int forceInitializionOfFields = initFields (); -SField::SField (SerializedTypeID tid, int fv) : fieldCode (FIELD_CODE (tid, fv)), fieldType (tid), fieldValue (fv), - fieldMeta (sMD_Default), fieldNum (++num), signingField (true), jsonName (nullptr) +SField::SField (SerializedTypeID tid, int fv) + : fieldCode (FIELD_CODE (tid, fv)), fieldType (tid), fieldValue (fv), + fieldMeta (sMD_Default), + fieldNum (++num), + signingField (true), + jsonName (nullptr) { // call with the map mutex fieldName = beast::lexicalCast (tid) + "/" + @@ -88,13 +94,14 @@ SField::ref SField::getField (int code) if (it != codeToField.end ()) return * (it->second); - if (field > 255) // don't dynamically extend types that have no binary encoding + // Don't dynamically extend types that have no binary encoding. + if (field > 255) return sfInvalid; switch (type) { - // types we are willing to dynamically extend - + // Types we are willing to dynamically extend + // TODO(tom): Remove this horrorr. #define FIELD(name, type, index) #define TYPE(name, type, index) case STI_##type: #include @@ -133,8 +140,8 @@ std::string SField::getName () const if (fieldValue == 0) return ""; - return beast::lexicalCastThrow (static_cast (fieldType)) + "/" + - beast::lexicalCastThrow (fieldValue); + return std::to_string(static_cast (fieldType)) + "/" + + std::to_string(fieldValue); } SField::ref SField::getField (const std::string& fieldName) @@ -160,4 +167,3 @@ SField::~SField () } } // ripple - diff --git a/src/ripple/module/data/protocol/FieldNames.h b/src/ripple/module/data/protocol/FieldNames.h index d3acae2c2d..e0e782edca 100644 --- a/src/ripple/module/data/protocol/FieldNames.h +++ b/src/ripple/module/data/protocol/FieldNames.h @@ -20,6 +20,8 @@ #ifndef RIPPLE_FIELDNAMES_H #define RIPPLE_FIELDNAMES_H +#include + namespace ripple { // VFALCO TODO lose the macro. @@ -64,8 +66,6 @@ public: static const int sMD_Always = 0x10; // value when node containing it is affected at all static const int sMD_Default = sMD_ChangeOrig | sMD_ChangeNew | sMD_DeleteFinal | sMD_Create; -public: - const int fieldCode; // (type<<16)|index const SerializedTypeID fieldType; // STI_* const int fieldValue; // Code number for protocol @@ -234,12 +234,13 @@ protected: static StaticLockType& getMutex (); // VFALCO NOTE can this be replaced with an atomic int???! - static int num; + static int num; SField (SerializedTypeID id, int val); }; -extern SField sfInvalid, sfGeneric, sfLedgerEntry, sfTransaction, sfValidation; +extern const SField sfInvalid, sfGeneric, sfLedgerEntry, sfTransaction, + sfValidation; #define FIELD(name, type, index) extern SField sf##name; #define TYPE(name, type, index) diff --git a/src/ripple/module/data/protocol/Protocol.h b/src/ripple/module/data/protocol/Protocol.h index e765f29176..bda1721efc 100644 --- a/src/ripple/module/data/protocol/Protocol.h +++ b/src/ripple/module/data/protocol/Protocol.h @@ -62,13 +62,6 @@ typedef uint256 TxID; */ typedef std::uint32_t TxSeq; // VFALCO NOTE Should read TxIndex or TxNum -/** An account hash. - - The hash is used to uniquely identify the account. -*/ -//typedef uint160 AccountHash; -//typedef uint260 ValidatorID; - } // ripple #endif diff --git a/src/ripple/module/data/protocol/RippleAddress.cpp b/src/ripple/module/data/protocol/RippleAddress.cpp index 425f179985..c13b057541 100644 --- a/src/ripple/module/data/protocol/RippleAddress.cpp +++ b/src/ripple/module/data/protocol/RippleAddress.cpp @@ -104,21 +104,25 @@ RippleAddress RippleAddress::createNodePublic (const std::string& strPublic) return naNew; } -uint160 RippleAddress::getNodeID () const +NodeID RippleAddress::getNodeID () const { switch (nVersion) { case VER_NONE: throw std::runtime_error ("unset source - getNodeID"); - case VER_NODE_PUBLIC: + case VER_NODE_PUBLIC: { // Note, we are encoding the left. - return Hash160 (vchData); + NodeID node; + node.copyFrom(Hash160 (vchData)); + return node; + } default: throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); } } + Blob const& RippleAddress::getNodePublic () const { switch (nVersion) @@ -287,7 +291,7 @@ void RippleAddress::signNodePrivate (uint256 const& hash, Blob& vchSig) const // AccountID // -uint160 RippleAddress::getAccountID () const +Account RippleAddress::getAccountID () const { switch (nVersion) { @@ -295,11 +299,15 @@ uint160 RippleAddress::getAccountID () const throw std::runtime_error ("unset source - getAccountID"); case VER_ACCOUNT_ID: - return uint160 (vchData); + return Account(vchData); - case VER_ACCOUNT_PUBLIC: + case VER_ACCOUNT_PUBLIC: { // Note, we are encoding the left. - return Hash160 (vchData); + // TODO(tom): decipher this comment. + Account account; + account.copyFrom (Hash160 (vchData)); + return account; + } default: throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); @@ -352,11 +360,12 @@ std::string RippleAddress::humanAccountID () const } } -bool RippleAddress::setAccountID (const std::string& strAccountID, Base58::Alphabet const& alphabet) +bool RippleAddress::setAccountID ( + const std::string& strAccountID, Base58::Alphabet const& alphabet) { if (strAccountID.empty ()) { - setAccountID (uint160 ()); + setAccountID (Account ()); mIsValid = true; } @@ -368,10 +377,9 @@ bool RippleAddress::setAccountID (const std::string& strAccountID, Base58::Alpha return mIsValid; } -void RippleAddress::setAccountID (const uint160& hash160) +void RippleAddress::setAccountID (Account const& hash160) { mIsValid = true; - SetData (VER_ACCOUNT_ID, hash160); } @@ -379,9 +387,10 @@ void RippleAddress::setAccountID (const uint160& hash160) // AccountPublic // -RippleAddress RippleAddress::createAccountPublic (const RippleAddress& naGenerator, int iSeq) +RippleAddress RippleAddress::createAccountPublic ( + const RippleAddress& generator, int iSeq) { - CKey ckPub (naGenerator, iSeq); + CKey ckPub (generator, iSeq); RippleAddress naNew; naNew.setAccountPublic (ckPub.GetPubKey ()); @@ -447,7 +456,8 @@ void RippleAddress::setAccountPublic (const RippleAddress& generator, int seq) setAccountPublic (pubkey.GetPubKey ()); } -bool RippleAddress::accountPublicVerify (uint256 const& uHash, Blob const& vucSig, ECDSA fullyCanonical) const +bool RippleAddress::accountPublicVerify ( + uint256 const& uHash, Blob const& vucSig, ECDSA fullyCanonical) const { CKey ckPublic; @@ -456,7 +466,8 @@ bool RippleAddress::accountPublicVerify (uint256 const& uHash, Blob const& vucSi if (bVerified && !ckPublic.SetPubKey (getAccountPublic ())) { // Bad private key. - WriteLog (lsWARNING, RippleAddress) << "accountPublicVerify: Bad private key."; + WriteLog (lsWARNING, RippleAddress) + << "accountPublicVerify: Bad private key."; bVerified = false; } else @@ -467,11 +478,10 @@ bool RippleAddress::accountPublicVerify (uint256 const& uHash, Blob const& vucSi return bVerified; } -RippleAddress RippleAddress::createAccountID (const uint160& uiAccountID) +RippleAddress RippleAddress::createAccountID (Account const& account) { RippleAddress na; - - na.setAccountID (uiAccountID); + na.setAccountID (account); return na; } @@ -480,11 +490,12 @@ RippleAddress RippleAddress::createAccountID (const uint160& uiAccountID) // AccountPrivate // -RippleAddress RippleAddress::createAccountPrivate (const RippleAddress& naGenerator, const RippleAddress& naSeed, int iSeq) +RippleAddress RippleAddress::createAccountPrivate ( + const RippleAddress& generator, const RippleAddress& naSeed, int iSeq) { RippleAddress naNew; - naNew.setAccountPrivate (naGenerator, naSeed, iSeq); + naNew.setAccountPrivate (generator, naSeed, iSeq); return naNew; } @@ -500,7 +511,7 @@ uint256 RippleAddress::getAccountPrivate () const return uint256 (vchData); default: - throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); + throw std::runtime_error ("bad source: " + std::to_string(nVersion)); } } @@ -515,35 +526,35 @@ std::string RippleAddress::humanAccountPrivate () const return ToString (); default: - throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); + throw std::runtime_error ("bad source: " + std::to_string(nVersion)); } } bool RippleAddress::setAccountPrivate (const std::string& strPrivate) { - mIsValid = SetString (strPrivate, VER_ACCOUNT_PRIVATE, Base58::getRippleAlphabet ()); + mIsValid = SetString ( + strPrivate, VER_ACCOUNT_PRIVATE, Base58::getRippleAlphabet ()); return mIsValid; } void RippleAddress::setAccountPrivate (Blob const& vPrivate) { - mIsValid = true; - + mIsValid = true; SetData (VER_ACCOUNT_PRIVATE, vPrivate); } void RippleAddress::setAccountPrivate (uint256 hash256) { mIsValid = true; - SetData (VER_ACCOUNT_PRIVATE, hash256); } -void RippleAddress::setAccountPrivate (const RippleAddress& naGenerator, const RippleAddress& naSeed, int seq) +void RippleAddress::setAccountPrivate ( + const RippleAddress& generator, const RippleAddress& naSeed, int seq) { CKey ckPubkey = CKey (naSeed.getSeed ()); - CKey ckPrivkey = CKey (naGenerator, ckPubkey.GetSecretBN (), seq); + CKey ckPrivkey = CKey (generator, ckPubkey.GetSecretBN (), seq); uint256 uPrivKey; ckPrivkey.GetPrivateKeyU (uPrivKey); @@ -559,33 +570,36 @@ bool RippleAddress::accountPrivateSign (uint256 const& uHash, Blob& vucSig) cons if (!ckPrivate.SetPrivateKeyU (getAccountPrivate ())) { // Bad private key. - WriteLog (lsWARNING, RippleAddress) << "accountPrivateSign: Bad private key."; + WriteLog (lsWARNING, RippleAddress) + << "accountPrivateSign: Bad private key."; bResult = false; } else { bResult = ckPrivate.Sign (uHash, vucSig); - CondLog (!bResult, lsWARNING, RippleAddress) << "accountPrivateSign: Signing failed."; + CondLog (!bResult, lsWARNING, RippleAddress) + << "accountPrivateSign: Signing failed."; } return bResult; } -Blob RippleAddress::accountPrivateEncrypt (const RippleAddress& naPublicTo, Blob const& vucPlainText) const +Blob RippleAddress::accountPrivateEncrypt ( + const RippleAddress& naPublicTo, Blob const& vucPlainText) const { - CKey ckPrivate; - CKey ckPublic; - Blob vucCipherText; + CKey ckPrivate; + CKey ckPublic; + Blob vucCipherText; if (!ckPublic.SetPubKey (naPublicTo.getAccountPublic ())) { - // Bad public key. - WriteLog (lsWARNING, RippleAddress) << "accountPrivateEncrypt: Bad public key."; + WriteLog (lsWARNING, RippleAddress) + << "accountPrivateEncrypt: Bad public key."; } else if (!ckPrivate.SetPrivateKeyU (getAccountPrivate ())) { - // Bad private key. - WriteLog (lsWARNING, RippleAddress) << "accountPrivateEncrypt: Bad private key."; + WriteLog (lsWARNING, RippleAddress) + << "accountPrivateEncrypt: Bad private key."; } else { @@ -601,7 +615,8 @@ Blob RippleAddress::accountPrivateEncrypt (const RippleAddress& naPublicTo, Blob return vucCipherText; } -Blob RippleAddress::accountPrivateDecrypt (const RippleAddress& naPublicFrom, Blob const& vucCipherText) const +Blob RippleAddress::accountPrivateDecrypt ( + const RippleAddress& naPublicFrom, Blob const& vucCipherText) const { CKey ckPrivate; CKey ckPublic; @@ -609,13 +624,13 @@ Blob RippleAddress::accountPrivateDecrypt (const RippleAddress& naPublicFrom, Bl if (!ckPublic.SetPubKey (naPublicFrom.getAccountPublic ())) { - // Bad public key. - WriteLog (lsWARNING, RippleAddress) << "accountPrivateDecrypt: Bad public key."; + WriteLog (lsWARNING, RippleAddress) + << "accountPrivateDecrypt: Bad public key."; } else if (!ckPrivate.SetPrivateKeyU (getAccountPrivate ())) { - // Bad private key. - WriteLog (lsWARNING, RippleAddress) << "accountPrivateDecrypt: Bad private key."; + WriteLog (lsWARNING, RippleAddress) + << "accountPrivateDecrypt: Bad private key."; } else { @@ -648,7 +663,7 @@ Blob const& RippleAddress::getGenerator () const return vchData; default: - throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); + throw std::runtime_error ("bad source: " + std::to_string(nVersion)); } } @@ -663,21 +678,20 @@ std::string RippleAddress::humanGenerator () const return ToString (); default: - throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); + throw std::runtime_error ("bad source: " + std::to_string(nVersion)); } } bool RippleAddress::setGenerator (const std::string& strGenerator) { - mIsValid = SetString (strGenerator, VER_FAMILY_GENERATOR, Base58::getRippleAlphabet ()); - + mIsValid = SetString ( + strGenerator, VER_FAMILY_GENERATOR, Base58::getRippleAlphabet ()); return mIsValid; } void RippleAddress::setGenerator (Blob const& vPublic) { mIsValid = true; - SetData (VER_FAMILY_GENERATOR, vPublic); } @@ -685,9 +699,7 @@ RippleAddress RippleAddress::createGeneratorPublic (const RippleAddress& naSeed) { CKey ckSeed (naSeed.getSeed ()); RippleAddress naNew; - naNew.setGenerator (ckSeed.GetPubKey ()); - return naNew; } @@ -706,7 +718,7 @@ uint128 RippleAddress::getSeed () const return uint128 (vchData); default: - throw std::runtime_error (str (boost::format ("bad source: %d") % int (nVersion))); + throw std::runtime_error ("bad source: " + std::to_string(nVersion)); } } @@ -875,21 +887,21 @@ public: expect (naNodePublic.verifyNodePublic (uHash, vucTextSig, ECDSA::strict), "Verify failed."); // Construct a public generator from the seed. - RippleAddress naGenerator = RippleAddress::createGeneratorPublic (naSeed); + RippleAddress generator = RippleAddress::createGeneratorPublic (naSeed); - expect (naGenerator.humanGenerator () == "fhuJKrhSDzV2SkjLn9qbwm5AaRmrxDPfFsHDCP6yfDZWcxDFz4mt", naGenerator.humanGenerator ()); + expect (generator.humanGenerator () == "fhuJKrhSDzV2SkjLn9qbwm5AaRmrxDPfFsHDCP6yfDZWcxDFz4mt", generator.humanGenerator ()); // Create account #0 public/private key pair. - RippleAddress naAccountPublic0 = RippleAddress::createAccountPublic (naGenerator, 0); - RippleAddress naAccountPrivate0 = RippleAddress::createAccountPrivate (naGenerator, naSeed, 0); + RippleAddress naAccountPublic0 = RippleAddress::createAccountPublic (generator, 0); + RippleAddress naAccountPrivate0 = RippleAddress::createAccountPrivate (generator, naSeed, 0); expect (naAccountPublic0.humanAccountID () == "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh", naAccountPublic0.humanAccountID ()); expect (naAccountPublic0.humanAccountPublic () == "aBQG8RQAzjs1eTKFEAQXr2gS4utcDiEC9wmi7pfUPTi27VCahwgw", naAccountPublic0.humanAccountPublic ()); expect (naAccountPrivate0.humanAccountPrivate () == "p9JfM6HHi64m6mvB6v5k7G2b1cXzGmYiCNJf6GHPKvFTWdeRVjh", naAccountPrivate0.humanAccountPrivate ()); // Create account #1 public/private key pair. - RippleAddress naAccountPublic1 = RippleAddress::createAccountPublic (naGenerator, 1); - RippleAddress naAccountPrivate1 = RippleAddress::createAccountPrivate (naGenerator, naSeed, 1); + RippleAddress naAccountPublic1 = RippleAddress::createAccountPublic (generator, 1); + RippleAddress naAccountPrivate1 = RippleAddress::createAccountPrivate (generator, naSeed, 1); expect (naAccountPublic1.humanAccountID () == "r4bYF7SLUMD7QgSLLpgJx38WJSY12ViRjP", naAccountPublic1.humanAccountID ()); expect (naAccountPublic1.humanAccountPublic () == "aBPXpTfuLy1Bhk3HnGTTAqnovpKWQ23NpFMNkAF6F1Atg5vDyPrw", naAccountPublic1.humanAccountPublic ()); diff --git a/src/ripple/module/data/protocol/RippleAddress.h b/src/ripple/module/data/protocol/RippleAddress.h index 289be3e246..2aca6808e1 100644 --- a/src/ripple/module/data/protocol/RippleAddress.h +++ b/src/ripple/module/data/protocol/RippleAddress.h @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -36,7 +37,9 @@ namespace ripple { // // Used to hold addresses and parse and produce human formats. // -// XXX This needs to be reworked to store data in uint160 and uint256. Conversion to CBase58Data should happen as needed. +// XXX This needs to be reworked to store data in uint160 and uint256. +// Conversion to CBase58Data should only happen as needed. + class RippleAddress : public CBase58Data { private: @@ -71,15 +74,17 @@ public: // // Node Public - Also used for Validators // - uint160 getNodeID () const; + NodeID getNodeID () const; Blob const& getNodePublic () const; std::string humanNodePublic () const; bool setNodePublic (const std::string& strPublic); void setNodePublic (Blob const& vPublic); - bool verifyNodePublic (uint256 const& hash, Blob const& vchSig, ECDSA mustBeFullyCanonical) const; - bool verifyNodePublic (uint256 const& hash, const std::string& strSig, ECDSA mustBeFullyCanonical) const; + bool verifyNodePublic (uint256 const& hash, Blob const& vchSig, + ECDSA mustBeFullyCanonical) const; + bool verifyNodePublic (uint256 const& hash, const std::string& strSig, + ECDSA mustBeFullyCanonical) const; static RippleAddress createNodePublic (const RippleAddress& naSeed); static RippleAddress createNodePublic (Blob const& vPublic); @@ -103,31 +108,25 @@ public: // // Accounts IDs // - uint160 getAccountID () const; + Account getAccountID () const; std::string humanAccountID () const; - bool setAccountID (const std::string& strAccountID, Base58::Alphabet const& alphabet = Base58::getRippleAlphabet()); - void setAccountID (const uint160& hash160In); + bool setAccountID ( + const std::string& strAccountID, + Base58::Alphabet const& alphabet = Base58::getRippleAlphabet()); + void setAccountID (Account const& hash160In); + #if 0 static RippleAddress createAccountID (const std::string& strAccountID) { RippleAddress na; na.setAccountID (strAccountID); return na; } + #endif - static RippleAddress createAccountID (const uint160& uiAccountID); - - static std::string createHumanAccountID (const uint160& uiAccountID) - { - return createAccountID (uiAccountID).humanAccountID (); - } - - static std::string createHumanAccountID (Blob const& vPrivate) - { - return createAccountPrivate (vPrivate).humanAccountID (); - } + static RippleAddress createAccountID (Account const& uiAccountID); // // Accounts Public @@ -140,14 +139,13 @@ public: void setAccountPublic (Blob const& vPublic); void setAccountPublic (const RippleAddress& generator, int seq); - bool accountPublicVerify (uint256 const& uHash, Blob const& vucSig, ECDSA mustBeFullyCanonical) const; + bool accountPublicVerify (uint256 const& uHash, Blob const& vucSig, + ECDSA mustBeFullyCanonical) const; static RippleAddress createAccountPublic (Blob const& vPublic) { - RippleAddress naNew; - + RippleAddress naNew; naNew.setAccountPublic (vPublic); - return naNew; } @@ -157,7 +155,8 @@ public: } // Create a deterministic public key from a public generator. - static RippleAddress createAccountPublic (const RippleAddress& naGenerator, int iSeq); + static RippleAddress createAccountPublic ( + const RippleAddress& naGenerator, int iSeq); // // Accounts Private @@ -169,17 +168,21 @@ public: bool setAccountPrivate (const std::string& strPrivate); void setAccountPrivate (Blob const& vPrivate); void setAccountPrivate (uint256 hash256); - void setAccountPrivate (const RippleAddress& naGenerator, const RippleAddress& naSeed, int seq); + void setAccountPrivate (const RippleAddress& naGenerator, + const RippleAddress& naSeed, int seq); bool accountPrivateSign (uint256 const& uHash, Blob& vucSig) const; // Encrypt a message. - Blob accountPrivateEncrypt (const RippleAddress& naPublicTo, Blob const& vucPlainText) const; + Blob accountPrivateEncrypt ( + const RippleAddress& naPublicTo, Blob const& vucPlainText) const; // Decrypt a message. - Blob accountPrivateDecrypt (const RippleAddress& naPublicFrom, Blob const& vucCipherText) const; + Blob accountPrivateDecrypt ( + const RippleAddress& naPublicFrom, Blob const& vucCipherText) const; - static RippleAddress createAccountPrivate (const RippleAddress& naGenerator, const RippleAddress& naSeed, int iSeq); + static RippleAddress createAccountPrivate ( + const RippleAddress& generator, const RippleAddress& seed, int iSeq); static RippleAddress createAccountPrivate (Blob const& vPrivate) { @@ -247,7 +250,7 @@ struct RipplePublicKeyHashTraits::assign { void operator() (value_type& value, RippleAddress const& v) const { - uint160 const ui (v.getNodeID ()); + auto const ui (v.getNodeID ()); construct (ui.begin(), ui.end(), value); } }; @@ -269,7 +272,7 @@ struct RippleAccountIDTraits::assign { void operator() (value_type& value, RippleAddress const& v) const { - uint160 const ui (v.getAccountID ()); + auto const ui (v.getAccountID ()); construct (ui.begin(), ui.end(), value); } }; diff --git a/src/ripple/module/data/protocol/RippleSystem.h b/src/ripple/module/data/protocol/RippleSystem.h index 78585b6f49..d88ab2b2a0 100644 --- a/src/ripple/module/data/protocol/RippleSystem.h +++ b/src/ripple/module/data/protocol/RippleSystem.h @@ -54,9 +54,7 @@ public: // It will be necessary to rewrite some of them to use string streams. // #define SYSTEM_NAME "ripple" -#define SYSTEM_CURRENCY_CODE "XRP" #define SYSTEM_CURRENCY_PRECISION 6 -#define SYSTEM_CURRENCY_CODE_RIPPLE "XRR" } // ripple diff --git a/src/ripple/module/data/protocol/STAmount.cpp b/src/ripple/module/data/protocol/STAmount.cpp index 0ab07a5a0d..171479a9bd 100644 --- a/src/ripple/module/data/protocol/STAmount.cpp +++ b/src/ripple/module/data/protocol/STAmount.cpp @@ -19,77 +19,16 @@ #include +#include + namespace ripple { -std::uint64_t STAmount::uRateOne = STAmount::getRate (STAmount (1), STAmount (1)); - -bool STAmount::issuerFromString (uint160& uDstIssuer, const std::string& sIssuer) -{ - bool bSuccess = true; - - if (sIssuer.size () == (160 / 4)) - { - uDstIssuer.SetHex (sIssuer); - } - else - { - RippleAddress raIssuer; - - if (raIssuer.setAccountID (sIssuer)) - { - uDstIssuer = raIssuer.getAccountID (); - } - else - { - bSuccess = false; - } - } - - return bSuccess; -} - -// --> sCurrency: "", "XRP", or three letter ISO code. -bool STAmount::currencyFromString (uint160& uDstCurrency, const std::string& sCurrency) -{ - bool bSuccess = true; - - if (sCurrency.empty () || !sCurrency.compare (SYSTEM_CURRENCY_CODE)) - { - uDstCurrency.zero (); - } - else if (3 == sCurrency.size ()) - { - Blob vucIso (3); - - std::transform (sCurrency.begin (), sCurrency.end (), vucIso.begin (), ::toupper); - - // std::string sIso; - // sIso.assign(vucIso.begin(), vucIso.end()); - - Serializer s; - - s.addZeros (96 / 8); - s.addRaw (vucIso); - s.addZeros (16 / 8); - s.addZeros (24 / 8); - - s.get160 (uDstCurrency, 0); - } - else if (40 == sCurrency.size ()) - { - bSuccess = uDstCurrency.SetHex (sCurrency); - } - else - { - bSuccess = false; - } - - return bSuccess; -} +std::uint64_t STAmount::uRateOne = + STAmount::getRate (STAmount (1), STAmount (1)); std::string STAmount::getHumanCurrency () const { - return createHumanCurrency (mCurrency); + return to_string (mCurrency); } bool STAmount::bSetJson (const Json::Value& jvSource) @@ -152,7 +91,7 @@ STAmount::STAmount (SField::ref n, const Json::Value& v) else value = v; - mIsNative = !currency.isString () || currency.asString ().empty () || (currency.asString () == SYSTEM_CURRENCY_CODE); + mIsNative = !currency.isString () || currency.asString ().empty () || (currency.asString () == systemCurrencyCode()); if (mIsNative) { @@ -162,11 +101,11 @@ STAmount::STAmount (SField::ref n, const Json::Value& v) else { // non-XRP - if (!currencyFromString (mCurrency, currency.asString ())) + if (!to_currency (mCurrency, currency.asString ())) throw std::runtime_error ("invalid currency"); if (!issuer.isString () - || !issuerFromString (mIssuer, issuer.asString ())) + || !to_issuer (mIssuer, issuer.asString ())) throw std::runtime_error ("invalid issuer"); if (mIssuer.isZero ()) @@ -216,53 +155,30 @@ STAmount::STAmount (SField::ref n, const Json::Value& v) throw std::runtime_error ("invalid amount type"); } -std::string STAmount::createHumanCurrency (const uint160& uCurrency) -{ - static uint160 const sIsoBits ("FFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFF"); - - if (uCurrency.isZero ()) - { - return SYSTEM_CURRENCY_CODE; - } - - if (CURRENCY_ONE == uCurrency) - { - return "1"; - } - - if ((uCurrency & sIsoBits).isZero ()) - { - // The offset of the 3 character ISO code in the currency descriptor - int const isoOffset = 12; - - std::string const iso( - uCurrency.data () + isoOffset, - uCurrency.data () + isoOffset + 3); - - // Specifying the system currency code using ISO-style representation - // is not allowed. - if (iso != SYSTEM_CURRENCY_CODE) - return iso; - } - - return to_string (uCurrency); -} - bool STAmount::setValue (const std::string& sAmount) { // Note: mIsNative and mCurrency must be set already! - static boost::regex reNumber ("\\`([+-]?)(\\d*)(\\.(\\d*))?([eE]([+-]?)(\\d+))?\\'"); + static boost::regex reNumber ( + "\\`([+-]?)(\\d*)(\\.(\\d*))?([eE]([+-]?)(\\d+))?\\'"); boost::smatch smMatch; if (!boost::regex_match (sAmount, smMatch, reNumber)) { - WriteLog (lsWARNING, STAmount) << "Number not valid: \"" << sAmount << "\""; + WriteLog (lsWARNING, STAmount) + << "Number not valid: \"" << sAmount << "\""; return false; } - // Match fields: 0 = whole input, 1 = sign, 2 = integer portion, 3 = whole fraction (with '.') - // 4 = fraction (without '.'), 5 = whole exponent (with 'e'), 6 = exponent sign, 7 = exponent number + // Match fields: + // 0 = whole input + // 1 = sign + // 2 = integer portion + // 3 = whole fraction (with '.') + // 4 = fraction (without '.') + // 5 = whole exponent (with 'e') + // 6 = exponent sign + // 7 = exponent number try { @@ -337,7 +253,7 @@ bool STAmount::setFullValue (const std::string& sAmount, const std::string& sCur // // Figure out the currency. // - if (!currencyFromString (mCurrency, sCurrency)) + if (!to_currency (mCurrency, sCurrency)) { WriteLog (lsINFO, STAmount) << "Currency malformed: " << sCurrency; @@ -530,14 +446,18 @@ STAmount* STAmount::construct (SerializerIterator& sit, SField::ref name) return new STAmount (name, value, true); // negative } - uint160 currency = sit.get160 (); + Currency currency; + currency.copyFrom (sit.get160 ()); if (!currency) throw std::runtime_error ("invalid non-native currency"); - uint160 issuer = sit.get160 (); + Account issuer; + issuer.copyFrom (sit.get160 ()); + + // 10 bits for the offset, sign and "not native" flag + int offset = static_cast (value >> (64 - 10)); - int offset = static_cast (value >> (64 - 10)); // 10 bits for the offset, sign and "not native" flag value &= ~ (1023ull << (64 - 10)); if (value) @@ -545,8 +465,13 @@ STAmount* STAmount::construct (SerializerIterator& sit, SField::ref name) bool isNegative = (offset & 256) == 0; offset = (offset & 255) - 97; // center the range - if ((value < cMinValue) || (value > cMaxValue) || (offset < cMinOffset) || (offset > cMaxOffset)) + if (value < cMinValue || + value > cMaxValue || + offset < cMinOffset || + offset > cMaxOffset) + { throw std::runtime_error ("invalid currency value"); + } return new STAmount (name, currency, issuer, value, offset, isNegative); } @@ -919,8 +844,8 @@ STAmount operator- (const STAmount& v1, const STAmount& v2) // NIKB TODO Make Amount::divide skip math if den == QUALITY_ONE STAmount STAmount::divide ( - const STAmount& num, const STAmount& den, const uint160& currency, - const uint160& issuer) + const STAmount& num, const STAmount& den, Currency const& currency, + Account const& issuer) { if (den == zero) throw std::runtime_error ("division by zero"); @@ -964,8 +889,8 @@ STAmount STAmount::divide ( } STAmount STAmount::multiply ( - const STAmount& v1, const STAmount& v2, const uint160& currency, - const uint160& issuer) + const STAmount& v1, const STAmount& v2, Currency const& currency, + Account const& issuer) { if (v1 == zero || v2 == zero) return STAmount (currency, issuer); @@ -1039,7 +964,7 @@ std::uint64_t STAmount::getRate (const STAmount& offerOut, const STAmount& offer try { - STAmount r = divide (offerIn, offerOut, CURRENCY_ONE, ACCOUNT_ONE); + STAmount r = divide (offerIn, offerOut, noCurrency(), noAccount()); if (r == zero) // offer is too good return 0; @@ -1060,12 +985,12 @@ std::uint64_t STAmount::getRate (const STAmount& offerOut, const STAmount& offer STAmount STAmount::setRate (std::uint64_t rate) { if (rate == 0) - return STAmount (CURRENCY_ONE, ACCOUNT_ONE); + return STAmount (noCurrency(), noAccount()); std::uint64_t mantissa = rate & ~ (255ull << (64 - 8)); int exponent = static_cast (rate >> (64 - 8)) - 100; - return STAmount (CURRENCY_ONE, ACCOUNT_ONE, mantissa, exponent); + return STAmount (noCurrency(), noAccount(), mantissa, exponent); } STAmount STAmount::getPay (const STAmount& offerOut, const STAmount& offerIn, const STAmount& needed) @@ -1080,7 +1005,7 @@ STAmount STAmount::getPay (const STAmount& offerOut, const STAmount& offerIn, co return needed; } - STAmount ret = divide (multiply (needed, offerIn, CURRENCY_ONE, ACCOUNT_ONE), offerOut, offerIn.getCurrency (), offerIn.getIssuer ()); + STAmount ret = divide (multiply (needed, offerIn, noCurrency(), noAccount()), offerOut, offerIn.getCurrency (), offerIn.getIssuer ()); return (ret > offerIn) ? offerIn : ret; } @@ -1105,10 +1030,10 @@ std::string STAmount::getFullText () const if (!mIssuer) ret += "0"; - else if (mIssuer == ACCOUNT_ONE) + else if (mIssuer == noAccount()) ret += "1"; else - ret += RippleAddress::createHumanAccountID (mIssuer); + ret += to_string (mIssuer); } return ret; @@ -1162,7 +1087,7 @@ void STAmount::setJson (Json::Value& elem) const elem[jss::value] = getText (); elem[jss::currency] = getHumanCurrency (); - elem[jss::issuer] = RippleAddress::createHumanAccountID (mIssuer); + elem[jss::issuer] = to_string (mIssuer); } else { @@ -1198,17 +1123,17 @@ public: bool roundTest (int n, int d, int m) { // check STAmount rounding - STAmount num (CURRENCY_ONE, ACCOUNT_ONE, n); - STAmount den (CURRENCY_ONE, ACCOUNT_ONE, d); - STAmount mul (CURRENCY_ONE, ACCOUNT_ONE, m); - STAmount quot = STAmount::divide (n, d, CURRENCY_ONE, ACCOUNT_ONE); - STAmount res = STAmount::multiply (quot, mul, CURRENCY_ONE, ACCOUNT_ONE); + STAmount num (noCurrency(), noAccount(), n); + STAmount den (noCurrency(), noAccount(), d); + STAmount mul (noCurrency(), noAccount(), m); + STAmount quot = STAmount::divide (n, d, noCurrency(), noAccount()); + STAmount res = STAmount::multiply (quot, mul, noCurrency(), noAccount()); expect (! res.isNative (), "Product should not be native"); res.roundSelf (); - STAmount cmp (CURRENCY_ONE, ACCOUNT_ONE, (n * m) / d); + STAmount cmp (noCurrency(), noAccount(), (n * m) / d); expect (! cmp.isNative (), "Comparison amount should not be native"); @@ -1233,13 +1158,13 @@ public: void mulTest (int a, int b) { - STAmount aa (CURRENCY_ONE, ACCOUNT_ONE, a); - STAmount bb (CURRENCY_ONE, ACCOUNT_ONE, b); - STAmount prod1 (STAmount::multiply (aa, bb, CURRENCY_ONE, ACCOUNT_ONE)); + STAmount aa (noCurrency(), noAccount(), a); + STAmount bb (noCurrency(), noAccount(), b); + STAmount prod1 (STAmount::multiply (aa, bb, noCurrency(), noAccount())); expect (! prod1.isNative ()); - STAmount prod2 (CURRENCY_ONE, ACCOUNT_ONE, static_cast (a) * static_cast (b)); + STAmount prod2 (noCurrency(), noAccount(), static_cast (a) * static_cast (b)); if (prod1 != prod2) { @@ -1254,7 +1179,7 @@ public: } aa = a; - prod1 = STAmount::multiply (aa, bb, CURRENCY_ONE, ACCOUNT_ONE); + prod1 = STAmount::multiply (aa, bb, noCurrency(), noAccount()); if (prod1 != prod2) { @@ -1431,16 +1356,16 @@ public: unexpected (STAmount (310).getText () != "310", "STAmount fail"); - unexpected (STAmount::createHumanCurrency (uint160 ()) != "XRP", "cHC(XRP)"); + unexpected (to_string (Currency ()) != "XRP", "cHC(XRP)"); - uint160 c; - unexpected (!STAmount::currencyFromString (c, "USD"), "create USD currency"); - unexpected (STAmount::createHumanCurrency (c) != "USD", "check USD currency"); + Currency c; + unexpected (!to_currency (c, "USD"), "create USD currency"); + unexpected (to_string (c) != "USD", "check USD currency"); const std::string cur = "015841551A748AD2C1F76FF6ECB0CCCD00000000"; - unexpected (!STAmount::currencyFromString (c, cur), "create custom currency"); - unexpected (STAmount::createHumanCurrency (c) != cur, "check custom currency"); - unexpected (c != uint160 (cur), "check custom currency"); + unexpected (!to_currency (c, cur), "create custom currency"); + unexpected (to_string (c) != cur, "check custom currency"); + unexpected (c != Currency (cur), "check custom currency"); } //-------------------------------------------------------------------------- @@ -1449,7 +1374,7 @@ public: { testcase ("custom currency"); - STAmount zeroSt (CURRENCY_ONE, ACCOUNT_ONE), one (CURRENCY_ONE, ACCOUNT_ONE, 1), hundred (CURRENCY_ONE, ACCOUNT_ONE, 100); + STAmount zeroSt (noCurrency(), noAccount()), one (noCurrency(), noAccount(), 1), hundred (noCurrency(), noAccount(), 100); unexpected (serializeAndDeserialize (zeroSt) != zeroSt, "STAmount fail"); @@ -1575,33 +1500,33 @@ public: unexpected ((hundred != hundred), "STAmount fail"); - unexpected (STAmount (CURRENCY_ONE, ACCOUNT_ONE).getText () != "0", "STAmount fail"); + unexpected (STAmount (noCurrency(), noAccount()).getText () != "0", "STAmount fail"); - unexpected (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 31).getText () != "31", "STAmount fail"); + unexpected (STAmount (noCurrency(), noAccount(), 31).getText () != "31", "STAmount fail"); - unexpected (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 31, 1).getText () != "310", "STAmount fail"); + unexpected (STAmount (noCurrency(), noAccount(), 31, 1).getText () != "310", "STAmount fail"); - unexpected (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 31, -1).getText () != "3.1", "STAmount fail"); + unexpected (STAmount (noCurrency(), noAccount(), 31, -1).getText () != "3.1", "STAmount fail"); - unexpected (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 31, -2).getText () != "0.31", "STAmount fail"); + unexpected (STAmount (noCurrency(), noAccount(), 31, -2).getText () != "0.31", "STAmount fail"); - unexpected (STAmount::multiply (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 20), STAmount (3), CURRENCY_ONE, ACCOUNT_ONE).getText () != "60", + unexpected (STAmount::multiply (STAmount (noCurrency(), noAccount(), 20), STAmount (3), noCurrency(), noAccount()).getText () != "60", "STAmount multiply fail 1"); - unexpected (STAmount::multiply (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 20), STAmount (3), uint160 (), ACCOUNT_XRP).getText () != "60", + unexpected (STAmount::multiply (STAmount (noCurrency(), noAccount(), 20), STAmount (3), xrpCurrency (), xrpIssuer()).getText () != "60", "STAmount multiply fail 2"); - unexpected (STAmount::multiply (STAmount (20), STAmount (3), CURRENCY_ONE, ACCOUNT_ONE).getText () != "60", + unexpected (STAmount::multiply (STAmount (20), STAmount (3), noCurrency(), noAccount()).getText () != "60", "STAmount multiply fail 3"); - unexpected (STAmount::multiply (STAmount (20), STAmount (3), uint160 (), ACCOUNT_XRP).getText () != "60", + unexpected (STAmount::multiply (STAmount (20), STAmount (3), xrpCurrency (), xrpIssuer()).getText () != "60", "STAmount multiply fail 4"); - if (STAmount::divide (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 60), STAmount (3), CURRENCY_ONE, ACCOUNT_ONE).getText () != "20") + if (STAmount::divide (STAmount (noCurrency(), noAccount(), 60), STAmount (3), noCurrency(), noAccount()).getText () != "20") { WriteLog (lsFATAL, STAmount) << "60/3 = " << - STAmount::divide (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 60), - STAmount (3), CURRENCY_ONE, ACCOUNT_ONE).getText (); + STAmount::divide (STAmount (noCurrency(), noAccount(), 60), + STAmount (3), noCurrency(), noAccount()).getText (); fail ("STAmount divide fail"); } else @@ -1609,21 +1534,21 @@ public: pass (); } - unexpected (STAmount::divide (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 60), STAmount (3), uint160 (), ACCOUNT_XRP).getText () != "20", + unexpected (STAmount::divide (STAmount (noCurrency(), noAccount(), 60), STAmount (3), xrpCurrency (), xrpIssuer()).getText () != "20", "STAmount divide fail"); - unexpected (STAmount::divide (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 60), STAmount (CURRENCY_ONE, ACCOUNT_ONE, 3), CURRENCY_ONE, ACCOUNT_ONE).getText () != "20", + unexpected (STAmount::divide (STAmount (noCurrency(), noAccount(), 60), STAmount (noCurrency(), noAccount(), 3), noCurrency(), noAccount()).getText () != "20", "STAmount divide fail"); - unexpected (STAmount::divide (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 60), STAmount (CURRENCY_ONE, ACCOUNT_ONE, 3), uint160 (), ACCOUNT_XRP).getText () != "20", + unexpected (STAmount::divide (STAmount (noCurrency(), noAccount(), 60), STAmount (noCurrency(), noAccount(), 3), xrpCurrency (), xrpIssuer()).getText () != "20", "STAmount divide fail"); - STAmount a1 (CURRENCY_ONE, ACCOUNT_ONE, 60), a2 (CURRENCY_ONE, ACCOUNT_ONE, 10, -1); + STAmount a1 (noCurrency(), noAccount(), 60), a2 (noCurrency(), noAccount(), 10, -1); - unexpected (STAmount::divide (a2, a1, CURRENCY_ONE, ACCOUNT_ONE) != STAmount::setRate (STAmount::getRate (a1, a2)), + unexpected (STAmount::divide (a2, a1, noCurrency(), noAccount()) != STAmount::setRate (STAmount::getRate (a1, a2)), "STAmount setRate(getRate) fail"); - unexpected (STAmount::divide (a1, a2, CURRENCY_ONE, ACCOUNT_ONE) != STAmount::setRate (STAmount::getRate (a2, a1)), + unexpected (STAmount::divide (a1, a2, noCurrency(), noAccount()) != STAmount::setRate (STAmount::getRate (a2, a1)), "STAmount setRate(getRate) fail"); } @@ -1662,22 +1587,22 @@ public: unexpected (STAmount::getRate (STAmount (10), STAmount (1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 2"); - unexpected (STAmount::getRate (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 1), STAmount (CURRENCY_ONE, ACCOUNT_ONE, 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + unexpected (STAmount::getRate (STAmount (noCurrency(), noAccount(), 1), STAmount (noCurrency(), noAccount(), 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 3"); - unexpected (STAmount::getRate (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 10), STAmount (CURRENCY_ONE, ACCOUNT_ONE, 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + unexpected (STAmount::getRate (STAmount (noCurrency(), noAccount(), 10), STAmount (noCurrency(), noAccount(), 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 4"); - unexpected (STAmount::getRate (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 1), STAmount (10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + unexpected (STAmount::getRate (STAmount (noCurrency(), noAccount(), 1), STAmount (10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 5"); - unexpected (STAmount::getRate (STAmount (CURRENCY_ONE, ACCOUNT_ONE, 10), STAmount (1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + unexpected (STAmount::getRate (STAmount (noCurrency(), noAccount(), 10), STAmount (1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 6"); - unexpected (STAmount::getRate (STAmount (1), STAmount (CURRENCY_ONE, ACCOUNT_ONE, 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), + unexpected (STAmount::getRate (STAmount (1), STAmount (noCurrency(), noAccount(), 10)) != (((100ull - 14) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 7"); - unexpected (STAmount::getRate (STAmount (10), STAmount (CURRENCY_ONE, ACCOUNT_ONE, 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), + unexpected (STAmount::getRate (STAmount (10), STAmount (noCurrency(), noAccount(), 1)) != (((100ull - 16) << (64 - 8)) | 1000000000000000ull), "STAmount getRate fail 8"); roundTest (1, 3, 3); @@ -1712,29 +1637,29 @@ public: testcase ("underflow"); STAmount bigNative (STAmount::cMaxNative / 2); - STAmount bigValue (CURRENCY_ONE, ACCOUNT_ONE, + STAmount bigValue (noCurrency(), noAccount(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMaxOffset - 1); - STAmount smallValue (CURRENCY_ONE, ACCOUNT_ONE, + STAmount smallValue (noCurrency(), noAccount(), (STAmount::cMinValue + STAmount::cMaxValue) / 2, STAmount::cMinOffset + 1); - STAmount zeroSt (CURRENCY_ONE, ACCOUNT_ONE, 0); + STAmount zeroSt (noCurrency(), noAccount(), 0); - STAmount smallXsmall = STAmount::multiply (smallValue, smallValue, CURRENCY_ONE, ACCOUNT_ONE); + STAmount smallXsmall = STAmount::multiply (smallValue, smallValue, noCurrency(), noAccount()); expect (smallXsmall == zero, "smallXsmall != 0"); - STAmount bigDsmall = STAmount::divide (smallValue, bigValue, CURRENCY_ONE, ACCOUNT_ONE); + STAmount bigDsmall = STAmount::divide (smallValue, bigValue, noCurrency(), noAccount()); expect (bigDsmall == zero, beast::String ("small/big != 0: ") + bigDsmall.getText ()); - bigDsmall = STAmount::divide (smallValue, bigNative, CURRENCY_ONE, uint160 ()); + bigDsmall = STAmount::divide (smallValue, bigNative, noCurrency(), xrpIssuer ()); expect (bigDsmall == zero, beast::String ("small/bigNative != 0: ") + bigDsmall.getText ()); - bigDsmall = STAmount::divide (smallValue, bigValue, uint160 (), uint160 ()); + bigDsmall = STAmount::divide (smallValue, bigValue, xrpCurrency (), xrpIssuer ()); expect (bigDsmall == zero, beast::String ("(small/big)->N != 0: ") + bigDsmall.getText ()); - bigDsmall = STAmount::divide (smallValue, bigNative, uint160 (), uint160 ()); + bigDsmall = STAmount::divide (smallValue, bigNative, xrpCurrency (), xrpIssuer ()); expect (bigDsmall == zero, beast::String ("(small/bigNative)->N != 0: ") + bigDsmall.getText ()); @@ -1763,27 +1688,27 @@ public: int offset = -14; STAmount::canonicalizeRound (false, value, offset, true); - STAmount one (CURRENCY_ONE, ACCOUNT_ONE, 1); - STAmount two (CURRENCY_ONE, ACCOUNT_ONE, 2); - STAmount three (CURRENCY_ONE, ACCOUNT_ONE, 3); + STAmount one (noCurrency(), noAccount(), 1); + STAmount two (noCurrency(), noAccount(), 2); + STAmount three (noCurrency(), noAccount(), 3); - STAmount oneThird1 = STAmount::divRound (one, three, CURRENCY_ONE, ACCOUNT_ONE, false); - STAmount oneThird2 = STAmount::divide (one, three, CURRENCY_ONE, ACCOUNT_ONE); - STAmount oneThird3 = STAmount::divRound (one, three, CURRENCY_ONE, ACCOUNT_ONE, true); + STAmount oneThird1 = STAmount::divRound (one, three, noCurrency(), noAccount(), false); + STAmount oneThird2 = STAmount::divide (one, three, noCurrency(), noAccount()); + STAmount oneThird3 = STAmount::divRound (one, three, noCurrency(), noAccount(), true); WriteLog (lsINFO, STAmount) << oneThird1; WriteLog (lsINFO, STAmount) << oneThird2; WriteLog (lsINFO, STAmount) << oneThird3; - STAmount twoThird1 = STAmount::divRound (two, three, CURRENCY_ONE, ACCOUNT_ONE, false); - STAmount twoThird2 = STAmount::divide (two, three, CURRENCY_ONE, ACCOUNT_ONE); - STAmount twoThird3 = STAmount::divRound (two, three, CURRENCY_ONE, ACCOUNT_ONE, true); + STAmount twoThird1 = STAmount::divRound (two, three, noCurrency(), noAccount(), false); + STAmount twoThird2 = STAmount::divide (two, three, noCurrency(), noAccount()); + STAmount twoThird3 = STAmount::divRound (two, three, noCurrency(), noAccount(), true); WriteLog (lsINFO, STAmount) << twoThird1; WriteLog (lsINFO, STAmount) << twoThird2; WriteLog (lsINFO, STAmount) << twoThird3; - STAmount oneA = STAmount::mulRound (oneThird1, three, CURRENCY_ONE, ACCOUNT_ONE, false); - STAmount oneB = STAmount::multiply (oneThird2, three, CURRENCY_ONE, ACCOUNT_ONE); - STAmount oneC = STAmount::mulRound (oneThird3, three, CURRENCY_ONE, ACCOUNT_ONE, true); + STAmount oneA = STAmount::mulRound (oneThird1, three, noCurrency(), noAccount(), false); + STAmount oneB = STAmount::multiply (oneThird2, three, noCurrency(), noAccount()); + STAmount oneC = STAmount::mulRound (oneThird3, three, noCurrency(), noAccount(), true); WriteLog (lsINFO, STAmount) << oneA; WriteLog (lsINFO, STAmount) << oneB; WriteLog (lsINFO, STAmount) << oneC; @@ -1795,9 +1720,9 @@ public: WriteLog (lsINFO, STAmount) << fourThirdsB; WriteLog (lsINFO, STAmount) << fourThirdsC; - STAmount dripTest1 = STAmount::mulRound (twoThird2, two, uint160 (), uint160 (), false); - STAmount dripTest2 = STAmount::multiply (twoThird2, two, uint160 (), uint160 ()); - STAmount dripTest3 = STAmount::mulRound (twoThird2, two, uint160 (), uint160 (), true); + STAmount dripTest1 = STAmount::mulRound (twoThird2, two, xrpCurrency (), xrpIssuer (), false); + STAmount dripTest2 = STAmount::multiply (twoThird2, two, xrpCurrency (), xrpIssuer ()); + STAmount dripTest3 = STAmount::mulRound (twoThird2, two, xrpCurrency (), xrpIssuer (), true); WriteLog (lsINFO, STAmount) << dripTest1; WriteLog (lsINFO, STAmount) << dripTest2; WriteLog (lsINFO, STAmount) << dripTest3; diff --git a/src/ripple/module/data/protocol/STAmountRound.cpp b/src/ripple/module/data/protocol/STAmountRound.cpp index 470a8a5eb7..27cc79102b 100644 --- a/src/ripple/module/data/protocol/STAmountRound.cpp +++ b/src/ripple/module/data/protocol/STAmountRound.cpp @@ -19,12 +19,15 @@ namespace ripple { -void STAmount::canonicalizeRound (bool isNative, std::uint64_t& value, int& offset, bool roundUp) +void STAmount::canonicalizeRound ( + bool isNative, std::uint64_t& value, int& offset, bool roundUp) { if (!roundUp) // canonicalize already rounds down return; - WriteLog (lsTRACE, STAmount) << "canonicalize< " << value << ":" << offset << (roundUp ? " up" : " down"); + WriteLog (lsTRACE, STAmount) + << "canonicalize< " << value + << ":" << offset << (roundUp ? " up" : " down"); if (isNative) { @@ -57,7 +60,9 @@ void STAmount::canonicalizeRound (bool isNative, std::uint64_t& value, int& offs ++offset; } - WriteLog (lsTRACE, STAmount) << "canonicalize> " << value << ":" << offset << (roundUp ? " up" : " down"); + WriteLog (lsTRACE, STAmount) + << "canonicalize> " << value + << ":" << offset << (roundUp ? " up" : " down"); } STAmount STAmount::addRound (const STAmount& v1, const STAmount& v2, bool roundUp) @@ -68,13 +73,15 @@ STAmount STAmount::addRound (const STAmount& v1, const STAmount& v2, bool roundU return v1; if (v1.mValue == 0) - return STAmount (v1.getFName (), v1.mCurrency, v1.mIssuer, v2.mValue, v2.mOffset, v2.mIsNegative); + return STAmount (v1.getFName (), v1.mCurrency, v1.mIssuer, v2.mValue, + v2.mOffset, v2.mIsNegative); if (v1.mIsNative) return STAmount (v1.getFName (), v1.getSNValue () + v2.getSNValue ()); int ov1 = v1.mOffset, ov2 = v2.mOffset; - std::int64_t vv1 = static_cast (v1.mValue), vv2 = static_cast (v2.mValue); + auto vv1 = static_cast (v1.mValue); + auto vv2 = static_cast (v2.mValue); if (v1.mIsNegative) vv1 = -vv1; @@ -138,13 +145,15 @@ STAmount STAmount::subRound (const STAmount& v1, const STAmount& v2, bool roundU return v1; if (v1.mValue == 0) - return STAmount (v1.getFName (), v1.mCurrency, v1.mIssuer, v2.mValue, v2.mOffset, !v2.mIsNegative); + return STAmount (v1.getFName (), v1.mCurrency, v1.mIssuer, v2.mValue, + v2.mOffset, !v2.mIsNegative); if (v1.mIsNative) return STAmount (v1.getFName (), v1.getSNValue () - v2.getSNValue ()); int ov1 = v1.mOffset, ov2 = v2.mOffset; - std::int64_t vv1 = static_cast (v1.mValue), vv2 = static_cast (v2.mValue); + auto vv1 = static_cast (v1.mValue); + auto vv2 = static_cast (v2.mValue); if (v1.mIsNegative) vv1 = -vv1; @@ -186,7 +195,8 @@ STAmount STAmount::subRound (const STAmount& v1, const STAmount& v2, bool roundU if ((fv >= -10) && (fv <= 10)) return STAmount (v1.getFName (), v1.mCurrency, v1.mIssuer); - else if (fv >= 0) + + if (fv >= 0) { std::uint64_t v = static_cast (fv); canonicalizeRound (false, v, ov1, roundUp); @@ -201,16 +211,18 @@ STAmount STAmount::subRound (const STAmount& v1, const STAmount& v2, bool roundU } STAmount STAmount::mulRound ( - const STAmount& v1, const STAmount& v2, const uint160& currency, - const uint160& issuer, bool roundUp) + const STAmount& v1, const STAmount& v2, Currency const& currency, + Account const& issuer, bool roundUp) { if (v1 == zero || v2 == zero) return STAmount (currency, issuer); if (v1.mIsNative && v2.mIsNative && currency.isZero ()) { - std::uint64_t minV = (v1.getSNValue () < v2.getSNValue ()) ? v1.getSNValue () : v2.getSNValue (); - std::uint64_t maxV = (v1.getSNValue () < v2.getSNValue ()) ? v2.getSNValue () : v1.getSNValue (); + std::uint64_t minV = (v1.getSNValue () < v2.getSNValue ()) ? + v1.getSNValue () : v2.getSNValue (); + std::uint64_t maxV = (v1.getSNValue () < v2.getSNValue ()) ? + v2.getSNValue () : v1.getSNValue (); if (minV > 3000000000ull) // sqrt(cMaxNative) throw std::runtime_error ("Native value overflow"); @@ -261,13 +273,14 @@ STAmount STAmount::mulRound ( std::uint64_t amount = v.getuint64 (); int offset = offset1 + offset2 + 14; - canonicalizeRound (currency.isZero (), amount, offset, resultNegative != roundUp); + canonicalizeRound ( + currency.isZero (), amount, offset, resultNegative != roundUp); return STAmount (currency, issuer, amount, offset, resultNegative); } STAmount STAmount::divRound ( const STAmount& num, const STAmount& den, - const uint160& currency, const uint160& issuer, bool roundUp) + Currency const& currency, Account const& issuer, bool roundUp) { if (den == zero) throw std::runtime_error ("division by zero"); @@ -311,7 +324,8 @@ STAmount STAmount::divRound ( std::uint64_t amount = v.getuint64 (); int offset = numOffset - denOffset - 17; - canonicalizeRound (currency.isZero (), amount, offset, resultNegative != roundUp); + canonicalizeRound ( + currency.isZero (), amount, offset, resultNegative != roundUp); return STAmount (currency, issuer, amount, offset, resultNegative); } diff --git a/src/ripple/module/data/protocol/STParsedJSON.cpp b/src/ripple/module/data/protocol/STParsedJSON.cpp index b07d187512..7c68c78acb 100644 --- a/src/ripple/module/data/protocol/STParsedJSON.cpp +++ b/src/ripple/module/data/protocol/STParsedJSON.cpp @@ -421,7 +421,7 @@ bool STParsedJSON::parse (std::string const& json_name, error = array_expected (json_name, fieldName); return false; } - + try { data.push_back (new STVector256 (field)); @@ -490,7 +490,8 @@ bool STParsedJSON::parse (std::string const& json_name, const Json::Value& currency = pathEl["currency"]; const Json::Value& issuer = pathEl["issuer"]; bool hasCurrency = false; - uint160 uAccount, uCurrency, uIssuer; + Account uAccount, uIssuer; + Currency uCurrency; if (! account.isNull ()) { @@ -534,8 +535,7 @@ bool STParsedJSON::parse (std::string const& json_name, { uCurrency.SetHex (currency.asString ()); } - else if (!STAmount::currencyFromString ( - uCurrency, currency.asString ())) + else if (!to_currency (uCurrency, currency.asString ())) { error = invalid_data (element_name, "currency"); return false; @@ -597,9 +597,9 @@ bool STParsedJSON::parse (std::string const& json_name, { if (value.size () == 40) // 160-bit hex account value { - uint160 v; - v.SetHex (strValue); - data.push_back (new STAccount (field, v)); + Account account; + account.SetHex (strValue); + data.push_back (new STAccount (field, account)); } else { diff --git a/src/ripple/module/data/protocol/SerializedObject.cpp b/src/ripple/module/data/protocol/SerializedObject.cpp index ca131150c4..ea0d1fb123 100644 --- a/src/ripple/module/data/protocol/SerializedObject.cpp +++ b/src/ripple/module/data/protocol/SerializedObject.cpp @@ -771,27 +771,24 @@ RippleAddress STObject::getFieldAccount (SField::ref field) const return cf->getValueNCA (); } -uint160 STObject::getFieldAccount160 (SField::ref field) const +Account STObject::getFieldAccount160 (SField::ref field) const { - uint160 a; - const SerializedType* rf = peekAtPField (field); - + auto rf = peekAtPField (field); if (!rf) throw std::runtime_error ("Field not found"); - SerializedTypeID id = rf->getSType (); - - if (id != STI_NOTPRESENT) + Account account; + if (rf->getSType () != STI_NOTPRESENT) { const STAccount* cf = dynamic_cast (rf); if (!cf) throw std::runtime_error ("Wrong field type"); - cf->getValueH160 (a); + cf->getValueH160 (account); } - return a; + return account; } Blob STObject::getFieldVL (SField::ref field) const @@ -962,21 +959,6 @@ void STObject::setFieldH128 (SField::ref field, const uint128& v) cf->setValue (v); } -void STObject::setFieldH160 (SField::ref field, const uint160& v) -{ - SerializedType* rf = getPField (field, true); - - if (!rf) throw std::runtime_error ("Field not found"); - - if (rf->getSType () == STI_NOTPRESENT) rf = makeFieldPresent (field); - - STHash160* cf = dynamic_cast (rf); - - if (!cf) throw std::runtime_error ("Wrong field type"); - - cf->setValue (v); -} - void STObject::setFieldH256 (SField::ref field, uint256 const& v) { SerializedType* rf = getPField (field, true); @@ -1007,17 +989,20 @@ void STObject::setFieldV256 (SField::ref field, const STVector256& v) cf->setValue (v); } -void STObject::setFieldAccount (SField::ref field, const uint160& v) +void STObject::setFieldAccount (SField::ref field, Account const& v) { SerializedType* rf = getPField (field, true); - if (!rf) throw std::runtime_error ("Field not found"); + if (!rf) + throw std::runtime_error ("Field not found"); - if (rf->getSType () == STI_NOTPRESENT) rf = makeFieldPresent (field); + if (rf->getSType () == STI_NOTPRESENT) + rf = makeFieldPresent (field); STAccount* cf = dynamic_cast (rf); - if (!cf) throw std::runtime_error ("Wrong field type"); + if (!cf) + throw std::runtime_error ("Wrong field type"); cf->setValueH160 (v); } @@ -1070,15 +1055,17 @@ void STObject::setFieldPathSet (SField::ref field, const STPathSet& v) Json::Value STObject::getJson (int options) const { Json::Value ret (Json::objectValue); + + // TODO(tom): this variable is never changed...? int index = 1; - BOOST_FOREACH (const SerializedType & it, mData) + for (auto const& it: mData) { if (it.getSType () != STI_NOTPRESENT) { - if (!it.getFName ().hasName ()) - ret[beast::lexicalCast (index)] = it.getJson (options); - else - ret[it.getJsonName ()] = it.getJson (options); + auto const& n = it.getFName (); + auto key = n.hasName () ? std::string(n.getJsonName ()) : + std::to_string (index); + ret[key] = it.getJson (options); } } return ret; @@ -1178,17 +1165,14 @@ Json::Value STArray::getJson (int p) const { Json::Value v = Json::arrayValue; int index = 1; - BOOST_FOREACH (const STObject & object, value) + for (auto const& object: value) { if (object.getSType () != STI_NOTPRESENT) { Json::Value inner = Json::objectValue; - - if (!object.getFName ().hasName ()) - inner[beast::lexicalCast (index)] = object.getJson (p); - else - inner[object.getName ()] = object.getJson (p); - + auto const& fname = object.getFName (); + auto k = fname.hasName () ? fname.fieldName : std::to_string(index); + inner[k] = object.getJson (p); v.append (inner); index++; } diff --git a/src/ripple/module/data/protocol/SerializedObject.h b/src/ripple/module/data/protocol/SerializedObject.h index c6d6c043c3..9642a1a91a 100644 --- a/src/ripple/module/data/protocol/SerializedObject.h +++ b/src/ripple/module/data/protocol/SerializedObject.h @@ -107,6 +107,8 @@ public: std::string getFullText () const; std::string getText () const; + + // TODO(tom): options should be an enum. virtual Json::Value getJson (int options) const; int addObject (const SerializedType & t) @@ -195,10 +197,12 @@ public: std::uint32_t getFieldU32 (SField::ref field) const; std::uint64_t getFieldU64 (SField::ref field) const; uint128 getFieldH128 (SField::ref field) const; + uint160 getFieldH160 (SField::ref field) const; uint256 getFieldH256 (SField::ref field) const; RippleAddress getFieldAccount (SField::ref field) const; - uint160 getFieldAccount160 (SField::ref field) const; + Account getFieldAccount160 (SField::ref field) const; + Blob getFieldVL (SField::ref field) const; const STAmount& getFieldAmount (SField::ref field) const; const STPathSet& getFieldPathSet (SField::ref field) const; @@ -210,10 +214,9 @@ public: void setFieldU32 (SField::ref field, std::uint32_t); void setFieldU64 (SField::ref field, std::uint64_t); void setFieldH128 (SField::ref field, const uint128&); - void setFieldH160 (SField::ref field, const uint160&); void setFieldH256 (SField::ref field, uint256 const& ); void setFieldVL (SField::ref field, Blob const&); - void setFieldAccount (SField::ref field, const uint160&); + void setFieldAccount (SField::ref field, Account const&); void setFieldAccount (SField::ref field, const RippleAddress & addr) { setFieldAccount (field, addr.getAccountID ()); @@ -222,6 +225,23 @@ public: void setFieldPathSet (SField::ref field, const STPathSet&); void setFieldV256 (SField::ref field, const STVector256 & v); + template + void setFieldH160 (SField::ref field, base_uint<160, Tag> const& v) + { + SerializedType* rf = getPField (field, true); + + if (!rf) + throw std::runtime_error ("Field not found"); + + if (rf->getSType () == STI_NOTPRESENT) + rf = makeFieldPresent (field); + + if (auto cf = dynamic_cast (rf)) + cf->setValue (v); + else + throw std::runtime_error ("Wrong field type"); + } + STObject& peekFieldObject (SField::ref field); bool isFieldPresent (SField::ref field) const; @@ -479,7 +499,8 @@ public: virtual std::string getFullText () const; virtual std::string getText () const; - virtual Json::Value getJson (int) const; + + virtual Json::Value getJson (int index) const; virtual void add (Serializer & s) const; void sort (bool (*compare) (const STObject & o1, const STObject & o2)); diff --git a/src/ripple/module/data/protocol/SerializedTypes.cpp b/src/ripple/module/data/protocol/SerializedTypes.cpp index d550309a39..cec276c39f 100644 --- a/src/ripple/module/data/protocol/SerializedTypes.cpp +++ b/src/ripple/module/data/protocol/SerializedTypes.cpp @@ -19,8 +19,8 @@ namespace ripple { -const STAmount saZero (CURRENCY_ONE, ACCOUNT_ONE, 0); -const STAmount saOne (CURRENCY_ONE, ACCOUNT_ONE, 1); +const STAmount saZero (noCurrency(), noAccount(), 0); +const STAmount saOne (noCurrency(), noAccount(), 1); SerializedType& SerializedType::operator= (const SerializedType& t) { @@ -271,7 +271,7 @@ bool STVariableLength::isEquivalent (const SerializedType& t) const std::string STAccount::getText () const { - uint160 u; + Account u; RippleAddress a; if (!getValueH160 (u)) @@ -341,7 +341,7 @@ bool STVector256::hasValue (uint256 const& v) const // STAccount // -STAccount::STAccount (SField::ref n, const uint160& v) : STVariableLength (n) +STAccount::STAccount (SField::ref n, Account const& v) : STVariableLength (n) { peekValue ().insert (peekValue ().end (), v.begin (), v.end ()); } @@ -351,28 +351,13 @@ bool STAccount::isValueH160 () const return peekValue ().size () == (160 / 8); } -void STAccount::setValueH160 (const uint160& v) -{ - peekValue ().clear (); - peekValue ().insert (peekValue ().end (), v.begin (), v.end ()); - assert (peekValue ().size () == (160 / 8)); -} - -bool STAccount::getValueH160 (uint160& v) const -{ - if (!isValueH160 ()) return false; - - memcpy (v.begin (), & (peekValue ().front ()), (160 / 8)); - return true; -} - RippleAddress STAccount::getValueNCA () const { RippleAddress a; - uint160 v; + Account account; - if (getValueH160 (v)) - a.setAccountID (v); + if (getValueH160 (account)) + a.setAccountID (account); return a; } @@ -391,7 +376,8 @@ STPathSet* STPathSet::construct (SerializerIterator& s, SField::ref name) { int iType = s.get8 (); - if (iType == STPathElement::typeNone || iType == STPathElement::typeBoundary) + if (iType == STPathElement::typeNone || + iType == STPathElement::typeBoundary) { if (path.empty ()) { @@ -410,30 +396,31 @@ STPathSet* STPathSet::construct (SerializerIterator& s, SField::ref name) } else if (iType & ~STPathElement::typeAll) { - WriteLog (lsINFO, SerializedType) << "STPathSet: Bad path element: " << iType; + WriteLog (lsINFO, SerializedType) + << "STPathSet: Bad path element: " << iType; throw std::runtime_error ("bad path element"); } else { - const bool bAccount = !! (iType & STPathElement::typeAccount); - const bool bCurrency = !! (iType & STPathElement::typeCurrency); - const bool bIssuer = !! (iType & STPathElement::typeIssuer); + auto hasAccount = iType & STPathElement::typeAccount; + auto hasCurrency = iType & STPathElement::typeCurrency; + auto hasIssuer = iType & STPathElement::typeIssuer; - uint160 account; - uint160 uCurrency; - uint160 issuer; + Account account; + Currency currency; + Account issuer; - if (bAccount) - account = s.get160 (); + if (hasAccount) + account.copyFrom (s.get160 ()); - if (bCurrency) - uCurrency = s.get160 (); + if (hasCurrency) + currency.copyFrom (s.get160 ()); - if (bIssuer) - issuer = s.get160 (); + if (hasIssuer) + issuer.copyFrom (s.get160 ()); - path.push_back (STPathElement (account, uCurrency, issuer, bCurrency)); + path.emplace_back (account, currency, issuer, hasCurrency); } } while (1); @@ -446,16 +433,14 @@ bool STPathSet::isEquivalent (const SerializedType& t) const } bool STPath::hasSeen ( - const uint160& uAccountId, const uint160& currency, - const uint160& issuer) const + Account const& account, Currency const& currency, + Account const& issuer) const { - for (int i = 0; i < mPath.size (); ++i) + for (auto& p: mPath) { - const STPathElement& ele = getElement (i); - - if (ele.getAccountID () == uAccountId - && ele.getCurrency () == currency - && ele.getIssuerID () == issuer) + if (p.getAccountID () == account + && p.getCurrency () == currency + && p.getIssuerID () == issuer) return true; } @@ -466,7 +451,7 @@ Json::Value STPath::getJson (int) const { Json::Value ret (Json::arrayValue); - BOOST_FOREACH (std::vector::const_iterator::value_type it, mPath) + for (auto it: mPath) { Json::Value elem (Json::objectValue); int iType = it.getNodeType (); @@ -475,13 +460,13 @@ Json::Value STPath::getJson (int) const elem[jss::type_hex] = strHex (iType); if (iType & STPathElement::typeAccount) - elem[jss::account] = RippleAddress::createHumanAccountID (it.getAccountID ()); + elem[jss::account] = to_string (it.getAccountID ()); if (iType & STPathElement::typeCurrency) - elem[jss::currency] = STAmount::createHumanCurrency (it.getCurrency ()); + elem[jss::currency] = to_string (it.getCurrency ()); if (iType & STPathElement::typeIssuer) - elem[jss::issuer] = RippleAddress::createHumanAccountID (it.getIssuerID ()); + elem[jss::issuer] = to_string (it.getIssuerID ()); ret.append (elem); } @@ -492,9 +477,8 @@ Json::Value STPath::getJson (int) const Json::Value STPathSet::getJson (int options) const { Json::Value ret (Json::arrayValue); - - BOOST_FOREACH (std::vector::const_iterator::value_type it, value) - ret.append (it.getJson (options)); + for (auto it: value) + ret.append (it.getJson (options)); return ret; } @@ -513,7 +497,7 @@ std::string STPath::getText () const { case STPathElement::typeAccount: { - ret += RippleAddress::createHumanAccountID (it.getNode ()); + ret += to_string (it.getNode ()); break; } diff --git a/src/ripple/module/data/protocol/SerializedTypes.h b/src/ripple/module/data/protocol/SerializedTypes.h index d4407619cf..18dea8df15 100644 --- a/src/ripple/module/data/protocol/SerializedTypes.h +++ b/src/ripple/module/data/protocol/SerializedTypes.h @@ -20,17 +20,21 @@ #ifndef RIPPLE_SERIALIZEDTYPES_H #define RIPPLE_SERIALIZEDTYPES_H +#include +#include + namespace ripple { // VFALCO TODO fix this restriction on copy assignment. // -// CAUTION: Do not create a vector (or similar container) of any object derived from -// SerializedType. Use Boost ptr_* containers. The copy assignment operator of -// SerializedType has semantics that will cause contained types to change their names -// when an object is deleted because copy assignment is used to "slide down" the -// remaining types and this will not copy the field name. Changing the copy assignment -// operator to copy the field name breaks the use of copy assignment just to copy values, -// which is used in the transaction engine code. +// CAUTION: Do not create a vector (or similar container) of any object derived +// from SerializedType. Use Boost ptr_* containers. The copy assignment operator +// of SerializedType has semantics that will cause contained types to change +// their names when an object is deleted because copy assignment is used to +// "slide down" the remaining types and this will not copy the field +// name. Changing the copy assignment operator to copy the field name breaks the +// use of copy assignment just to copy values, which is used in the transaction +// engine code. // VFALCO TODO Remove this unused enum /* @@ -49,24 +53,6 @@ enum PathFlags }; */ -// VFALCO TODO make these non static or otherwise clean constants. -static const uint160 u160_zero (0), u160_one (1); -static inline const uint160& get_u160_zero () -{ - return u160_zero; -} -static inline const uint160& get_u160_one () -{ - return u160_one; -} - -// VFALCO TODO replace these with language constructs -#define CURRENCY_XRP get_u160_zero() -#define CURRENCY_ONE get_u160_one() // Used as a place holder. -#define CURRENCY_BAD uint160(0x5852500000000000) // Do not allow XRP as an IOU currency. -#define ACCOUNT_XRP get_u160_zero() -#define ACCOUNT_ONE get_u160_one() // Used as a place holder. - //------------------------------------------------------------------------------ /** A type which can be exported to a well known binary format. @@ -116,15 +102,6 @@ public: { return *fName; } - std::string getName () const - { - return fName->fieldName; - } - Json::StaticString const& getJsonName () const - { - return fName->getJsonName (); - } - virtual SerializedTypeID getSType () const { return STI_NOTPRESENT; @@ -479,7 +456,8 @@ public: static std::uint64_t uRateOne; - STAmount (std::uint64_t v = 0, bool isNeg = false) : mValue (v), mOffset (0), mIsNative (true), mIsNegative (isNeg) + STAmount (std::uint64_t v = 0, bool isNeg = false) + : mValue (v), mOffset (0), mIsNative (true), mIsNegative (isNeg) { if (v == 0) mIsNegative = false; } @@ -495,49 +473,49 @@ public: set (v); } - STAmount (const uint160& currency, const uint160& issuer, + STAmount (Currency const& currency, Account const& issuer, std::uint64_t uV = 0, int iOff = 0, bool bNegative = false) : mCurrency (currency), mIssuer (issuer), mValue (uV), mOffset (iOff), mIsNegative (bNegative) { canonicalize (); } - STAmount (const uint160& currency, const uint160& issuer, + STAmount (Currency const& currency, Account const& issuer, std::uint32_t uV, int iOff = 0, bool bNegative = false) : mCurrency (currency), mIssuer (issuer), mValue (uV), mOffset (iOff), mIsNegative (bNegative) { canonicalize (); } - STAmount (SField::ref n, const uint160& currency, const uint160& issuer, + STAmount (SField::ref n, Currency const& currency, Account const& issuer, std::uint64_t v = 0, int off = 0, bool isNeg = false) : SerializedType (n), mCurrency (currency), mIssuer (issuer), mValue (v), mOffset (off), mIsNegative (isNeg) { canonicalize (); } - STAmount (const uint160& currency, const uint160& issuer, std::int64_t v, int iOff = 0) + STAmount (Currency const& currency, Account const& issuer, std::int64_t v, int iOff = 0) : mCurrency (currency), mIssuer (issuer), mOffset (iOff) { set (v); canonicalize (); } - STAmount (SField::ref n, const uint160& currency, const uint160& issuer, std::int64_t v, int off = 0) + STAmount (SField::ref n, Currency const& currency, Account const& issuer, std::int64_t v, int off = 0) : SerializedType (n), mCurrency (currency), mIssuer (issuer), mOffset (off) { set (v); canonicalize (); } - STAmount (const uint160& currency, const uint160& issuer, int v, int iOff = 0) + STAmount (Currency const& currency, Account const& issuer, int v, int iOff = 0) : mCurrency (currency), mIssuer (issuer), mOffset (iOff) { set (v); canonicalize (); } - STAmount (SField::ref n, const uint160& currency, const uint160& issuer, int v, int off = 0) + STAmount (SField::ref n, Currency const& currency, Account const& issuer, int v, int off = 0) : SerializedType (n), mCurrency (currency), mIssuer (issuer), mOffset (off) { set (v); @@ -557,7 +535,7 @@ public: static STAmount saFromRate (std::uint64_t uRate = 0) { - return STAmount (CURRENCY_ONE, ACCOUNT_ONE, uRate, -9, false); + return STAmount (noCurrency(), noAccount(), uRate, -9, false); } SerializedTypeID getSType () const @@ -646,7 +624,7 @@ public: mIsNative = saTmpl.mIsNative; clear (); } - void clear (const uint160& currency, const uint160& issuer) + void clear (Currency const& currency, Account const& issuer) { mCurrency = currency; mIssuer = issuer; @@ -662,22 +640,24 @@ public: int compare (const STAmount&) const; - const uint160& getIssuer () const + Account const& getIssuer () const { return mIssuer; } - STAmount* setIssuer (const uint160& uIssuer) + STAmount* setIssuer (Account const& uIssuer) { mIssuer = uIssuer; return this; } - const uint160& getCurrency () const + Currency const& getCurrency () const { return mCurrency; } bool setValue (const std::string& sAmount); - bool setFullValue (const std::string& sAmount, const std::string& sCurrency = "", const std::string& sIssuer = ""); + bool setFullValue ( + const std::string& sAmount, const std::string& sCurrency = "", + const std::string& sIssuer = ""); void setValue (const STAmount&); virtual bool isEquivalent (const SerializedType& t) const; @@ -717,7 +697,7 @@ public: static STAmount divide ( const STAmount& v1, const STAmount& v2, - const uint160& currency, const uint160& issuer); + Currency const& currency, Account const& issuer); static STAmount divide ( const STAmount& v1, const STAmount& v2, const STAmount& saUnit) @@ -731,7 +711,7 @@ public: static STAmount multiply ( const STAmount& v1, const STAmount& v2, - const uint160& currency, const uint160& issuer); + Currency const& currency, Account const& issuer); static STAmount multiply ( const STAmount& v1, const STAmount& v2, const STAmount& saUnit) @@ -752,9 +732,9 @@ public: static STAmount addRound (const STAmount& v1, const STAmount& v2, bool roundUp); static STAmount subRound (const STAmount& v1, const STAmount& v2, bool roundUp); static STAmount mulRound (const STAmount& v1, const STAmount& v2, - const uint160& currency, const uint160& issuer, bool roundUp); + Currency const& currency, Account const& issuer, bool roundUp); static STAmount divRound (const STAmount& v1, const STAmount& v2, - const uint160& currency, const uint160& issuer, bool roundUp); + Currency const& currency, Account const& issuer, bool roundUp); static STAmount mulRound (const STAmount& v1, const STAmount& v2, const STAmount& saUnit, bool roundUp) { @@ -779,18 +759,10 @@ public: static STAmount setRate (std::uint64_t rate); // Someone is offering X for Y, I need Z, how much do I pay - static STAmount getPay (const STAmount& offerOut, const STAmount& offerIn, const STAmount& needed); - - static std::string createHumanCurrency (const uint160& uCurrency); - static Json::Value createJsonCurrency (const uint160& uCurrency) - // XXX Punted. - { - return createHumanCurrency (uCurrency); - } + static STAmount getPay ( + const STAmount& offerOut, const STAmount& offerIn, const STAmount& needed); static STAmount deserialize (SerializerIterator&); - static bool currencyFromString (uint160& uDstCurrency, const std::string& sCurrency); - static bool issuerFromString (uint160& uDstIssuer, const std::string& sIssuer); Json::Value getJson (int) const; void setJson (Json::Value&) const; @@ -798,11 +770,12 @@ public: STAmount getRound () const; void roundSelf (); - static void canonicalizeRound (bool isNative, std::uint64_t& value, int& offset, bool roundUp); + static void canonicalizeRound ( + bool isNative, std::uint64_t& value, int& offset, bool roundUp); private: - uint160 mCurrency; // Compared by ==. Always update mIsNative. - uint160 mIssuer; // Not compared by ==. 0 for XRP. + Currency mCurrency; // Compared by ==. Always update mIsNative. + Account mIssuer; // Not compared by ==. 0 for XRP. std::uint64_t mValue; int mOffset; @@ -816,10 +789,10 @@ private: } static STAmount* construct (SerializerIterator&, SField::ref name); - STAmount (SField::ref name, const uint160& cur, const uint160& iss, + STAmount (SField::ref name, Currency const& cur, Account const& iss, std::uint64_t val, int off, bool isNat, bool isNeg) - : SerializedType (name), mCurrency (cur), mIssuer (iss), mValue (val), mOffset (off), - mIsNative (isNat), mIsNegative (isNeg) + : SerializedType (name), mCurrency (cur), mIssuer (iss), mValue (val), + mOffset (off), mIsNative (isNat), mIsNegative (isNeg) { ; } @@ -859,6 +832,8 @@ extern const STAmount saOne; //------------------------------------------------------------------------------ +// TODO(tom): make STHash128, STHash160 and STHash256 a single templated class +// to reduce the triple redundancy we have all over the rippled code. class STHash128 : public SerializedType { public: @@ -935,11 +910,11 @@ private: class STHash160 : public SerializedType { public: - STHash160 (const uint160& v) : value (v) + STHash160 (uint160 const& v) : value (v) { ; } - STHash160 (SField::ref n, const uint160& v) : SerializedType (n), value (v) + STHash160 (SField::ref n, uint160 const& v) : SerializedType (n), value (v) { ; } @@ -974,13 +949,15 @@ public: s.add160 (value); } - const uint160& getValue () const + uint160 const& getValue () const { return value; } - void setValue (const uint160& v) + + template + void setValue (base_uint<160, Tag> const& v) { - value = v; + value.copyFrom(v); } operator uint160 () const @@ -1164,7 +1141,7 @@ public: { ; } - STAccount (SField::ref n, const uint160& v); + STAccount (SField::ref n, Account const& v); STAccount (SField::ref n) : STVariableLength (n) { ; @@ -1187,8 +1164,23 @@ public: RippleAddress getValueNCA () const; void setValueNCA (const RippleAddress& nca); - void setValueH160 (const uint160& v); - bool getValueH160 (uint160&) const; + template + void setValueH160 (base_uint<160, Tag> const& v) + { + peekValue ().clear (); + peekValue ().insert (peekValue ().end (), v.begin (), v.end ()); + assert (peekValue ().size () == (160 / 8)); + } + + template + bool getValueH160 (base_uint<160, Tag>& v) const + { + auto success = isValueH160 (); + if (success) + memcpy (v.begin (), & (peekValue ().front ()), (160 / 8)); + return success; + } + bool isValueH160 () const; private: @@ -1223,8 +1215,8 @@ public: public: STPathElement ( - const uint160& account, const uint160& currency, - const uint160& issuer, bool forceCurrency = false) + Account const& account, Currency const& currency, + Account const& issuer, bool forceCurrency = false) : mAccountID (account), mCurrencyID (currency), mIssuerID (issuer) { mType = @@ -1235,19 +1227,15 @@ public: } STPathElement ( - unsigned int uType, const uint160& account, const uint160& currency, - const uint160& issuer) + unsigned int uType, Account const& account, Currency const& currency, + Account const& issuer) : mType (uType), mAccountID (account), mCurrencyID (currency), mIssuerID (issuer) - { - ; - } + {} STPathElement () : mType (0) - { - ; - } + {} int getNodeType () const { @@ -1262,33 +1250,34 @@ public: return !isOffer (); } - // Nodes are either an account ID or a offer prefix. Offer prefixs denote a class of offers. - const uint160& getAccountID () const + // Nodes are either an account ID or a offer prefix. Offer prefixs denote a + // class of offers. + Account const& getAccountID () const { return mAccountID; } - const uint160& getCurrency () const + Currency const& getCurrency () const { return mCurrencyID; } - const uint160& getIssuerID () const + Account const& getIssuerID () const { return mIssuerID; } bool operator== (const STPathElement& t) const { - return ((mType & typeAccount) == (t.mType & typeAccount)) - && (mAccountID == t.mAccountID) - && (mCurrencyID == t.mCurrencyID) - && (mIssuerID == t.mIssuerID); + return (mType & typeAccount) == (t.mType & typeAccount) + && mAccountID == t.mAccountID + && mCurrencyID == t.mCurrencyID + && mIssuerID == t.mIssuerID; } private: - unsigned int mType; - uint160 mAccountID; - uint160 mCurrencyID; - uint160 mIssuerID; + unsigned int mType; + Account mAccountID; + Currency mCurrencyID; + Account mIssuerID; }; //------------------------------------------------------------------------------ @@ -1317,6 +1306,11 @@ public: { return mPath.empty (); } + bool empty() const + { + return mPath.empty (); + } + const STPathElement& getElement (int offset) const { return mPath[offset]; @@ -1333,8 +1327,8 @@ public: { mPath.clear (); } - bool hasSeen (const uint160& account, const uint160& currency, - const uint160& issuer) const; + bool hasSeen (Account const& account, Currency const& currency, + Account const& issuer) const; Json::Value getJson (int) const; std::vector::iterator begin () @@ -1457,7 +1451,7 @@ public: } void addUniquePath (const STPath& e) { - BOOST_FOREACH(const STPath& p, value) + for (auto const& p: value) { if (p == e) return; diff --git a/src/ripple/module/data/protocol/Serializer.cpp b/src/ripple/module/data/protocol/Serializer.cpp index e58b9e4fa2..15cf0986fd 100644 --- a/src/ripple/module/data/protocol/Serializer.cpp +++ b/src/ripple/module/data/protocol/Serializer.cpp @@ -70,13 +70,6 @@ int Serializer::add128 (const uint128& i) return ret; } -int Serializer::add160 (const uint160& i) -{ - int ret = mData.size (); - mData.insert (mData.end (), i.begin (), i.end ()); - return ret; -} - int Serializer::add256 (uint256 const& i) { int ret = mData.size (); @@ -162,14 +155,6 @@ bool Serializer::get128 (uint128& o, int offset) const return true; } -bool Serializer::get160 (uint160& o, int offset) const -{ - if ((offset + (160 / 8)) > mData.size ()) return false; - - memcpy (o.begin (), & (mData.front ()) + offset, (160 / 8)); - return true; -} - bool Serializer::get256 (uint256& o, int offset) const { if ((offset + (256 / 8)) > mData.size ()) return false; diff --git a/src/ripple/module/data/protocol/Serializer.h b/src/ripple/module/data/protocol/Serializer.h index f8e870a730..dad40bfbcd 100644 --- a/src/ripple/module/data/protocol/Serializer.h +++ b/src/ripple/module/data/protocol/Serializer.h @@ -20,6 +20,8 @@ #ifndef RIPPLE_SERIALIZER_H #define RIPPLE_SERIALIZER_H +#include + #include namespace ripple { @@ -64,13 +66,21 @@ public: int add32 (std::uint32_t); // ledger indexes, account sequence, timestamps int add64 (std::uint64_t); // native currency amounts int add128 (const uint128&); // private key generators - int add160 (const uint160&); // account names, hankos int add256 (uint256 const& ); // transaction and ledger hashes int addRaw (Blob const& vector); int addRaw (const void* ptr, int len); int addRaw (const Serializer& s); int addZeros (size_t uBytes); + // TODO(tom): merge with add128 and add256. + template + int add160 (base_uint<160, Tag> const& i) + { + int ret = mData.size (); + mData.insert (mData.end (), i.begin (), i.end ()); + return ret; + } + int addVL (Blob const& vector); int addVL (const std::string& string); int addVL (const void* ptr, int len); @@ -82,9 +92,19 @@ public: bool get32 (std::uint32_t&, int offset) const; bool get64 (std::uint64_t&, int offset) const; bool get128 (uint128&, int offset) const; - bool get160 (uint160&, int offset) const; bool get256 (uint256&, int offset) const; uint256 get256 (int offset) const; + + // TODO(tom): merge with get128 and get256. + template + bool get160 (base_uint<160, Tag>& o, int offset) const + { + auto success = (offset + (160 / 8)) <= mData.size (); + if (success) + memcpy (o.begin (), & (mData.front ()) + offset, (160 / 8)); + return success; + } + bool getRaw (Blob&, int offset, int length) const; Blob getRaw (int offset, int length) const; @@ -224,7 +244,7 @@ public: std::string getHex () const { std::stringstream h; - + for (unsigned char const& element : mData) { h << @@ -307,4 +327,3 @@ public: } // ripple #endif - diff --git a/src/ripple/module/net/rpc/InfoSub.h b/src/ripple/module/net/rpc/InfoSub.h index 6e32e97cda..f3b16deae3 100644 --- a/src/ripple/module/net/rpc/InfoSub.h +++ b/src/ripple/module/net/rpc/InfoSub.h @@ -57,7 +57,7 @@ public: virtual void subAccount (ref ispListener, const boost::unordered_set& vnaAccountIDs, std::uint32_t uLedgerIndex, bool rt) = 0; - + virtual void unsubAccount (std::uint64_t uListener, const boost::unordered_set& vnaAccountIDs, bool rt) = 0; @@ -65,28 +65,28 @@ public: // VFALCO TODO Document the bool return value virtual bool subLedger (ref ispListener, Json::Value& jvResult) = 0; - + virtual bool unsubLedger (std::uint64_t uListener) = 0; virtual bool subServer (ref ispListener, Json::Value& jvResult) = 0; - + virtual bool unsubServer (std::uint64_t uListener) = 0; virtual bool subBook (ref ispListener, - RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets) = 0; - + Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets) = 0; + virtual bool unsubBook (std::uint64_t uListener, - RippleCurrency const& currencyPays, RippleCurrency const& currencyGets, - RippleIssuer const& issuerPays, RippleIssuer const& issuerGets) = 0; + Currency const& currencyPays, Currency const& currencyGets, + Account const& issuerPays, Account const& issuerGets) = 0; virtual bool subTransactions (ref ispListener) = 0; - + virtual bool unsubTransactions (std::uint64_t uListener) = 0; virtual bool subRTTransactions (ref ispListener) = 0; - + virtual bool unsubRTTransactions (std::uint64_t uListener) = 0; // VFALCO TODO Remove diff --git a/src/ripple/module/rpc/handlers/AccountCurrencies.cpp b/src/ripple/module/rpc/handlers/AccountCurrencies.cpp index bbbc63f386..2b74f5b346 100644 --- a/src/ripple/module/rpc/handlers/AccountCurrencies.cpp +++ b/src/ripple/module/rpc/handlers/AccountCurrencies.cpp @@ -49,9 +49,11 @@ Json::Value doAccountCurrencies (RPC::Context& context) if (!jvAccepted.empty ()) return jvAccepted; - std::set send, receive; - AccountItems rippleLines (naAccount.getAccountID (), lpLedger, AccountItem::pointer (new RippleState ())); - BOOST_FOREACH(AccountItem::ref item, rippleLines.getItems ()) + std::set send, receive; + AccountItems rippleLines ( + naAccount.getAccountID (), lpLedger, + AccountItem::pointer (new RippleState ())); + for (auto item: rippleLines.getItems ()) { RippleState* rspEntry = (RippleState*) item.get (); const STAmount& saBalance = rspEntry->getBalance (); @@ -63,20 +65,18 @@ Json::Value doAccountCurrencies (RPC::Context& context) } - send.erase (CURRENCY_BAD); - receive.erase (CURRENCY_BAD); + send.erase (badCurrency()); + receive.erase (badCurrency()); - Json::Value& sendCurrencies = (jvResult["send_currencies"] = Json::arrayValue); - BOOST_FOREACH(uint160 const& c, send) - { - sendCurrencies.append (STAmount::createHumanCurrency (c)); - } + Json::Value& sendCurrencies = + (jvResult["send_currencies"] = Json::arrayValue); + for (auto const& c: send) + sendCurrencies.append (to_string (c)); - Json::Value& recvCurrencies = (jvResult["receive_currencies"] = Json::arrayValue); - BOOST_FOREACH(uint160 const& c, receive) - { - recvCurrencies.append (STAmount::createHumanCurrency (c)); - } + Json::Value& recvCurrencies = + (jvResult["receive_currencies"] = Json::arrayValue); + for (auto const& c: receive) + recvCurrencies.append (to_string (c)); return jvResult; diff --git a/src/ripple/module/rpc/handlers/AccountLines.cpp b/src/ripple/module/rpc/handlers/AccountLines.cpp index 03c411978b..9347fd5dc4 100644 --- a/src/ripple/module/rpc/handlers/AccountLines.cpp +++ b/src/ripple/module/rpc/handlers/AccountLines.cpp @@ -89,7 +89,7 @@ Json::Value doAccountLines (RPC::Context& context) Json::Value& jPeer = jsonLines.append (Json::objectValue); - jPeer[jss::account] = RippleAddress::createHumanAccountID (line->getAccountIDPeer ()); + jPeer[jss::account] = to_string (line->getAccountIDPeer ()); // Amount reported is positive if current account holds other account's IOUs. // Amount reported is negative if other account holds current account's IOUs. jPeer[jss::balance] = saBalance.getText (); diff --git a/src/ripple/module/rpc/handlers/BookOffers.cpp b/src/ripple/module/rpc/handlers/BookOffers.cpp index 35d78ecf18..bf7be746c0 100644 --- a/src/ripple/module/rpc/handlers/BookOffers.cpp +++ b/src/ripple/module/rpc/handlers/BookOffers.cpp @@ -19,33 +19,6 @@ namespace ripple { -template -inline bool is_xrp (UnsignedInteger const& value) -{ - return value.isZero(); -} - -template -inline bool is_not_xrp (UnsignedInteger const& value) -{ - return ! is_xrp (value); -} - -inline uint160 const& xrp_issuer () -{ - return ACCOUNT_XRP; -} - -inline uint160 const& xrp_currency () -{ - return CURRENCY_XRP; -} - -inline uint160 const& neutral_issuer () -{ - return ACCOUNT_ONE; -} - Json::Value doBookOffers (RPC::Context& context) { context.lock_.unlock (); @@ -90,82 +63,80 @@ Json::Value doBookOffers (RPC::Context& context) if (! taker_gets ["currency"].isString ()) return RPC::expected_field_error ("taker_gets.currency", "string"); - uint160 pay_currency; + Currency pay_currency; - if (! STAmount::currencyFromString ( - pay_currency, taker_pays ["currency"].asString ())) + if (!to_currency (pay_currency, taker_pays ["currency"].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency."; return RPC::make_error (rpcSRC_CUR_MALFORMED, "Invalid field 'taker_pays.currency', bad currency."); } - uint160 get_currency; + Currency get_currency; - if (! STAmount::currencyFromString ( - get_currency, taker_gets ["currency"].asString ())) + if (!to_currency (get_currency, taker_gets ["currency"].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad taker_gets currency."; return RPC::make_error (rpcDST_AMT_MALFORMED, "Invalid field 'taker_gets.currency', bad currency."); } - uint160 pay_issuer; + Account pay_issuer; if (taker_pays.isMember ("issuer")) { if (! taker_pays ["issuer"].isString()) return RPC::expected_field_error ("taker_pays.issuer", "string"); - if (! STAmount::issuerFromString ( + if (!to_issuer( pay_issuer, taker_pays ["issuer"].asString ())) return RPC::make_error (rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', bad issuer."); - if (pay_issuer == neutral_issuer ()) + if (pay_issuer == noAccount ()) return RPC::make_error (rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', bad issuer account one."); } else { - pay_issuer = xrp_issuer (); + pay_issuer = xrpIssuer (); } - if (is_xrp (pay_currency) && ! is_xrp (pay_issuer)) + if (isXRP (pay_currency) && ! isXRP (pay_issuer)) return RPC::make_error (rpcSRC_ISR_MALFORMED, "Unneeded field 'taker_pays.issuer' for XRP currency specification."); - if (is_not_xrp (pay_currency) && is_xrp (pay_issuer)) + if (!isXRP (pay_currency) && isXRP (pay_issuer)) return RPC::make_error (rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); - uint160 get_issuer; + Account get_issuer; if (taker_gets.isMember ("issuer")) { if (! taker_gets ["issuer"].isString()) return RPC::expected_field_error ("taker_gets.issuer", "string"); - if (! STAmount::issuerFromString ( + if (! to_issuer ( get_issuer, taker_gets ["issuer"].asString ())) return RPC::make_error (rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer."); - if (get_issuer == neutral_issuer ()) + if (get_issuer == noAccount ()) return RPC::make_error (rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer account one."); } else { - get_issuer = xrp_issuer (); + get_issuer = xrpIssuer (); } - if (is_xrp (get_currency) && ! is_xrp (get_issuer)) + if (isXRP (get_currency) && ! isXRP (get_issuer)) return RPC::make_error (rpcDST_ISR_MALFORMED, "Unneeded field 'taker_gets.issuer' for XRP currency specification."); - if (is_not_xrp (get_currency) && is_xrp (get_issuer)) + if (!isXRP (get_currency) && isXRP (get_issuer)) return RPC::make_error (rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', expected non-XRP issuer."); @@ -181,7 +152,7 @@ Json::Value doBookOffers (RPC::Context& context) } else { - raTakerID.setAccountID (ACCOUNT_ONE); + raTakerID.setAccountID (noAccount()); } if (pay_currency == get_currency && pay_issuer == get_issuer) diff --git a/src/ripple/module/rpc/handlers/LedgerEntry.cpp b/src/ripple/module/rpc/handlers/LedgerEntry.cpp index b497d090d6..b2c988a0b6 100644 --- a/src/ripple/module/rpc/handlers/LedgerEntry.cpp +++ b/src/ripple/module/rpc/handlers/LedgerEntry.cpp @@ -159,7 +159,7 @@ Json::Value doLedgerEntry (RPC::Context& context) { RippleAddress naA; RippleAddress naB; - uint160 uCurrency; + Currency uCurrency; Json::Value jvRippleState = context.params_["ripple_state"]; if (!jvRippleState.isObject () @@ -179,7 +179,8 @@ Json::Value doLedgerEntry (RPC::Context& context) { jvResult["error"] = "malformedAddress"; } - else if (!STAmount::currencyFromString (uCurrency, jvRippleState["currency"].asString ())) + else if (!to_currency ( + uCurrency, jvRippleState["currency"].asString ())) { jvResult["error"] = "malformedCurrency"; } diff --git a/src/ripple/module/rpc/handlers/Profile.cpp b/src/ripple/module/rpc/handlers/Profile.cpp index 5b569dd6c0..82bda7a8a6 100644 --- a/src/ripple/module/rpc/handlers/Profile.cpp +++ b/src/ripple/module/rpc/handlers/Profile.cpp @@ -31,10 +31,10 @@ Json::Value doProfile (RPC::Context& context) int iArgs = context.params_.size(); RippleAddress naSeedA; RippleAddress naAccountA; - uint160 uCurrencyOfferA; + Currency uCurrencyOfferA; RippleAddress naSeedB; RippleAddress naAccountB; - uint160 uCurrencyOfferB; + Currency uCurrencyOfferB; uint32 iCount = 100; bool bSubmit = false; @@ -48,11 +48,11 @@ Json::Value doProfile (RPC::Context& context) naAccountA.setAccountID(context.params_[2u].asString()); // - if (!STAmount::currencyFromString(uCurrencyOfferA, context.params_[3u].asString())) // + if (!to_currency(uCurrencyOfferA, context.params_[3u].asString())) // return rpcError(rpcINVALID_PARAMS); naAccountB.setAccountID(context.params_[4u].asString()); // - if (!STAmount::currencyFromString(uCurrencyOfferB, context.params_[5u].asString())) // + if (!to_currency(uCurrencyOfferB, context.params_[5u].asString())) // return rpcError(rpcINVALID_PARAMS); iCount = lexicalCast (context.params_[6u].asString()); diff --git a/src/ripple/module/rpc/handlers/RipplePathFind.cpp b/src/ripple/module/rpc/handlers/RipplePathFind.cpp index 69c7992fba..8401d5754e 100644 --- a/src/ripple/module/rpc/handlers/RipplePathFind.cpp +++ b/src/ripple/module/rpc/handlers/RipplePathFind.cpp @@ -69,7 +69,7 @@ Json::Value doRipplePathFind (RPC::Context& context) !context.params_.isMember ("destination_amount") || !saDstAmount.bSetJson (context.params_["destination_amount"]) || saDstAmount <= zero - || (!!saDstAmount.getCurrency () && (!saDstAmount.getIssuer () || ACCOUNT_ONE == saDstAmount.getIssuer ()))) + || (!!saDstAmount.getCurrency () && (!saDstAmount.getIssuer () || noAccount() == saDstAmount.getIssuer ()))) { WriteLog (lsINFO, RPCHandler) << "Bad destination_amount."; jvResult = rpcError (rpcINVALID_PARAMS); @@ -111,16 +111,14 @@ Json::Value doRipplePathFind (RPC::Context& context) } else { - boost::unordered_set usCurrencies = usAccountSourceCurrencies (raSrc, cache, true); + auto usCurrencies = usAccountSourceCurrencies (raSrc, cache, true); - jvSrcCurrencies = Json::Value (Json::arrayValue); + jvSrcCurrencies = Json::Value (Json::arrayValue); - BOOST_FOREACH (const uint160 & uCurrency, usCurrencies) + for (auto const& uCurrency: usCurrencies) { Json::Value jvCurrency (Json::objectValue); - - jvCurrency["currency"] = STAmount::createHumanCurrency (uCurrency); - + jvCurrency["currency"] = to_string(uCurrency); jvSrcCurrencies.append (jvCurrency); } } @@ -128,9 +126,9 @@ Json::Value doRipplePathFind (RPC::Context& context) // Fill in currencies destination will accept Json::Value jvDestCur (Json::arrayValue); - boost::unordered_set usDestCurrID = usAccountDestCurrencies (raDst, cache, true); - BOOST_FOREACH (const uint160 & uCurrency, usDestCurrID) - jvDestCur.append (STAmount::createHumanCurrency (uCurrency)); + auto usDestCurrID = usAccountDestCurrencies (raDst, cache, true); + for (auto const& uCurrency: usDestCurrID) + jvDestCur.append (to_string (uCurrency)); jvResult["destination_currencies"] = jvDestCur; jvResult["destination_account"] = raDst.humanAccountID (); @@ -141,15 +139,16 @@ Json::Value doRipplePathFind (RPC::Context& context) { Json::Value jvSource = jvSrcCurrencies[i]; - uint160 uSrcCurrencyID; - uint160 uSrcIssuerID; + Currency uSrcCurrencyID; + Account uSrcIssuerID; if (!jvSource.isObject ()) return rpcError (rpcINVALID_PARAMS); // Parse mandatory currency. if (!jvSource.isMember ("currency") - || !STAmount::currencyFromString (uSrcCurrencyID, jvSource["currency"].asString ())) + || !to_currency ( + uSrcCurrencyID, jvSource["currency"].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad currency."; @@ -162,9 +161,9 @@ Json::Value doRipplePathFind (RPC::Context& context) // Parse optional issuer. if (jvSource.isMember ("issuer") && ((!jvSource["issuer"].isString () || - !STAmount::issuerFromString (uSrcIssuerID, jvSource["issuer"].asString ())) || + !to_issuer (uSrcIssuerID, jvSource["issuer"].asString ())) || (uSrcIssuerID.isZero () != uSrcCurrencyID.isZero ()) || - (ACCOUNT_ONE == uSrcIssuerID))) + (noAccount() == uSrcIssuerID))) { WriteLog (lsINFO, RPCHandler) << "Bad issuer."; @@ -209,8 +208,8 @@ Json::Value doRipplePathFind (RPC::Context& context) !!uSrcIssuerID ? uSrcIssuerID // Use specifed issuer. : !!uSrcCurrencyID // Default to source account. - ? raSrc.getAccountID () - : ACCOUNT_XRP, + ? Account(raSrc.getAccountID ()) + : xrpIssuer(), 1); saMaxAmount.negate (); diff --git a/src/ripple/module/rpc/handlers/Subscribe.cpp b/src/ripple/module/rpc/handlers/Subscribe.cpp index 73ae083adb..edcacc8286 100644 --- a/src/ripple/module/rpc/handlers/Subscribe.cpp +++ b/src/ripple/module/rpc/handlers/Subscribe.cpp @@ -199,10 +199,10 @@ Json::Value doSubscribe (RPC::Context& context) return rpcError (rpcINVALID_PARAMS); // VFALCO TODO Use RippleAsset here - RippleCurrency pay_currency; - RippleIssuer pay_issuer; - RippleCurrency get_currency; - RippleIssuer get_issuer; + Currency pay_currency; + Account pay_issuer; + Currency get_currency; + Account get_issuer; bool bBoth = (jvSubRequest.isMember ("both") && jvSubRequest["both"].asBool ()) || (jvSubRequest.isMember ("both_sides") && jvSubRequest["both_sides"].asBool ()); // DEPRECATED @@ -214,7 +214,7 @@ Json::Value doSubscribe (RPC::Context& context) // Parse mandatory currency. if (!taker_pays.isMember (jss::currency) - || !STAmount::currencyFromString (pay_currency, taker_pays[jss::currency].asString ())) + || !to_currency (pay_currency, taker_pays[jss::currency].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency."; @@ -223,10 +223,10 @@ Json::Value doSubscribe (RPC::Context& context) // Parse optional issuer. else if (((taker_pays.isMember (jss::issuer)) && (!taker_pays[jss::issuer].isString () - || !STAmount::issuerFromString (pay_issuer, taker_pays[jss::issuer].asString ()))) + || !to_issuer (pay_issuer, taker_pays[jss::issuer].asString ()))) // Don't allow illegal issuers. || (!pay_currency != !pay_issuer) - || ACCOUNT_ONE == pay_issuer) + || noAccount() == pay_issuer) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays issuer."; @@ -235,7 +235,7 @@ Json::Value doSubscribe (RPC::Context& context) // Parse mandatory currency. if (!taker_gets.isMember (jss::currency) - || !STAmount::currencyFromString (get_currency, taker_gets[jss::currency].asString ())) + || !to_currency (get_currency, taker_gets[jss::currency].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency."; @@ -244,10 +244,10 @@ Json::Value doSubscribe (RPC::Context& context) // Parse optional issuer. else if (((taker_gets.isMember (jss::issuer)) && (!taker_gets[jss::issuer].isString () - || !STAmount::issuerFromString (get_issuer, taker_gets[jss::issuer].asString ()))) + || !to_issuer (get_issuer, taker_gets[jss::issuer].asString ()))) // Don't allow illegal issuers. || (!get_currency != !get_issuer) - || ACCOUNT_ONE == get_issuer) + || noAccount() == get_issuer) { WriteLog (lsINFO, RPCHandler) << "Bad taker_gets issuer."; @@ -266,7 +266,7 @@ Json::Value doSubscribe (RPC::Context& context) if (!jvSubRequest.isMember ("taker")) { - raTakerID.setAccountID (ACCOUNT_ONE); + raTakerID.setAccountID (noAccount()); } else if (!raTakerID.setAccountID (jvSubRequest["taker"].asString ())) { diff --git a/src/ripple/module/rpc/handlers/Unsubscribe.cpp b/src/ripple/module/rpc/handlers/Unsubscribe.cpp index cb82cc26b9..217bfbed5d 100644 --- a/src/ripple/module/rpc/handlers/Unsubscribe.cpp +++ b/src/ripple/module/rpc/handlers/Unsubscribe.cpp @@ -137,19 +137,22 @@ Json::Value doUnsubscribe (RPC::Context& context) || !jvSubRequest["taker_gets"].isObject ()) return rpcError (rpcINVALID_PARAMS); - uint160 pay_currency; - uint160 pay_issuer; - uint160 get_currency; - uint160 get_issuer; - bool bBoth = (jvSubRequest.isMember ("both") && jvSubRequest["both"].asBool ()) - || (jvSubRequest.isMember ("both_sides") && jvSubRequest["both_sides"].asBool ()); // DEPRECATED + Currency pay_currency; + Account pay_issuer; + Currency get_currency; + Account get_issuer; + bool bBoth = (jvSubRequest.isMember ("both") && + jvSubRequest["both"].asBool ()) + || (jvSubRequest.isMember ("both_sides") && + jvSubRequest["both_sides"].asBool ()); // DEPRECATED Json::Value taker_pays = jvSubRequest["taker_pays"]; Json::Value taker_gets = jvSubRequest["taker_gets"]; // Parse mandatory currency. if (!taker_pays.isMember ("currency") - || !STAmount::currencyFromString (pay_currency, taker_pays["currency"].asString ())) + || !to_currency ( + pay_currency, taker_pays["currency"].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency."; @@ -158,10 +161,11 @@ Json::Value doUnsubscribe (RPC::Context& context) // Parse optional issuer. else if (((taker_pays.isMember ("issuer")) && (!taker_pays["issuer"].isString () - || !STAmount::issuerFromString (pay_issuer, taker_pays["issuer"].asString ()))) + || !to_issuer ( + pay_issuer, taker_pays["issuer"].asString ()))) // Don't allow illegal issuers. || (!pay_currency != !pay_issuer) - || ACCOUNT_ONE == pay_issuer) + || noAccount() == pay_issuer) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays issuer."; @@ -170,7 +174,8 @@ Json::Value doUnsubscribe (RPC::Context& context) // Parse mandatory currency. if (!taker_gets.isMember ("currency") - || !STAmount::currencyFromString (get_currency, taker_gets["currency"].asString ())) + || !to_currency (get_currency, + taker_gets["currency"].asString ())) { WriteLog (lsINFO, RPCHandler) << "Bad taker_pays currency."; @@ -179,10 +184,11 @@ Json::Value doUnsubscribe (RPC::Context& context) // Parse optional issuer. else if (((taker_gets.isMember ("issuer")) && (!taker_gets["issuer"].isString () - || !STAmount::issuerFromString (get_issuer, taker_gets["issuer"].asString ()))) + || !to_issuer (get_issuer, + taker_gets["issuer"].asString ()))) // Don't allow illegal issuers. || (!get_currency != !get_issuer) - || ACCOUNT_ONE == get_issuer) + || noAccount() == get_issuer) { WriteLog (lsINFO, RPCHandler) << "Bad taker_gets issuer."; @@ -197,9 +203,18 @@ Json::Value doUnsubscribe (RPC::Context& context) return rpcError (rpcBAD_MARKET); } - context.netOps_.unsubBook (ispSub->getSeq (), pay_currency, get_currency, pay_issuer, get_issuer); + context.netOps_.unsubBook ( + ispSub->getSeq (), + pay_currency, get_currency, + pay_issuer, get_issuer); - if (bBoth) context.netOps_.unsubBook (ispSub->getSeq (), get_currency, pay_currency, get_issuer, pay_issuer); + if (bBoth) + { + context.netOps_.unsubBook ( + ispSub->getSeq (), + get_currency, pay_currency, + get_issuer, pay_issuer); + } } } diff --git a/src/ripple/module/rpc/impl/AccountFromString.cpp b/src/ripple/module/rpc/impl/AccountFromString.cpp index 97f186c85e..492e39bf93 100644 --- a/src/ripple/module/rpc/impl/AccountFromString.cpp +++ b/src/ripple/module/rpc/impl/AccountFromString.cpp @@ -59,7 +59,7 @@ Json::Value accountFromString (Ledger::ref lrLedger, RippleAddress& naAccount, naRegular0Public.setAccountPublic (naGenerator, 0); naRegular0Private.setAccountPrivate (naGenerator, naSeed, 0); - // uint160 uGeneratorID = naRegular0Public.getAccountID(); + // Account uGeneratorID = naRegular0Public.getAccountID(); SLE::pointer sleGen = netOps.getGenerator (lrLedger, naRegular0Public.getAccountID ()); if (!sleGen) diff --git a/src/ripple/module/rpc/impl/TransactionSign.cpp b/src/ripple/module/rpc/impl/TransactionSign.cpp index 6ca71b2bfe..b82fb4c376 100644 --- a/src/ripple/module/rpc/impl/TransactionSign.cpp +++ b/src/ripple/module/rpc/impl/TransactionSign.cpp @@ -122,8 +122,8 @@ static Json::Value signPayment( { // Need a ripple path. STPathSet spsPaths; - uint160 uSrcCurrencyID; - uint160 uSrcIssuerID; + Currency uSrcCurrencyID; + Account uSrcIssuerID; STAmount saSendMax; diff --git a/src/ripple/types/api/RippleAssets.h b/src/ripple/types/api/RippleAssets.h index d6575d5937..3c10c04aa6 100644 --- a/src/ripple/types/api/RippleAssets.h +++ b/src/ripple/types/api/RippleAssets.h @@ -24,48 +24,38 @@ #include #include +#include + namespace ripple { -/** Identifies a currency in the payment network. - Currencies are associated with issuers. - @see RippleIssuer -*/ -typedef uint160 RippleCurrency; - -/** Identifies the account of a currency issuer. - Currency IOUs are issued by account holders. - @see RippleCurrency -*/ -typedef uint160 RippleIssuer; - //------------------------------------------------------------------------------ /** Ripple asset specifier, expressed as a currency issuer pair. When ByValue is `false`, this only stores references, and the caller is responsible for managing object lifetime. - @see RippleCurrency, RippleIssuer, RippleAssset, RippleAssetRef + @see Currency, Account, RippleAssset, RippleAssetRef */ template class RippleAssetType { public: - typedef typename std::conditional ::type Currency; + typedef typename + std::conditional ::type + AssetCurrency; - typedef typename std::conditional ::type Issuer; + typedef typename + std::conditional ::type + AssetIssuer; - Currency currency; - Issuer issuer; + AssetCurrency currency; + AssetIssuer issuer; RippleAssetType () { } - RippleAssetType (RippleCurrency const& currency_, - RippleIssuer const& issuer_) - : currency (currency_) - , issuer (issuer_) + RippleAssetType (Currency const& currency_, Account const& issuer_) + : currency (currency_), issuer (issuer_) { // Either XRP and (currency == zero && issuer == zero) or some custom // currency and (currency != 0 && issuer != 0) @@ -193,7 +183,7 @@ RippleAsset make_asset (Json::Value json, /** Returns an asset specifier that represents XRP. */ inline RippleAssetRef xrp_asset () { - static RippleAsset asset (RippleCurrency (0), RippleIssuer (0)); + static RippleAsset asset (Currency (0), Account (0)); return asset; } @@ -327,14 +317,14 @@ namespace std { template struct hash > - : private boost::base_from_member , 0> - , private boost::base_from_member , 1> + : private boost::base_from_member , 0> + , private boost::base_from_member , 1> { private: typedef boost::base_from_member < - std::hash , 0> currency_hash_type; + std::hash , 0> currency_hash_type; typedef boost::base_from_member < - std::hash , 1> issuer_hash_type; + std::hash , 1> issuer_hash_type; public: typedef std::size_t value_type; diff --git a/src/ripple/types/api/UInt160.h b/src/ripple/types/api/UInt160.h index 93091ddf3a..86853f9612 100644 --- a/src/ripple/types/api/UInt160.h +++ b/src/ripple/types/api/UInt160.h @@ -31,7 +31,13 @@ namespace ripple { -uint256 to256 (uint160 const& a); +template +uint256 to256 (base_uint<160, Tag> const& a) +{ + uint256 m; + memcpy (m.begin (), a.begin (), a.size ()); + return m; +} } diff --git a/src/ripple/types/api/UintTypes.h b/src/ripple/types/api/UintTypes.h new file mode 100644 index 0000000000..1e50fe3fe5 --- /dev/null +++ b/src/ripple/types/api/UintTypes.h @@ -0,0 +1,135 @@ +//------------------------------------------------------------------------------ +/* + This file is part of rippled: https://github.com/ripple/rippled + Copyright (c) 2014 Ripple Labs Inc. + + Permission to use, copy, modify, and/or 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. +*/ +//============================================================================== + +#ifndef RIPPLE_TYPES_BASICS +#define RIPPLE_TYPES_BASICS + +#include + +#include + +namespace ripple { +namespace detail { + +class AccountTag {}; +class CurrencyTag {}; +class DirectoryTag {}; +class NodeIDTag {}; + +} // detail + +/** Directory is an index into the directory of offer books. + The last 64 bits of this are the quality. */ +typedef base_uint<256, detail::DirectoryTag> Directory; + +/** Account is a hash representing a specific account. */ +typedef base_uint<160, detail::AccountTag> Account; + +/** Currency is a hash representing a specific currency. */ +typedef base_uint<160, detail::CurrencyTag> Currency; + +/** NodeID is a 160-bit hash representing one node. */ +typedef base_uint<160, detail::NodeIDTag> NodeID; + +typedef std::unordered_set CurrencySet; +typedef std::unordered_set NodeIDSet; + +/** A special account that's used as the "issuer" for XRP. */ +Account const& xrpIssuer(); + +/** XRP currency. */ +Currency const& xrpCurrency(); + +/** A placeholder for empty accounts. */ +Account const& noAccount(); + +/** A placeholder for empty currencies. */ +Currency const& noCurrency(); + +/** We deliberately disallow the currency that looks like "XRP" because too + many people were using it instead of the correct XRP currency. */ +Currency const& badCurrency(); + +inline bool isXRP(Currency const& c) +{ + return c == zero; +} + +inline bool isXRP(Account const& c) +{ + return c == zero; +} + +/** Returns a human-readable form of the account. */ +std::string to_string(Account const&); + +/** Returns "", "XRP", or three letter ISO code. */ +std::string to_string(Currency const& c); + +const char* systemCurrencyCode(); + +/** Tries to convert a string to a Currency, returns true on success. */ +bool to_currency(Currency&, std::string const&); + +/** Tries to convert a string to a Currency, returns noCurrency() on failure. */ +Currency to_currency(std::string const&); + +/** Tries to convert a string to an Account representing an issuer, returns true + * on success. */ +bool to_issuer(Account&, std::string const&); + +inline std::ostream& operator<< (std::ostream& os, Account const& x) +{ + os << to_string (x); + return os; +} + +inline std::ostream& operator<< (std::ostream& os, Currency const& x) +{ + os << to_string (x); + return os; +} + +} // ripple + +namespace std { + +template <> +struct hash : ripple::Account::hasher +{ +}; + +template <> +struct hash : ripple::Currency::hasher +{ +}; + +template <> +struct hash : ripple::NodeID::hasher +{ +}; + +template <> +struct hash : ripple::Directory::hasher +{ +}; + +} // std + +#endif diff --git a/src/ripple/types/api/base_uint.h b/src/ripple/types/api/base_uint.h index 6335d405b9..0e3eebb2be 100644 --- a/src/ripple/types/api/base_uint.h +++ b/src/ripple/types/api/base_uint.h @@ -65,7 +65,7 @@ public: // STL Container Interface // - static std::size_t const bytes = Bits/8; + static std::size_t const bytes = Bits / 8; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; @@ -122,7 +122,7 @@ private: explicit base_uint (void const* data, VoidHelper) { - memcpy (&pn [0], data, Bits / 8); + memcpy (&pn [0], data, bytes); } public: @@ -152,15 +152,10 @@ public: base_uint (base_uint const& other) = default; - template < - class OtherTag, - class = std::enable_if_t < - std::is_same ::value != - std::is_same ::value> - > - base_uint (base_uint const& other) + template + void copyFrom (base_uint const& other) { - memcpy (&pn [0], other.data(), Bits / 8); + memcpy (&pn [0], other.data(), bytes); } /* Construct from a raw pointer. @@ -414,20 +409,9 @@ extern std::size_t hash_value (uint256 const&); //------------------------------------------------------------------------------ -template -struct is_tag_compatible -{ - static bool const value = - std::is_same ::value || - std::is_same ::value || - std::is_same ::value; -}; - -template ::value> -> +template inline int compare ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { auto ret = std::mismatch (a.cbegin (), a.cend (), b.cbegin ()); @@ -442,68 +426,56 @@ inline int compare ( return -1; } -template ::value> -> +template inline bool operator< ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { return compare (a, b) < 0; } -template ::value> -> +template inline bool operator<= ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { return compare (a, b) <= 0; } -template ::value> -> +template inline bool operator> ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { return compare (a, b) > 0; } -template ::value> -> +template inline bool operator>= ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { return compare (a, b) >= 0; } -template ::value> -> +template inline bool operator== ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { return compare (a, b) == 0; } -template ::value> -> +template inline bool operator!= ( - base_uint const& a, base_uint const& b) + base_uint const& a, base_uint const& b) { return compare (a, b) != 0; } //------------------------------------------------------------------------------ -template +template inline bool operator== (base_uint const& a, std::uint64_t b) { return a == base_uint(b); } -template +template inline bool operator!= (base_uint const& a, std::uint64_t b) { return !(a == b); diff --git a/src/ripple/types/impl/RippleAssets.cpp b/src/ripple/types/impl/RippleAssets.cpp index 16f03767c5..603f81b6ec 100644 --- a/src/ripple/types/impl/RippleAssets.cpp +++ b/src/ripple/types/impl/RippleAssets.cpp @@ -79,9 +79,9 @@ public: template void testAssetType () { - RippleCurrency const c1 (1); RippleIssuer const i1 (1); - RippleCurrency const c2 (2); RippleIssuer const i2 (2); - RippleCurrency const c3 (3); RippleIssuer const i3 (3); + Currency const c1 (1); Account const i1 (1); + Currency const c2 (2); Account const i2 (2); + Currency const c3 (3); Account const i3 (3); expect (Asset (c1, i1) != Asset (c2, i1)); expect (Asset (c1, i1) < Asset (c2, i1)); @@ -124,10 +124,10 @@ public: template void testAssetSet () { - RippleCurrency const c1 (1); - RippleIssuer const i1 (1); - RippleCurrency const c2 (2); - RippleIssuer const i2 (2); + Currency const c1 (1); + Account const i1 (1); + Currency const c2 (2); + Account const i2 (2); RippleAssetRef const a1 (c1, i1); RippleAssetRef const a2 (c2, i2); @@ -170,10 +170,10 @@ public: template void testAssetMap () { - RippleCurrency const c1 (1); - RippleIssuer const i1 (1); - RippleCurrency const c2 (2); - RippleIssuer const i2 (2); + Currency const c1 (1); + Account const i1 (1); + Currency const c2 (2); + Account const i2 (2); RippleAssetRef const a1 (c1, i1); RippleAssetRef const a2 (c2, i2); @@ -259,9 +259,9 @@ public: template void testBook () { - RippleCurrency const c1 (1); RippleIssuer const i1 (1); - RippleCurrency const c2 (2); RippleIssuer const i2 (2); - RippleCurrency const c3 (3); RippleIssuer const i3 (3); + Currency const c1 (1); Account const i1 (1); + Currency const c2 (2); Account const i2 (2); + Currency const c3 (3); Account const i3 (3); RippleAsset a1 (c1, i1); RippleAsset a2 (c1, i2); @@ -316,10 +316,10 @@ public: template void testBookSet () { - RippleCurrency const c1 (1); - RippleIssuer const i1 (1); - RippleCurrency const c2 (2); - RippleIssuer const i2 (2); + Currency const c1 (1); + Account const i1 (1); + Currency const c2 (2); + Account const i2 (2); RippleAssetRef const a1 (c1, i1); RippleAssetRef const a2 (c2, i2); RippleBookRef const b1 (a1, a2); @@ -364,10 +364,10 @@ public: template void testBookMap () { - RippleCurrency const c1 (1); - RippleIssuer const i1 (1); - RippleCurrency const c2 (2); - RippleIssuer const i2 (2); + Currency const c1 (1); + Account const i1 (1); + Currency const c2 (2); + Account const i2 (2); RippleAssetRef const a1 (c1, i1); RippleAssetRef const a2 (c2, i2); RippleBookRef const b1 (a1, a2); @@ -459,11 +459,11 @@ public: void run() { - testcase ("RippleCurrency"); - testUnsigned (); + testcase ("Currency"); + testUnsigned (); - testcase ("RippleIssuer"); - testUnsigned (); + testcase ("Account"); + testUnsigned (); // --- diff --git a/src/ripple/types/impl/UInt160.cpp b/src/ripple/types/impl/UInt160.cpp deleted file mode 100644 index 8df5862e14..0000000000 --- a/src/ripple/types/impl/UInt160.cpp +++ /dev/null @@ -1,29 +0,0 @@ -//------------------------------------------------------------------------------ -/* - This file is part of rippled: https://github.com/ripple/rippled - Copyright (c) 2012, 2013 Ripple Labs Inc. - - Permission to use, copy, modify, and/or 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. -*/ -//============================================================================== - -namespace ripple { - -uint256 to256 (uint160 const& a) -{ - uint256 m; - memcpy (m.begin (), a.begin (), a.size ()); - return m; -} - -} diff --git a/src/ripple/types/impl/UintTypes.cpp b/src/ripple/types/impl/UintTypes.cpp new file mode 100644 index 0000000000..5c8b1d5f5e --- /dev/null +++ b/src/ripple/types/impl/UintTypes.cpp @@ -0,0 +1,151 @@ +//------------------------------------------------------------------------------ +/* + This file is part of rippled: https://github.com/ripple/rippled + Copyright (c) 2014 Ripple Labs Inc. + + Permission to use, copy, modify, and/or 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 + +#include +#include + +namespace ripple { + +std::string to_string(Account const& account) +{ + return RippleAddress::createAccountID (account).humanAccountID (); +} + +std::string to_string(Currency const& currency) +{ + static Currency const sIsoBits ("FFFFFFFFFFFFFFFFFFFFFFFF000000FFFFFFFFFF"); + + if (currency == zero) + return systemCurrencyCode(); + + if (currency == noCurrency()) + return "1"; + + if ((currency & sIsoBits).isZero ()) + { + // The offset of the 3 character ISO code in the currency descriptor + int const isoOffset = 12; + + std::string const iso( + currency.data () + isoOffset, + currency.data () + isoOffset + 3); + + // Specifying the system currency code using ISO-style representation + // is not allowed. + if (iso != systemCurrencyCode()) + return iso; + } + + uint160 simple; + simple.copyFrom(currency); + + return to_string(simple); +} + +bool to_currency(Currency& currency, std::string const& code) +{ + if (code.empty () || !code.compare (systemCurrencyCode())) + { + currency = zero; + return true; + } + + static const int CURRENCY_CODE_LENGTH = 3; + if (code.size () == CURRENCY_CODE_LENGTH) + { + Blob codeBlob (CURRENCY_CODE_LENGTH); + + std::transform (code.begin (), code.end (), codeBlob.begin (), ::toupper); + + Serializer s; + + s.addZeros (96 / 8); + s.addRaw (codeBlob); + s.addZeros (16 / 8); + s.addZeros (24 / 8); + + s.get160 (currency, 0); + return true; + } + + if (40 == code.size ()) + return currency.SetHex (code); + + return false; +} + +Currency to_currency(std::string const& code) +{ + Currency currency; + if (!to_currency(currency, code)) + currency = noCurrency(); + return currency; +} + +bool to_issuer(Account& issuer, std::string const& s) +{ + if (s.size () == (160 / 4)) + { + issuer.SetHex (s); + return true; + } + RippleAddress address; + bool success = address.setAccountID (s); + if (success) + issuer = address.getAccountID (); + return success; +} + +const char* systemCurrencyCode() { + return "XRP"; +} + +Account const& xrpIssuer() +{ + static const Account account(0); + return account; +} + +Currency const& xrpCurrency() +{ + static const Currency currency(0); + return currency; +} + +Account const& noAccount() +{ + static const Account account(1); + return account; +} + +Currency const& noCurrency() +{ + static const Currency currency(1); + return currency; +} + +Currency const& badCurrency() +{ + static const Currency currency(0x5852500000000000); + return currency; +} + +} // ripple diff --git a/src/ripple/unity/app.h b/src/ripple/unity/app.h index 4d60c83962..e5747e8eeb 100644 --- a/src/ripple/unity/app.h +++ b/src/ripple/unity/app.h @@ -125,10 +125,5 @@ #include #include #include -// VFALCO NOTE These contracts files are bunk -#include -#include -#include -#include #endif diff --git a/src/ripple/unity/app1.cpp b/src/ripple/unity/app1.cpp index 164deff175..c47aa76a26 100644 --- a/src/ripple/unity/app1.cpp +++ b/src/ripple/unity/app1.cpp @@ -37,7 +37,8 @@ #include #include -#include // requires Application +// requires Application +#include #include diff --git a/src/ripple/unity/app3.cpp b/src/ripple/unity/app3.cpp index 5d9a369f79..a2aa3111fc 100644 --- a/src/ripple/unity/app3.cpp +++ b/src/ripple/unity/app3.cpp @@ -27,7 +27,3 @@ #include #include #include -#include -#include -#include -#include diff --git a/src/ripple/unity/app9.cpp b/src/ripple/unity/app9.cpp index 3f8cee01c2..46ec6740fd 100644 --- a/src/ripple/unity/app9.cpp +++ b/src/ripple/unity/app9.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include diff --git a/src/ripple/unity/types.cpp b/src/ripple/unity/types.cpp index 84f67a0bbc..c4b2f52430 100644 --- a/src/ripple/unity/types.cpp +++ b/src/ripple/unity/types.cpp @@ -44,9 +44,8 @@ #include #include #include -#include +#include #include #include #include -