feerate.cpp raw

   1  // Copyright (c) 2009-2010 Satoshi Nakamoto
   2  // Copyright (c) 2009-2022 The Limenka developers
   3  // Distributed under the MIT software license, see the accompanying
   4  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   5  
   6  #include <consensus/amount.h>
   7  #include <policy/feerate.h>
   8  #include <tinyformat.h>
   9  
  10  #include <cmath>
  11  
  12  CFeeRate::CFeeRate(const CAmount& nFeePaid, uint32_t num_bytes)
  13  {
  14      const int64_t nSize{num_bytes};
  15  
  16      if (nSize > 0) {
  17          nSatoshisPerK = nFeePaid * 1000 / nSize;
  18      } else {
  19          nSatoshisPerK = 0;
  20      }
  21  }
  22  
  23  CAmount CFeeRate::GetFee(uint32_t num_bytes) const
  24  {
  25      const int64_t nSize{num_bytes};
  26  
  27      // Be explicit that we're converting from a double to int64_t (CAmount) here.
  28      // Integer ceil division - exact for the 128-bit product (no double
  29      // precision loss above 2^53).  For non-positive products, truncation
  30      // toward zero IS ceil; for positive products, round up.
  31      const CAmount product{nSatoshisPerK * nSize};
  32      CAmount nFee{product > 0 ? (product + 999) / 1000 : product / 1000};
  33  
  34      if (nFee == 0 && nSize != 0) {
  35          if (nSatoshisPerK > 0) nFee = CAmount(1);
  36          if (nSatoshisPerK < 0) nFee = CAmount(-1);
  37      }
  38  
  39      return nFee;
  40  }
  41  
  42  std::string CFeeRate::ToString(const FeeEstimateMode& fee_estimate_mode) const
  43  {
  44      switch (fee_estimate_mode) {
  45      case FeeEstimateMode::SAT_VB: return strprintf("%d.%03d %s/vB", static_cast<int64_t>(nSatoshisPerK / 1000), static_cast<int64_t>(nSatoshisPerK % 1000), CURRENCY_ATOM);
  46      default:                      return strprintf("%d.%08d %s/kvB", static_cast<int64_t>(nSatoshisPerK / COIN), static_cast<int64_t>(nSatoshisPerK % COIN), CURRENCY_UNIT);
  47      }
  48  }
  49  
  50  std::string CFeeRate::SatsToString() const {
  51      return strprintf("%d.%03d", static_cast<int64_t>(nSatoshisPerK / 1000), static_cast<int64_t>(nSatoshisPerK % 1000));
  52  }
  53