31 #include <graphene/chain/hardfork.hpp>
42 namespace graphene {
namespace chain {
44 void database::update_global_dynamic_data(
const signed_block& b,
const uint32_t missed_blocks )
49 modify( _dgp, [&b,
this,missed_blocks]( dynamic_global_property_object& dgp ){
50 const uint32_t block_num = b.block_num();
51 if( BOOST_UNLIKELY( block_num == 1 ) )
52 dgp.recently_missed_count = 0;
53 else if( !_checkpoints.empty() && _checkpoints.rbegin()->first >= block_num )
54 dgp.recently_missed_count = 0;
55 else if( missed_blocks )
59 else if( dgp.recently_missed_count > 0 )
60 dgp.recently_missed_count--;
62 dgp.head_block_number = block_num;
63 dgp.head_block_id = b.id();
64 dgp.time = b.timestamp;
65 dgp.current_witness = b.witness;
66 dgp.recent_slots_filled = (
67 (dgp.recent_slots_filled << 1)
68 + 1) << missed_blocks;
69 dgp.current_aslot += missed_blocks+1;
75 "The database does not have enough undo history to support a blockchain with so many missed blocks. "
76 "Please add a checkpoint if you would like to continue applying blocks beyond this point.",
77 (
"last_irreversible_block_num",_dgp.last_irreversible_block_num)(
"head", _dgp.head_block_number)
82 _fork_db.
set_max_size( _dgp.head_block_number - _dgp.last_irreversible_block_num + 1 );
85 void database::update_signing_witness(
const witness_object& signing_witness,
const signed_block& new_block)
89 uint64_t new_block_aslot = dpo.current_aslot +
get_slot_at_time( new_block.timestamp );
91 share_type witness_pay = std::min( gpo.parameters.witness_pay_per_block, dpo.witness_budget );
93 modify( dpo, [&]( dynamic_global_property_object& _dpo )
95 _dpo.witness_budget -= witness_pay;
100 modify( signing_witness, [&]( witness_object& _wit )
102 _wit.last_aslot = new_block_aslot;
103 _wit.last_confirmed_block_num = new_block.block_num();
107 void database::update_last_irreversible_block()
113 vector< const witness_object* > wit_objs;
114 wit_objs.reserve( gpo.active_witnesses.size() );
115 for(
const witness_id_type& wid : gpo.active_witnesses )
116 wit_objs.push_back( &(wid(*
this)) );
127 std::nth_element( wit_objs.begin(), wit_objs.begin() + offset, wit_objs.end(),
128 [](
const witness_object* a,
const witness_object* b )
130 return a->last_confirmed_block_num < b->last_confirmed_block_num;
133 uint32_t new_last_irreversible_block_num = wit_objs[offset]->last_confirmed_block_num;
135 if( new_last_irreversible_block_num > dpo.last_irreversible_block_num )
137 modify( dpo, [&]( dynamic_global_property_object& _dpo )
139 _dpo.last_irreversible_block_num = new_last_irreversible_block_num;
144 void database::clear_expired_transactions()
149 impl_transaction_history_object_type));
150 const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
151 while( (!dedupe_index.empty()) && (
head_block_time() > dedupe_index.begin()->trx.expiration) )
152 transaction_idx.remove(*dedupe_index.begin());
155 void database::clear_expired_proposals()
157 const auto& proposal_expiration_index = get_index_type<proposal_index>().indices().get<by_expiration>();
158 while( !proposal_expiration_index.empty() && proposal_expiration_index.begin()->expiration_time <=
head_block_time() )
160 const proposal_object& proposal = *proposal_expiration_index.begin();
161 processed_transaction result;
163 if( proposal.is_authorized_to_execute(*
this) )
170 elog(
"Failed to apply proposed transaction on its expiration. Deleting it.\n${proposal}\n${error}",
178 static optional<price> get_derived_current_feed_price(
const database& db,
179 const asset_bitasset_data_object& bitasset )
181 optional<price> result;
183 if( bitasset.median_feed.settlement_price.is_null() )
185 if( bitasset.current_feed.settlement_price.is_null() )
188 return bitasset.median_feed.settlement_price;
192 const auto bsrm = bitasset.get_black_swan_response_method();
193 if( bsrm_type::no_settlement == bsrm )
196 const call_order_object* call_ptr = db.find_least_collateralized_short( bitasset,
true );
200 auto least_collateral = call_ptr->collateralization();
202 bitasset.current_feed.maximum_short_squeeze_ratio );
203 result = std::max( bitasset.median_feed.settlement_price, lowest_callable_feed_price );
206 result = bitasset.median_feed.settlement_price;
208 else if( bsrm_type::individual_settlement_to_fund == bsrm && bitasset.individual_settlement_debt > 0 )
211 price fund_price = asset( bitasset.individual_settlement_debt, bitasset.asset_id )
212 / asset( bitasset.individual_settlement_fund, bitasset.options.short_backing_asset );
213 auto lowest_callable_feed_price = fund_price * bitasset.get_margin_call_order_ratio();
214 result = std::max( bitasset.median_feed.settlement_price, lowest_callable_feed_price );
217 result = bitasset.median_feed.settlement_price;
220 if( result.valid() && (*result) == bitasset.current_feed.settlement_price )
226 static void update_settled_debt_order( database& db,
const asset_bitasset_data_object& bitasset )
229 if( bitasset.current_feed.settlement_price.is_null() )
232 const limit_order_object* limit_ptr = db.find_settled_debt_order( bitasset.asset_id );
236 bool sell_all =
true;
240 price sell_price = ~bitasset.get_margin_call_order_price();
241 asset settled_debt( bitasset.individual_settlement_debt, limit_ptr->receive_asset_id() );
244 for_sale = settled_debt.multiply_and_round_up( sell_price ).amount;
245 if( for_sale <= bitasset.individual_settlement_fund )
255 db.modify( *limit_ptr, [sell_all, &sell_price, &for_sale, &bitasset]( limit_order_object& obj )
259 obj.for_sale = bitasset.individual_settlement_fund;
260 obj.sell_price = ~bitasset.get_individual_settlement_price();
264 obj.for_sale = for_sale;
265 obj.sell_price = sell_price;
276 if( skip_median_update )
278 if( bsrm_type::no_settlement != bsrm && bsrm_type::individual_settlement_to_fund != bsrm )
287 new_current_feed_price = get_derived_current_feed_price( *
this, bitasset );
288 if( !new_current_feed_price.
valid() )
296 modify( bitasset, [
this, skip_median_update, &head_time, &new_current_feed_price, &bsrm]
299 if( !skip_median_update )
304 if( bsrm_type::no_settlement == bsrm || bsrm_type::individual_settlement_to_fund == bsrm )
305 new_current_feed_price = get_derived_current_feed_price( *
this, abdo );
307 if( new_current_feed_price.
valid() )
312 if( !skip_median_update
313 && bsrm_type::individual_settlement_to_order == bsrm
314 && HARDFORK_CORE_2591_PASSED( head_time ) )
316 update_settled_debt_order( *
this, bitasset );
320 void database::clear_expired_orders()
326 bool before_core_hardfork_606 = ( maint_time <= HARDFORK_CORE_606_TIME );
328 auto& limit_index = get_index_type<limit_order_index>().indices().get<
by_expiration>();
329 while( !limit_index.empty() && limit_index.begin()->expiration <= head_time )
335 if( before_core_hardfork_606 )
348 void database::clear_expired_force_settlements()
359 const auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>();
360 if( settlement_index.empty() )
366 const bool before_core_hardfork_184 = ( maint_time <= HARDFORK_CORE_184_TIME );
367 const bool before_core_hardfork_342 = ( maint_time <= HARDFORK_CORE_342_TIME );
369 asset_id_type current_asset = settlement_index.begin()->settlement_asset_id();
370 const asset_object* mia_object_ptr = &
get(current_asset);
371 const asset_bitasset_data_object* mia_ptr = &mia_object_ptr->bitasset_data(*
this);
373 asset max_settlement_volume;
374 price settlement_fill_price;
375 price settlement_price;
376 bool current_asset_finished =
false;
378 auto next_asset = [¤t_asset, &mia_object_ptr, &mia_ptr, ¤t_asset_finished, &settlement_index,
this] {
379 const auto bound = settlement_index.upper_bound(current_asset);
380 if( bound == settlement_index.end() )
382 current_asset = bound->settlement_asset_id();
383 mia_object_ptr = &
get(current_asset);
384 mia_ptr = &mia_object_ptr->bitasset_data(*
this);
385 current_asset_finished =
false;
390 for(
auto itr = settlement_index.lower_bound(current_asset);
391 itr != settlement_index.end();
392 itr = settlement_index.lower_bound(current_asset) )
394 const force_settlement_object& settle_order = *itr;
395 auto settle_order_id = settle_order.id;
397 if( current_asset != settle_order.settlement_asset_id() )
399 current_asset = settle_order.settlement_asset_id();
400 mia_object_ptr = &
get(current_asset);
401 mia_ptr = &mia_object_ptr->bitasset_data(*
this);
405 const asset_object& mia_object = *mia_object_ptr;
406 const asset_bitasset_data_object& mia = *mia_ptr;
408 if( mia.is_globally_settled() )
410 ilog(
"Canceling a force settlement because of black swan" );
416 if( settle_order.settlement_date > head_time )
423 if( mia.current_feed.settlement_price.is_null() )
425 ilog(
"Canceling a force settlement in ${asset} because settlement price is null",
426 (
"asset", mia_object.symbol));
432 ilog(
"Canceling a force settlement in ${asset} because settlement offset is 100%",
433 (
"asset", mia_object.symbol));
439 if( max_settlement_volume.asset_id != current_asset )
440 max_settlement_volume = mia_object.amount( mia.max_force_settlement_volume(
441 mia_object.dynamic_data(*this).current_supply ) );
444 if( mia.force_settled_volume >= max_settlement_volume.amount || current_asset_finished )
451 if( settlement_fill_price.base.asset_id != current_asset )
452 settlement_fill_price = mia.current_feed.settlement_price
456 if( before_core_hardfork_342 )
458 auto& pays = settle_order.balance;
459 auto receives = (settle_order.balance * mia.current_feed.settlement_price);
460 receives.amount =
static_cast<uint64_t
>( ( fc::uint128_t(receives.amount.value) *
463 assert(receives <= settle_order.balance * mia.current_feed.settlement_price);
464 settlement_price = pays / receives;
466 else if( settlement_price.base.asset_id != current_asset )
467 settlement_price = settlement_fill_price;
469 asset settled = mia_object.amount(mia.force_settled_volume);
471 while( settled < max_settlement_volume &&
find_object(settle_order_id) )
473 if( 0 == settle_order.balance.amount )
475 wlog(
"0 settlement detected" );
484 wlog(
"No debt position found when processing force settlement ${o}", (
"o",settle_order) );
490 asset max_settlement = max_settlement_volume - settled;
492 asset new_settled = match( settle_order, *call_ptr, settlement_price, mia,
493 max_settlement, settlement_fill_price );
494 if( !before_core_hardfork_184 && new_settled.amount == 0 )
497 current_asset_finished = (
nullptr !=
find_object( settle_order_id ) );
500 settled += new_settled;
514 catch (
const black_swan_exception& e ) {
515 wlog(
"Cancelling a settle_order since it may trigger a black swan: ${o}, ${e}",
516 (
"o", settle_order)(
"e", e.to_detail_string()) );
521 if( mia.force_settled_volume != settled.amount )
523 modify(mia, [&settled](asset_bitasset_data_object& b) {
524 b.force_settled_volume = settled.amount;
530 void database::update_expired_feeds()
533 bool after_hardfork_615 = ( head_time >= HARDFORK_615_TIME );
534 bool after_core_hardfork_2582 = HARDFORK_CORE_2582_PASSED( head_time );
536 const auto& idx = get_index_type<asset_bitasset_data_index>().indices().get<by_feed_expiration>();
537 auto itr = idx.begin();
538 while( itr != idx.end() && itr->feed_is_expired( head_time ) )
540 const asset_bitasset_data_object& b = *itr;
544 if( !( after_hardfork_615 || b.feed_is_expired_before_hf_615( head_time ) ) )
547 auto old_current_feed = b.current_feed;
548 auto old_median_feed = b.median_feed;
549 const asset_object& asset_obj = b.asset_id( *
this );
553 if( !b.current_feed.settlement_price.is_null()
554 && !b.current_feed.margin_call_params_equal( old_current_feed ) )
558 else if( after_core_hardfork_2582 && !b.median_feed.settlement_price.is_null()
559 && !b.median_feed.margin_call_params_equal( old_median_feed ) )
564 if( b.need_to_update_cer() )
566 modify( b, []( asset_bitasset_data_object& abdo )
568 abdo.asset_cer_updated =
false;
569 abdo.feed_cer_updated =
false;
571 if( asset_obj.options.core_exchange_rate != b.current_feed.core_exchange_rate )
573 modify( asset_obj, [&b]( asset_object& ao )
575 ao.options.core_exchange_rate = b.current_feed.core_exchange_rate;
582 if( !after_hardfork_615 )
584 for( asset_id_type a : _issue_453_affected_assets )
591 void database::update_core_exchange_rates()
593 const auto& idx = get_index_type<asset_bitasset_data_index>().indices().get<by_cer_update>();
594 if( idx.begin() != idx.end() )
596 for(
auto itr = idx.rbegin(); itr->need_to_update_cer(); itr = idx.rbegin() )
598 const asset_bitasset_data_object& b = *itr;
599 const asset_object& a = b.asset_id( *
this );
600 if( a.options.core_exchange_rate != b.current_feed.core_exchange_rate )
602 modify( a, [&b]( asset_object& ao )
604 ao.options.core_exchange_rate = b.current_feed.core_exchange_rate;
607 modify( b, []( asset_bitasset_data_object& abdo )
609 abdo.asset_cer_updated =
false;
610 abdo.feed_cer_updated =
false;
616 void database::update_maintenance_flag(
bool new_maintenance_flag )
622 (dpo.dynamic_flags & (uint32_t)(~maintenance_flag))
623 | (new_maintenance_flag ? (uint32_t)maintenance_flag : 0U);
628 void database::update_withdraw_permissions()
630 auto& permit_index = get_index_type<withdraw_permission_index>().indices().get<by_expiration>();
631 while( !permit_index.empty() && permit_index.begin()->expiration <=
head_block_time() )
632 remove(*permit_index.begin());
635 void database::clear_expired_htlcs()
637 const auto& htlc_idx = get_index_type<htlc_index>().indices().get<by_expiration>();
638 while ( htlc_idx.begin() != htlc_idx.end()
639 && htlc_idx.begin()->conditions.time_lock.expiration <=
head_block_time() )
641 const htlc_object& obj = *htlc_idx.begin();
642 const auto amount = asset(obj.transfer.amount, obj.transfer.asset_id);
645 htlc_refund_operation vop( obj.get_id(), obj.transfer.from, obj.transfer.to, amount,
646 obj.conditions.hash_lock.preimage_hash, obj.conditions.hash_lock.preimage_size );
660 auto& idx = get_index_type<ticket_index>().indices().get<by_next_update>();
661 while( !idx.empty() && idx.begin()->next_auto_update_time <=
head_block_time() )
693 if( ticket.
value == 0 )
700 delta_forever_value = ticket.
value - old_value;
708 delta_forever_value = ticket.
value;
710 delta_other_value = -old_value;
714 delta_other_value = ticket.
value - old_value;
719 modify( stat, [delta_inactive_amount,delta_forever_amount,delta_forever_value,
735 if( total_delta_pob != 0 || total_delta_inactive != 0 )
747 void database::update_credit_offers_and_deals()
752 const auto& offer_idx = get_index_type<credit_offer_index>().indices().get<by_auto_disable_time>();
753 auto offer_itr = offer_idx.lower_bound(
true );
754 auto offer_itr_end = offer_idx.upper_bound( boost::make_tuple(
true, head_time ) );
755 while( offer_itr != offer_itr_end )
765 const auto& deal_idx = get_index_type<credit_deal_index>().indices().get<by_latest_repay_time>();
766 const auto& deal_summary_idx = get_index_type<credit_deal_summary_index>().indices().get<by_offer_borrower>();
767 auto deal_itr_end = deal_idx.upper_bound( head_time );
768 for(
auto deal_itr = deal_idx.begin(); deal_itr != deal_itr_end; deal_itr = deal_idx.begin() )
770 const credit_deal_object& deal = *deal_itr;
775 if(
static_cast<uint8_t
>(repay_type::no_auto_repayment) != deal.auto_repay )
777 credit_deal_repay_operation op;
778 op.account = deal.borrower;
779 op.deal_id = deal.get_id();
782 auto required_fee = ( ( ( fc::uint128_t( deal.debt_amount.value ) * deal.fee_rate )
784 fc::uint128_t total_required = required_fee + deal.debt_amount.value;
785 auto balance =
get_balance( deal.borrower, deal.debt_asset );
786 if(
static_cast<uint8_t
>(repay_type::only_full_repayment) == deal.auto_repay
787 || fc::uint128_t( balance.amount.value ) >= total_required )
789 op.repay_amount = asset( deal.debt_amount, deal.debt_asset );
790 op.credit_fee = asset(
static_cast<int64_t
>( required_fee ), deal.debt_asset );
796 fc::uint128_t collateral_to_release = ( debt_to_repay * deal.collateral_amount.value )
797 / deal.debt_amount.value;
798 debt_to_repay = ( ( ( collateral_to_release * deal.debt_amount.value ) + deal.collateral_amount.value )
799 - 1 ) / deal.collateral_amount.value;
800 fc::uint128_t fee_to_pay = ( ( ( debt_to_repay * deal.fee_rate )
802 op.repay_amount = asset(
static_cast<int64_t
>( debt_to_repay ), deal.debt_asset );
803 op.credit_fee = asset(
static_cast<int64_t
>( fee_to_pay ), deal.debt_asset );
806 auto deal_copy = deal;
808 transaction_evaluation_state eval_state(
this);
809 eval_state.skip_fee_schedule_check =
true;
813 try_push_virtual_operation( eval_state, op );
819 wlog(
"Automatic repayment ${op} for credit deal ${credit_deal} failed at block ${n}; "
820 "account balance was ${balance}; exception was ${e}",
821 (
"op", op)(
"credit_deal", deal_copy)
825 if( !
find( op.deal_id ) )
831 const credit_offer_object& offer = deal.offer_id(*
this);
832 modify( offer, [&deal]( credit_offer_object& obj ){
833 obj.total_balance -= deal.debt_amount;
837 auto summ_itr = deal_summary_idx.find( boost::make_tuple( deal.offer_id, deal.borrower ) );
838 if( summ_itr == deal_summary_idx.end() )
841 elog(
"Error: unable to find the credit deal summary object for credit deal ${d}",
846 const credit_deal_summary_object& summ_obj = *summ_itr;
847 if( summ_obj.total_debt_amount == deal.debt_amount )
853 modify( summ_obj, [&deal]( credit_deal_summary_object& obj ){
854 obj.total_debt_amount -= deal.debt_amount;
860 adjust_balance( deal.offer_owner, asset( deal.collateral_amount, deal.collateral_asset ) );
864 deal.get_id(), deal.offer_id, deal.offer_owner, deal.borrower,
865 asset( deal.debt_amount, deal.debt_asset ),
866 asset( deal.collateral_amount, deal.collateral_asset ),