From 02224e714d7e3ca0d07416b5882ae0cfc92900f2 Mon Sep 17 00:00:00 2001
From: UkoeHB <37489173+UkoeHB@users.noreply.github.com>
Date: Wed, 8 Jan 2020 05:21:43 -0600
Subject: [PATCH] Fix check_fee() discrepancy.

M100 = max{300kb, min{100block_median, m_long_term_effective_median_block_weight}}
not
M100 = max{300kb, m_long_term_effective_median_block_weight}

Fix base reward in get_dynamic_base_fee_estimate().

get_dynamic_base_fee_estimate() should match check_fee()

Fee is calculated based on block reward, and the reward penalty takes into account 0.5*max_block_weight (both before and after HF_VERSION_EFFECTIVE_SHORT_TERM_MEDIAN_IN_PENALTY).

Moved median calculation according to best practice of 'keep definitions close to where they are used'.
---
 src/cryptonote_core/blockchain.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/cryptonote_core/blockchain.cpp b/src/cryptonote_core/blockchain.cpp
index 7357e44d0..f162f4608 100644
--- a/src/cryptonote_core/blockchain.cpp
+++ b/src/cryptonote_core/blockchain.cpp
@@ -3409,7 +3409,7 @@ bool Blockchain::check_fee(size_t tx_weight, uint64_t fee) const
   if (version >= HF_VERSION_PER_BYTE_FEE)
   {
     const bool use_long_term_median_in_fee = version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT;
-    uint64_t fee_per_byte = get_dynamic_base_fee(base_reward, use_long_term_median_in_fee ? m_long_term_effective_median_block_weight : median, version);
+    uint64_t fee_per_byte = get_dynamic_base_fee(base_reward, use_long_term_median_in_fee ? std::min<uint64_t>(median, m_long_term_effective_median_block_weight) : median, version);
     MDEBUG("Using " << print_money(fee_per_byte) << "/byte fee");
     needed_fee = tx_weight * fee_per_byte;
     // quantize fee up to 8 decimals
@@ -3467,7 +3467,7 @@ uint64_t Blockchain::get_dynamic_base_fee_estimate(uint64_t grace_blocks) const
 
   uint64_t already_generated_coins = db_height ? m_db->get_block_already_generated_coins(db_height - 1) : 0;
   uint64_t base_reward;
-  if (!get_block_reward(median, 1, already_generated_coins, base_reward, version))
+  if (!get_block_reward(m_current_block_cumul_weight_limit / 2, 1, already_generated_coins, base_reward, version))
   {
     MERROR("Failed to determine block reward, using placeholder " << print_money(BLOCK_REWARD_OVERESTIMATE) << " as a high bound");
     base_reward = BLOCK_REWARD_OVERESTIMATE;