chain_controller.cpp 92.0 KB
Newer Older
A
Andrianto Lie 已提交
1 2 3
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
N
Nathan Hourt 已提交
4
 */
N
Nathan Hourt 已提交
5

B
Bart Wyatt 已提交
6
#include <eosio/chain/chain_controller.hpp>
N
Nathan Hourt 已提交
7

B
Bart Wyatt 已提交
8 9
#include <eosio/chain/block_summary_object.hpp>
#include <eosio/chain/global_property_object.hpp>
10
#include <eosio/chain/contracts/contract_table_objects.hpp>
B
Bart Wyatt 已提交
11 12 13 14 15 16
#include <eosio/chain/action_objects.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/transaction_object.hpp>
#include <eosio/chain/producer_object.hpp>
#include <eosio/chain/permission_link_object.hpp>
#include <eosio/chain/authority_checker.hpp>
D
Daniel Larimer 已提交
17
#include <eosio/chain/contracts/chain_initializer.hpp>
18
#include <eosio/chain/scope_sequence_object.hpp>
19
#include <eosio/chain/merkle.hpp>
N
Nathan Hourt 已提交
20

21
#include <eosio/chain/exceptions.hpp>
B
Bart Wyatt 已提交
22
#include <eosio/chain/wasm_interface.hpp>
23

24
#include <eosio/utilities/rand.hpp>
25

N
Nathan Hourt 已提交
26
#include <fc/smart_ref_impl.hpp>
N
Nathan Hourt 已提交
27 28 29
#include <fc/uint128.hpp>
#include <fc/crypto/digest.hpp>

30
#include <boost/range/algorithm/copy.hpp>
31
#include <boost/range/algorithm_ext/erase.hpp>
N
Nathan Hourt 已提交
32
#include <boost/range/algorithm_ext/is_sorted.hpp>
33
#include <boost/range/adaptor/transformed.hpp>
N
Nathan Hourt 已提交
34
#include <boost/range/adaptor/map.hpp>
35
#include <boost/range/algorithm/sort.hpp>
36 37
#include <boost/range/algorithm/find.hpp>
#include <boost/range/algorithm/remove_if.hpp>
38
#include <boost/range/algorithm/equal.hpp>
N
Nathan Hourt 已提交
39 40 41

#include <fstream>
#include <functional>
42
#include <chrono>
N
Nathan Hourt 已提交
43

P
Pravin 已提交
44
namespace eosio { namespace chain {
D
Daniel Larimer 已提交
45

46 47 48 49 50
bool chain_controller::is_start_of_round( block_num_type block_num )const  {
  return 0 == (block_num % blocks_per_round());
}

uint32_t chain_controller::blocks_per_round()const {
51
  return get_global_properties().active_producers.producers.size()*config::producer_repetitions;
52 53
}

D
Daniel Larimer 已提交
54
chain_controller::chain_controller( const chain_controller::controller_config& cfg )
55 56 57
:_db( cfg.shared_memory_dir,
      (cfg.read_only ? database::read_only : database::read_write),
      cfg.shared_memory_size),
58
 _block_log(cfg.block_log_dir),
59
 _wasm_interface(cfg.wasm_runtime),
B
Bart Wyatt 已提交
60
 _limits(cfg.limits),
61
 _resource_limits(_db)
D
Daniel Larimer 已提交
62 63
{
   _initialize_indexes();
64 65
   _resource_limits.initialize_database();

D
Daniel Larimer 已提交
66

67 68
   for (auto& f : cfg.applied_block_callbacks)
      applied_block.connect(f);
69 70
   for (auto& f : cfg.applied_irreversible_block_callbacks)
      applied_irreversible_block.connect(f);
71 72
   for (auto& f : cfg.on_pending_transaction_callbacks)
      on_pending_transaction.connect(f);
73

D
Daniel Larimer 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
   contracts::chain_initializer starter(cfg.genesis);
   starter.register_types(*this, _db);

   // Behave as though we are applying a block during chain initialization (it's the genesis block!)
   with_applying_block([&] {
      _initialize_chain(starter);
   });

   _spinup_db();
   _spinup_fork_db();

   if (_block_log.read_head() && head_block_num() < _block_log.read_head()->block_num())
      replay();
} /// chain_controller::chain_controller


chain_controller::~chain_controller() {
   clear_pending();
   _db.flush();
}

95
bool chain_controller::is_known_block(const block_id_type& id)const
N
Nathan Hourt 已提交
96
{
97
   return _fork_db.is_known_block(id) || _block_log.read_block_by_id(id);
N
Nathan Hourt 已提交
98 99 100 101 102 103
}
/**
 * Only return true *if* the transaction has not expired or been invalidated. If this
 * method is called with a VERY old transaction we will return false, they should
 * query things by blocks if they are that old.
 */
104
bool chain_controller::is_known_transaction(const transaction_id_type& id)const
N
Nathan Hourt 已提交
105
{
106
   const auto& trx_idx = _db.get_index<transaction_multi_index, by_trx_id>();
N
Nathan Hourt 已提交
107 108 109
   return trx_idx.find( id ) != trx_idx.end();
}

110
block_id_type chain_controller::get_block_id_for_num(uint32_t block_num)const
N
Nathan Hourt 已提交
111
{ try {
112 113
   if (const auto& block = fetch_block_by_number(block_num))
      return block->id();
N
Nathan Hourt 已提交
114

115 116 117
   FC_THROW_EXCEPTION(unknown_block_exception, "Could not find block");
} FC_CAPTURE_AND_RETHROW((block_num)) }

118
optional<signed_block> chain_controller::fetch_block_by_id(const block_id_type& id)const
N
Nathan Hourt 已提交
119
{
120 121
   auto b = _fork_db.fetch_block(id);
   if(b) return b->data;
122
   return _block_log.read_block_by_id(id);
N
Nathan Hourt 已提交
123 124
}

125
optional<signed_block> chain_controller::fetch_block_by_number(uint32_t num)const
N
Nathan Hourt 已提交
126
{
127
   if (const auto& block = _block_log.read_block_by_num(num))
128 129
      return *block;

N
Nathan Hourt 已提交
130
   // Not in _block_log, so it must be since the last irreversible block. Grab it from _fork_db instead
131 132 133 134 135 136 137 138
   if (num <= head_block_num()) {
      auto block = _fork_db.head();
      while (block && block->num > num)
         block = block->prev.lock();
      if (block && block->num == num)
         return block->data;
   }

N
Nathan Hourt 已提交
139 140 141
   return optional<signed_block>();
}

142
std::vector<block_id_type> chain_controller::get_block_ids_on_fork(block_id_type head_of_fork) const
N
Nathan Hourt 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
{
  pair<fork_database::branch_type, fork_database::branch_type> branches = _fork_db.fetch_branch_from(head_block_id(), head_of_fork);
  if( !((branches.first.back()->previous_id() == branches.second.back()->previous_id())) )
  {
     edump( (head_of_fork)
            (head_block_id())
            (branches.first.size())
            (branches.second.size()) );
     assert(branches.first.back()->previous_id() == branches.second.back()->previous_id());
  }
  std::vector<block_id_type> result;
  for (const item_ptr& fork_block : branches.second)
    result.emplace_back(fork_block->id);
  result.emplace_back(branches.first.back()->previous_id());
  return result;
}

160

N
Nathan Hourt 已提交
161 162 163 164 165 166
/**
 * Push block "may fail" in which case every partial change is unwound.  After
 * push block is successful the block is appended to the chain database on disk.
 *
 * @return true if we switched forks as a result of this push.
 */
D
Daniel Larimer 已提交
167
void chain_controller::push_block(const signed_block& new_block, uint32_t skip)
D
Daniel Larimer 已提交
168
{ try {
169
   with_skip_flags( skip, [&](){
D
Daniel Larimer 已提交
170
      return without_pending_transactions( [&]() {
171
         return _db.with_write_lock( [&]() {
172
            return _push_block(new_block);
173
         } );
N
Nathan Hourt 已提交
174 175
      });
   });
176
} FC_CAPTURE_AND_RETHROW((new_block)) }
N
Nathan Hourt 已提交
177

178
bool chain_controller::_push_block(const signed_block& new_block)
N
Nathan Hourt 已提交
179
{ try {
N
Nathan Hourt 已提交
180
   uint32_t skip = _skip_flags;
181
   if (!(skip&skip_fork_db)) {
N
Nathan Hourt 已提交
182
      /// TODO: if the block is greater than the head block and before the next maintenance interval
N
Nathan Hourt 已提交
183 184 185 186
      // verify that the block signer is in the current set of active producers.

      shared_ptr<fork_item> new_head = _fork_db.push_block(new_block);
      //If the head block from the longest chain does not build off of the current head, we need to switch forks.
187
      if (new_head->data.previous != head_block_id()) {
N
Nathan Hourt 已提交
188 189
         //If the newly pushed block is the same height as head, we get head back in new_head
         //Only switch forks if new_head is actually higher than head
190 191
         if (new_head->data.block_num() > head_block_num()) {
            wlog("Switching to fork: ${id}", ("id",new_head->data.id()));
N
Nathan Hourt 已提交
192 193 194
            auto branches = _fork_db.fetch_branch_from(new_head->data.id(), head_block_id());

            // pop blocks until we hit the forked block
195
            while (head_block_id() != branches.second.back()->data.previous)
N
Nathan Hourt 已提交
196 197 198
               pop_block();

            // push all blocks on the new fork
199 200
            for (auto ritr = branches.first.rbegin(); ritr != branches.first.rend(); ++ritr) {
                ilog("pushing blocks from fork ${n} ${id}", ("n",(*ritr)->data.block_num())("id",(*ritr)->data.id()));
201 202 203 204 205 206 207
                {
                   uint32_t delta = 0;
                   if (ritr != branches.first.rbegin()) {
                      delta = (*ritr)->data.timestamp.slot - (*std::prev(ritr))->data.timestamp.slot;
                   } else {
                      optional<signed_block> prev = fetch_block_by_id((*ritr)->data.previous);
                      if (prev)
K
Khaled Al-Hassanieh 已提交
208
                         delta = (*ritr)->data.timestamp.slot - prev->timestamp.slot;
209 210 211 212
                   }
                   if (delta > 1)
                      wlog("Number of missed blocks: ${num}", ("num", delta-1));
                }
N
Nathan Hourt 已提交
213 214
                optional<fc::exception> except;
                try {
215
                   auto session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
216
                   _apply_block((*ritr)->data, skip);
N
Nathan Hourt 已提交
217 218
                   session.push();
                }
219 220 221
                catch (const fc::exception& e) { except = e; }
                if (except) {
                   wlog("exception thrown while switching forks ${e}", ("e",except->to_detail_string()));
N
Nathan Hourt 已提交
222
                   // remove the rest of branches.first from the fork_db, those blocks are invalid
223 224
                   while (ritr != branches.first.rend()) {
                      _fork_db.remove((*ritr)->data.id());
N
Nathan Hourt 已提交
225 226
                      ++ritr;
                   }
227
                   _fork_db.set_head(branches.second.front());
N
Nathan Hourt 已提交
228 229

                   // pop all blocks from the bad fork
230
                   while (head_block_id() != branches.second.back()->data.previous)
N
Nathan Hourt 已提交
231 232 233
                      pop_block();

                   // restore all blocks from the good fork
234
                   for (auto ritr = branches.second.rbegin(); ritr != branches.second.rend(); ++ritr) {
235
                      auto session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
236
                      _apply_block((*ritr)->data, skip);
N
Nathan Hourt 已提交
237 238 239 240 241
                      session.push();
                   }
                   throw *except;
                }
            }
D
Daniel Larimer 已提交
242
            return true; //swithced fork
N
Nathan Hourt 已提交
243
         }
D
Daniel Larimer 已提交
244
         else return false; // didn't switch fork
N
Nathan Hourt 已提交
245 246 247 248
      }
   }

   try {
249
      auto session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
250
      _apply_block(new_block, skip);
N
Nathan Hourt 已提交
251 252 253 254 255 256 257 258
      session.push();
   } catch ( const fc::exception& e ) {
      elog("Failed to push new block:\n${e}", ("e", e.to_detail_string()));
      _fork_db.remove(new_block.id());
      throw;
   }

   return false;
259
} FC_CAPTURE_AND_RETHROW((new_block)) }
N
Nathan Hourt 已提交
260 261 262 263 264 265 266 267 268 269

/**
 * Attempts to push the transaction into the pending queue
 *
 * When called to push a locally generated transaction, set the skip_block_size_check bit on the skip argument. This
 * will allow the transaction to be pushed even if it causes the pending block size to exceed the maximum block size.
 * Although the transaction will probably not propagate further now, as the peers are likely to have their pending
 * queues full as well, it will be kept in the queue to be propagated later when a new block flushes out the pending
 * queues.
 */
270
transaction_trace chain_controller::push_transaction(const packed_transaction& trx, uint32_t skip)
N
Nathan Hourt 已提交
271
{ try {
272 273 274 275 276 277
   // If this is the first transaction pushed after applying a block, start a new undo session.
   // This allows us to quickly rewind to the clean state of the head block, in case a new block arrives.
   if( !_pending_block ) {
      _start_pending_block();
   }

278 279
   return with_skip_flags(skip, [&]() {
      return _db.with_write_lock([&]() {
280
         return _push_transaction(trx);
D
Daniel Larimer 已提交
281
      });
N
Nathan Hourt 已提交
282
   });
283
} EOS_CAPTURE_AND_RETHROW( transaction_exception ) }
N
Nathan Hourt 已提交
284

285
transaction_trace chain_controller::_push_transaction(const packed_transaction& packed_trx)
286
{ try {
287
   //edump((transaction_header(packed_trx.get_transaction())));
288
   auto start = fc::time_point::now();
289
   transaction_metadata   mtrx( packed_trx, get_chain_id(), head_block_time());
290
   //idump((transaction_header(mtrx.trx())));
291

292 293 294 295 296 297 298
   const transaction& trx = mtrx.trx();
   validate_transaction_with_minimal_state( packed_trx, &trx );
   validate_referenced_accounts(trx);
   validate_uniqueness(trx);
   auto delay = check_transaction_authorization(trx, packed_trx.signatures, packed_trx.context_free_data);
   validate_expiration_not_too_far(trx, head_block_time() + delay );
   mtrx.delay = delay;
299

300
   auto setup_us = fc::time_point::now() - start;
301

302
   transaction_trace result(mtrx.id);
B
Bart Wyatt 已提交
303

304
   if( delay.count() == 0 ) {
305
      result = _push_transaction( std::move(mtrx) );
306
   } else {
307 308 309
      result = wrap_transaction_processing( std::move(mtrx),
                                            [this](transaction_metadata& meta) { return delayed_transaction_processing(meta); } );
   }
310

311 312
   // notify anyone listening to pending transactions
   on_pending_transaction(_pending_transaction_metas.back(), packed_trx);
313

314
   _pending_block->input_transactions.emplace_back(packed_trx);
315

H
Harry 已提交
316
   result._setup_profiling_us = setup_us;
317
   return result;
318

319
} FC_CAPTURE_AND_RETHROW( (transaction_header(packed_trx.get_transaction())) ) }
320

321 322 323 324 325
transaction_trace chain_controller::_push_transaction( transaction_metadata&& data )
{ try {
   auto process_apply_transaction = [this](transaction_metadata& meta) {
      auto cyclenum = _pending_block->regions.back().cycles_summary.size() - 1;
      //wdump((transaction_header(meta.trx())));
326

327
      const auto& trx = meta.trx();
328

329 330 331
      // Validate uniqueness and expiration again
      validate_uniqueness(trx);
      validate_not_expired(trx);
332

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
      /// TODO: move _pending_cycle into db so that it can be undone if transation fails, for now we will apply
      /// the transaction first so that there is nothing to undo... this only works because things are currently
      /// single threaded
      // set cycle, shard, region etc
      meta.region_id = 0;
      meta.cycle_index = cyclenum;
      meta.shard_index = 0;
      return _apply_transaction( meta );
   };
 //  wdump((transaction_header(data.trx())));
   return wrap_transaction_processing( move(data), process_apply_transaction );
} FC_CAPTURE_AND_RETHROW( ) }

transaction_trace chain_controller::delayed_transaction_processing( const transaction_metadata& mtrx )
{ try {
   transaction_trace result(mtrx.id);
   result.status = transaction_trace::delayed;

   const auto& trx = mtrx.trx();
352

353 354 355 356 357 358 359 360 361
   // add in the system account authorization
   action for_deferred = trx.actions[0];
   bool found = false;
   for (const auto& auth : for_deferred.authorization) {
      if (auth.actor == config::system_account_name &&
          auth.permission == config::active_name) {
         found = true;
         break;
      }
362
   }
363 364
   if (!found)
      for_deferred.authorization.push_back(permission_level{config::system_account_name, config::active_name});
365

366
   apply_context context(*this, _db, for_deferred, mtrx); // TODO: Better solution for getting next sender_id needed.
367

368 369
   time_point_sec execute_after = head_block_time();
   execute_after += mtrx.delay;
370 371

   // TODO: update to better method post RC1?
372 373 374 375 376 377 378 379 380 381 382 383 384
   account_name payer;
   for(const auto& act : mtrx.trx().actions ) {
      for (const auto& auth : act.authorization) {
         payer = auth.actor;
         break;
      }

      if (!payer.empty()) {
         break;
      }
   }

   FC_ASSERT(!payer.empty(), "Failed to find a payer for delayed transaction!");
385 386

   deferred_transaction dtrx(context.get_next_sender_id(), config::system_account_name, payer, execute_after, trx);
387 388 389 390 391
   FC_ASSERT( dtrx.execute_after < dtrx.expiration, "transaction expires before it can execute" );

   result.deferred_transaction_requests.push_back(std::move(dtrx));

   _create_generated_transaction(result.deferred_transaction_requests[0].get<deferred_transaction>());
392

B
Bart Wyatt 已提交
393 394
   return result;

395
} FC_CAPTURE_AND_RETHROW( ) }
B
Bart Wyatt 已提交
396

B
Bart Wyatt 已提交
397
static void record_locks_for_data_access(transaction_trace& trace, flat_set<shard_lock>& read_locks, flat_set<shard_lock>& write_locks ) {
398 399
   // Precondition: read_locks and write_locks do not intersect.

B
Bart Wyatt 已提交
400
   for (const auto& at: trace.action_traces) {
B
Bart Wyatt 已提交
401 402
      for (const auto& access: at.data_access) {
         if (access.type == data_access_info::read) {
B
Bart Wyatt 已提交
403
            trace.read_locks.emplace(shard_lock{access.code, access.scope});
B
Bart Wyatt 已提交
404
         } else {
B
Bart Wyatt 已提交
405
            trace.write_locks.emplace(shard_lock{access.code, access.scope});
B
Bart Wyatt 已提交
406 407 408
         }
      }
   }
B
Bart Wyatt 已提交
409

410
   // Step RR: Remove from trace.read_locks and from read_locks only the read locks necessary to ensure they each do not intersect with trace.write_locks.
411
   std::for_each(trace.write_locks.begin(), trace.write_locks.end(), [&]( const shard_lock& l){
412 413 414
      trace.read_locks.erase(l); read_locks.erase(l); // for step RR
      // write_locks.insert(l); // Step AW could instead be done here, but it would add unnecessary work to the lookups in step AR.
    });
B
Bart Wyatt 已提交
415

416
   // At this point, the trace.read_locks and trace.write_locks are good.
B
Bart Wyatt 已提交
417

418 419 420 421 422
   // Step AR: Add into read_locks the subset of trace.read_locks that does not intersect with write_locks (must occur after step RR).
   //          (Works regardless of whether step AW is done before or after this step.)
   std::for_each(trace.read_locks.begin(), trace.read_locks.end(), [&]( const shard_lock& l){
      if( write_locks.find(l) == write_locks.end() )
         read_locks.insert(l);
423
   });
424

N
Nathan Hourt 已提交
425

426
   // Step AW: Add trace.write_locks into write_locks.
B
Bart Wyatt 已提交
427
   write_locks.insert(trace.write_locks.begin(), trace.write_locks.end());
428 429 430

   // Postcondition: read_locks and write_locks do not intersect
   // Postcondition: trace.read_locks and trace.write_locks do not intersect
B
Bart Wyatt 已提交
431
}
K
Khaled Al-Hassanieh 已提交
432 433 434 435 436

block_header chain_controller::head_block_header() const
{
   auto b = _fork_db.fetch_block(head_block_id());
   if( b ) return b->data;
437

K
Khaled Al-Hassanieh 已提交
438 439 440
   if (auto head_block = fetch_block_by_id(head_block_id()))
      return *head_block;
   return block_header();
N
Nathan Hourt 已提交
441 442
}

443
void chain_controller::_start_pending_block( bool skip_deferred )
444 445 446 447 448
{
   FC_ASSERT( !_pending_block );
   _pending_block         = signed_block();
   _pending_block_trace   = block_trace(*_pending_block);
   _pending_block_session = _db.start_undo_session(true);
449 450
   _pending_block->regions.resize(1);
   _pending_block_trace->region_traces.resize(1);
451

452
   _start_pending_cycle();
453
   _apply_on_block_transaction();
454
   _finalize_pending_cycle();
455

456
   _start_pending_cycle();
457 458

   if ( !skip_deferred ) {
A
Anton Perkov 已提交
459 460
      _push_deferred_transactions( false );
      if (_pending_cycle_trace && _pending_cycle_trace->shard_traces.size() > 0 && _pending_cycle_trace->shard_traces.back().transaction_traces.size() > 0) {
461 462 463
         _finalize_pending_cycle();
         _start_pending_cycle();
      }
464
   }
465 466
}

K
Khaled Al-Hassanieh 已提交
467
transaction chain_controller::_get_on_block_transaction()
468 469 470 471 472
{
   action on_block_act;
   on_block_act.account = config::system_account_name;
   on_block_act.name = N(onblock);
   on_block_act.authorization = vector<permission_level>{{config::system_account_name, config::active_name}};
473
   on_block_act.data = fc::raw::pack(head_block_header());
474 475 476 477

   transaction trx;
   trx.actions.emplace_back(std::move(on_block_act));
   trx.set_reference_block(head_block_id());
478
   trx.expiration = head_block_time() + fc::seconds(1);
479
   trx.kcpu_usage = 2000; // 1 << 24;
480 481 482 483 484
   return trx;
}

void chain_controller::_apply_on_block_transaction()
{
485
   _pending_block_trace->implicit_transactions.emplace_back(_get_on_block_transaction());
B
Bucky Kittinger 已提交
486
   transaction_metadata mtrx(packed_transaction(_pending_block_trace->implicit_transactions.back()), get_chain_id(), head_block_time(), true /*is implicit*/);
487
   _push_transaction(std::move(mtrx));
488 489
}

490 491
/**
 *  Wraps up all work for current shards, starts a new cycle, and
492
 *  executes any pending transactions
493
 */
494
void chain_controller::_start_pending_cycle() {
495 496 497 498 499
   // only add a new cycle if there are no cycles or if the previous cycle isn't empty
   if (_pending_block->regions.back().cycles_summary.empty() ||
       (!_pending_block->regions.back().cycles_summary.back().empty() &&
        !_pending_block->regions.back().cycles_summary.back().back().empty()))
      _pending_block->regions.back().cycles_summary.resize( _pending_block->regions[0].cycles_summary.size() + 1 );
500 501


502
   _pending_cycle_trace = cycle_trace();
503 504

   _pending_cycle_trace->shard_traces.resize(_pending_cycle_trace->shard_traces.size() + 1 );
505 506 507 508

   auto& bcycle = _pending_block->regions.back().cycles_summary.back();
   if(bcycle.empty() || !bcycle.back().empty())
      bcycle.resize( bcycle.size()+1 );
B
Bart Wyatt 已提交
509 510
}

511 512
void chain_controller::_finalize_pending_cycle()
{
513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
   // prune empty shard
   if (!_pending_block->regions.back().cycles_summary.empty() &&
       !_pending_block->regions.back().cycles_summary.back().empty() &&
       _pending_block->regions.back().cycles_summary.back().back().empty()) {
      _pending_block->regions.back().cycles_summary.back().resize( _pending_block->regions.back().cycles_summary.back().size() - 1 );
      _pending_cycle_trace->shard_traces.resize(_pending_cycle_trace->shard_traces.size() - 1 );
   }
   // prune empty cycle
   if (!_pending_block->regions.back().cycles_summary.empty() &&
       _pending_block->regions.back().cycles_summary.back().empty()) {
      _pending_block->regions.back().cycles_summary.resize( _pending_block->regions.back().cycles_summary.size() - 1 );
      _pending_cycle_trace.reset();
      return;
   }

B
Bart Wyatt 已提交
528 529 530 531 532 533
   for( int idx = 0; idx < _pending_cycle_trace->shard_traces.size(); idx++ ) {
      auto& trace = _pending_cycle_trace->shard_traces.at(idx);
      auto& shard = _pending_block->regions.back().cycles_summary.back().at(idx);

      trace.finalize_shard();
      shard.read_locks.reserve(trace.read_locks.size());
534
      shard.read_locks.insert(shard.read_locks.end(), trace.read_locks.begin(), trace.read_locks.end());
B
Bart Wyatt 已提交
535 536 537

      shard.write_locks.reserve(trace.write_locks.size());
      shard.write_locks.insert(shard.write_locks.end(), trace.write_locks.begin(), trace.write_locks.end());
538 539
   }

540
   _apply_cycle_trace(*_pending_cycle_trace);
541
   _pending_block_trace->region_traces.back().cycle_traces.emplace_back(std::move(*_pending_cycle_trace));
542 543
   _pending_cycle_trace.reset();
}
B
Bart Wyatt 已提交
544

545 546
void chain_controller::_apply_cycle_trace( const cycle_trace& res )
{
547 548 549
   auto &generated_transaction_idx = _db.get_mutable_index<generated_transaction_multi_index>();
   const auto &generated_index = generated_transaction_idx.indices().get<by_sender_id>();

550
   // TODO: Check for conflicts in deferred_transaction_requests between shards
551 552
   for (const auto&st: res.shard_traces) {
      for (const auto &tr: st.transaction_traces) {
553 554 555 556 557
         for (const auto &req: tr.deferred_transaction_requests) {
            if ( req.contains<deferred_transaction>() ) {
               const auto& dt = req.get<deferred_transaction>();
               const auto itr = generated_index.lower_bound(boost::make_tuple(dt.sender, dt.sender_id));
               if ( itr != generated_index.end() && itr->sender == dt.sender && itr->sender_id == dt.sender_id ) {
558
                  _destroy_generated_transaction(*itr);
559
               }
560

561
               _create_generated_transaction(dt);
562 563 564 565
            } else if ( req.contains<deferred_reference>() ) {
               const auto& dr = req.get<deferred_reference>();
               const auto itr = generated_index.lower_bound(boost::make_tuple(dr.sender, dr.sender_id));
               if ( itr != generated_index.end() && itr->sender == dr.sender && itr->sender_id == dr.sender_id ) {
B
Bart Wyatt 已提交
566
                  _destroy_generated_transaction(*itr);
567 568 569
               }
            }
         }
570 571 572 573
         ///TODO: hook this up as a signal handler in a de-coupled "logger" that may just silently drop them
         for (const auto &ar : tr.action_traces) {
            if (!ar.console.empty()) {
               auto prefix = fc::format_string(
B
Bart Wyatt 已提交
574
                  "[(${a},${n})->${r}]",
575
                  fc::mutable_variant_object()
B
Bart Wyatt 已提交
576 577
                     ("a", ar.act.account)
                     ("n", ar.act.name)
578
                     ("r", ar.receiver));
579 580 581
               ilog(prefix + ": CONSOLE OUTPUT BEGIN =====================");
               ilog(ar.console);
               ilog(prefix + ": CONSOLE OUTPUT END   =====================");
582
            }
583
         }
B
Bart Wyatt 已提交
584 585 586 587
      }
   }
}

588 589 590 591
/**
 *  After applying all transactions successfully we can update
 *  the current block time, block number, producer stats, etc
 */
592
void chain_controller::_finalize_block( const block_trace& trace, const producer_object& signing_producer ) { try {
593 594 595 596 597 598 599 600 601
   const auto& b = trace.block;

   update_global_properties( b );
   update_global_dynamic_data( b );
   update_signing_producer(signing_producer, b);

   create_block_summary(b);
   clear_expired_transactions();

602
   update_last_irreversible_block();
603
   _resource_limits.process_account_limit_updates();
604

605 606 607 608 609 610
   const auto& chain_config = this->get_global_properties().configuration;
   _resource_limits.set_block_parameters(
      {EOS_PERCENT(chain_config.max_block_cpu_usage, chain_config.target_block_cpu_usage_pct), chain_config.max_block_cpu_usage, config::block_cpu_usage_average_window_ms / config::block_interval_ms, 1000, {99, 100}, {1000, 999}},
      {EOS_PERCENT(chain_config.max_block_net_usage, chain_config.target_block_net_usage_pct), chain_config.max_block_net_usage, config::block_size_average_window_ms / config::block_interval_ms, 1000, {99, 100}, {1000, 999}}
   );

611 612
   // trigger an update of our elastic values for block limits
   _resource_limits.process_block_usage(b.block_num());
613

614
   applied_block( trace ); //emit
615 616 617 618 619
   if (_currently_replaying_blocks)
     applied_irreversible_block(b);

} FC_CAPTURE_AND_RETHROW( (trace.block) ) }

620
signed_block chain_controller::generate_block(
D
Daniel Larimer 已提交
621 622 623
   block_timestamp_type when,
   account_name producer,
   const private_key_type& block_signing_private_key,
N
Nathan Hourt 已提交
624 625 626
   uint32_t skip /* = 0 */
   )
{ try {
627
   return with_skip_flags( skip | created_block, [&](){
D
Daniel Larimer 已提交
628
      return _db.with_write_lock( [&](){
D
Daniel Larimer 已提交
629
         return _generate_block( when, producer, block_signing_private_key );
D
Daniel Larimer 已提交
630
      });
N
Nathan Hourt 已提交
631
   });
D
Daniel Larimer 已提交
632
} FC_CAPTURE_AND_RETHROW( (when) ) }
N
Nathan Hourt 已提交
633

634 635
signed_block chain_controller::_generate_block( block_timestamp_type when,
                                              account_name producer,
D
Daniel Larimer 已提交
636 637
                                              const private_key_type& block_signing_key )
{ try {
638

639
   try {
640
      FC_ASSERT( head_block_time() < (fc::time_point)when, "block must be generated at a timestamp after the head block time" );
641 642 643 644 645
      uint32_t skip     = _skip_flags;
      uint32_t slot_num = get_slot_at_time( when );
      FC_ASSERT( slot_num > 0 );
      account_name scheduled_producer = get_scheduled_producer( slot_num );
      FC_ASSERT( scheduled_producer == producer );
N
Nathan Hourt 已提交
646

647
      const auto& producer_obj = get_producer(scheduled_producer);
N
Nathan Hourt 已提交
648

649 650 651
      if( !_pending_block ) {
         _start_pending_block();
      }
652

653
      _finalize_pending_cycle();
654

655
      if( !(skip & skip_producer_signature) )
K
Kevin Heifner 已提交
656 657
         FC_ASSERT( producer_obj.signing_key == block_signing_key.get_public_key(),
                    "producer key ${pk}, block key ${bk}", ("pk", producer_obj.signing_key)("bk", block_signing_key.get_public_key()) );
N
Nathan Hourt 已提交
658

B
Brian Johnson 已提交
659 660 661 662 663 664
      _pending_block->timestamp   = when;
      _pending_block->producer    = producer_obj.owner;
      _pending_block->previous    = head_block_id();
      _pending_block->block_mroot = get_dynamic_global_properties().block_merkle_root.get_root();
      _pending_block->transaction_mroot = transaction_metadata::calculate_transaction_merkle_root( _pending_transaction_metas );
      _pending_block->action_mroot = _pending_block_trace->calculate_action_merkle_root();
665

S
Spartucus 已提交
666
      if( is_start_of_round( _pending_block->block_num() ) ) {
667 668 669 670
         auto latest_producer_schedule = _calculate_producer_schedule();
         if( latest_producer_schedule != _head_producer_schedule() )
            _pending_block->new_producers = latest_producer_schedule;
      }
671
      _pending_block->schedule_version = get_global_properties().active_producers.version;
672

673 674
      if( !(skip & skip_producer_signature) )
         _pending_block->sign( block_signing_key );
675

676
      _finalize_block( *_pending_block_trace, producer_obj );
N
Nathan Hourt 已提交
677

678
      _pending_block_session->push();
D
Daniel Larimer 已提交
679

680
      auto result = move( *_pending_block );
681

682
      clear_pending();
D
Daniel Larimer 已提交
683

684 685 686 687 688
      if (!(skip&skip_fork_db)) {
         _fork_db.push_block(result);
      }
      return result;
   } catch ( ... ) {
689
      clear_pending();
690

691 692 693
      elog( "error while producing block" );
      _start_pending_block();
      throw;
N
Nathan Hourt 已提交
694 695
   }

N
Nathan Hourt 已提交
696
} FC_CAPTURE_AND_RETHROW( (producer) ) }
N
Nathan Hourt 已提交
697 698

/**
N
Nathan Hourt 已提交
699
 * Removes the most recent block from the database and undoes any changes it made.
N
Nathan Hourt 已提交
700
 */
701
void chain_controller::pop_block()
N
Nathan Hourt 已提交
702
{ try {
D
Daniel Larimer 已提交
703
   _pending_block_session.reset();
N
Nathan Hourt 已提交
704 705 706 707 708
   auto head_id = head_block_id();
   optional<signed_block> head_block = fetch_block_by_id( head_id );
   EOS_ASSERT( head_block.valid(), pop_empty_chain, "there are no blocks to pop" );

   _fork_db.pop_block();
709
   _db.undo();
N
Nathan Hourt 已提交
710 711
} FC_CAPTURE_AND_RETHROW() }

712
void chain_controller::clear_pending()
N
Nathan Hourt 已提交
713
{ try {
714
   _pending_block_trace.reset();
D
Daniel Larimer 已提交
715
   _pending_block.reset();
D
Daniel Larimer 已提交
716
   _pending_block_session.reset();
717
   _pending_transaction_metas.clear();
N
Nathan Hourt 已提交
718 719 720 721
} FC_CAPTURE_AND_RETHROW() }

//////////////////// private methods ////////////////////

D
Daniel Larimer 已提交
722
void chain_controller::_apply_block(const signed_block& next_block, uint32_t skip)
N
Nathan Hourt 已提交
723 724
{
   auto block_num = next_block.block_num();
725 726 727 728 729
   if (_checkpoints.size() && _checkpoints.rbegin()->second != block_id_type()) {
      auto itr = _checkpoints.find(block_num);
      if (itr != _checkpoints.end())
         FC_ASSERT(next_block.id() == itr->second,
                   "Block did not match checkpoint", ("checkpoint",*itr)("block_id",next_block.id()));
N
Nathan Hourt 已提交
730

731
      if (_checkpoints.rbegin()->first >= block_num)
N
Nathan Hourt 已提交
732 733
         skip = ~0;// WE CAN SKIP ALMOST EVERYTHING
   }
N
Nathan Hourt 已提交
734 735 736

   with_applying_block([&] {
      with_skip_flags(skip, [&] {
D
Daniel Larimer 已提交
737
         __apply_block(next_block);
N
Nathan Hourt 已提交
738 739
      });
   });
N
Nathan Hourt 已提交
740 741
}

742 743
static void validate_shard_locks(const vector<shard_lock>& locks, const string& tag) {
   if (locks.size() < 2) {
744 745 746
      return;
   }

B
Bart Wyatt 已提交
747
   for (auto cur = locks.begin() + 1; cur != locks.end(); ++cur) {
748
      auto prev = cur - 1;
B
Bart Wyatt 已提交
749 750
      EOS_ASSERT(*prev != *cur, block_lock_exception, "${tag} lock \"${a}::${s}\" is not unique", ("tag",tag)("a",cur->account)("s",cur->scope));
      EOS_ASSERT(*prev < *cur,  block_lock_exception, "${tag} locks are not sorted", ("tag",tag));
751 752
   }
}
753

D
Daniel Larimer 已提交
754
void chain_controller::__apply_block(const signed_block& next_block)
N
Nathan Hourt 已提交
755
{ try {
756 757
   optional<fc::time_point> processing_deadline;
   if (!_currently_replaying_blocks && _limits.max_push_block_us.count() > 0) {
B
Bart Wyatt 已提交
758
      processing_deadline = fc::time_point::now() + _limits.max_push_block_us;
759 760
   }

N
Nathan Hourt 已提交
761
   uint32_t skip = _skip_flags;
N
Nathan Hourt 已提交
762 763

   const producer_object& signing_producer = validate_block_header(skip, next_block);
764

765 766 767 768
   /// regions must be listed in order
   for( uint32_t i = 1; i < next_block.regions.size(); ++i )
      FC_ASSERT( next_block.regions[i-1].region < next_block.regions[i].region );

769
   block_trace next_block_trace(next_block);
770

B
Bucky Kittinger 已提交
771
   /// cache the input transaction ids so that they can be looked up when executing the
772
   /// summary
773
   vector<transaction_metadata> input_metas;
B
Bucky Kittinger 已提交
774
   // add all implicit transactions
775
   {
776
      next_block_trace.implicit_transactions.emplace_back(_get_on_block_transaction());
777
   }
B
Bucky Kittinger 已提交
778 779

   input_metas.reserve(next_block.input_transactions.size() + next_block_trace.implicit_transactions.size());
780

B
Bucky Kittinger 已提交
781 782 783 784
   for ( const auto& t : next_block_trace.implicit_transactions ) {
      input_metas.emplace_back(packed_transaction(t), get_chain_id(), head_block_time(), true /*implicit*/);
   }

B
Bart Wyatt 已提交
785
   map<transaction_id_type,size_t> trx_index;
786
   for( const auto& t : next_block.input_transactions ) {
787
      input_metas.emplace_back(t, chain_id_type(), next_block.timestamp);
788 789 790
      validate_transaction_with_minimal_state( t, &input_metas.back().trx() );
      if( should_check_signatures() )
         input_metas.back().signing_keys = input_metas.back().trx().get_signature_keys( t.signatures, chain_id_type(), t.context_free_data, false );
B
Bart Wyatt 已提交
791
      trx_index[input_metas.back().id] =  input_metas.size() - 1;
792
   }
793

794 795
   next_block_trace.region_traces.reserve(next_block.regions.size());

796 797
   for( uint32_t region_index = 0; region_index < next_block.regions.size(); ++region_index ) {
      const auto& r = next_block.regions[region_index];
798 799 800
      region_trace r_trace;
      r_trace.cycle_traces.reserve(r.cycles_summary.size());

801
      EOS_ASSERT(!r.cycles_summary.empty(), tx_empty_region,"region[${r_index}] has no cycles", ("r_index",region_index));
802
      for (uint32_t cycle_index = 0; cycle_index < r.cycles_summary.size(); cycle_index++) {
803
         const auto& cycle = r.cycles_summary.at(cycle_index);
804 805 806
         cycle_trace c_trace;
         c_trace.shard_traces.reserve(cycle.size());

807 808
         // validate that no read_scope is used as a write scope in this cycle and that no two shards
         // share write scopes
809 810
         set<shard_lock> read_locks;
         map<shard_lock, uint32_t> write_locks;
811

812
         EOS_ASSERT(!cycle.empty(), tx_empty_cycle,"region[${r_index}] cycle[${c_index}] has no shards", ("r_index",region_index)("c_index",cycle_index));
813 814
         for (uint32_t shard_index = 0; shard_index < cycle.size(); shard_index++) {
            const auto& shard = cycle.at(shard_index);
815 816
            EOS_ASSERT(!shard.empty(), tx_empty_shard,"region[${r_index}] cycle[${c_index}] shard[${s_index}] is empty",
                       ("r_index",region_index)("c_index",cycle_index)("s_index",shard_index));
817

818
            // Validate that the shards locks are unique and sorted
819 820 821 822
            validate_shard_locks(shard.read_locks,  "read");
            validate_shard_locks(shard.write_locks, "write");

            for (const auto& s: shard.read_locks) {
B
Bart Wyatt 已提交
823
               EOS_ASSERT(write_locks.count(s) == 0, block_concurrency_exception,
824 825 826
                  "shard ${i} requires read lock \"${a}::${s}\" which is locked for write by shard ${j}",
                  ("i", shard_index)("s", s)("j", write_locks[s]));
               read_locks.emplace(s);
827 828
            }

829
            for (const auto& s: shard.write_locks) {
B
Bart Wyatt 已提交
830
               EOS_ASSERT(write_locks.count(s) == 0, block_concurrency_exception,
831
                  "shard ${i} requires write lock \"${a}::${s}\" which is locked for write by shard ${j}",
B
Bart Wyatt 已提交
832 833 834 835
                  ("i", shard_index)("a", s.account)("s", s.scope)("j", write_locks[s]));
               EOS_ASSERT(read_locks.count(s) == 0, block_concurrency_exception,
                  "shard ${i} requires write lock \"${a}::${s}\" which is locked for read",
                  ("i", shard_index)("a", s.account)("s", s.scope));
836
               write_locks[s] = shard_index;
837 838
            }

B
Bart Wyatt 已提交
839 840
            flat_set<shard_lock> used_read_locks;
            flat_set<shard_lock> used_write_locks;
B
Bart Wyatt 已提交
841

842
            shard_trace s_trace;
B
Bart Wyatt 已提交
843
            for (const auto& receipt : shard.transactions) {
844 845
                optional<transaction_metadata> _temp;
                auto make_metadata = [&]() -> transaction_metadata* {
846 847
                  auto itr = trx_index.find(receipt.id);
                  if( itr != trx_index.end() ) {
848
                     auto& trx_meta = input_metas.at(itr->second);
849 850
                     const auto& trx      = trx_meta.trx();
                     validate_referenced_accounts(trx);
851
                     validate_uniqueness(trx);
852 853
                     FC_ASSERT( !should_check_signatures() || trx_meta.signing_keys,
                                "signing_keys missing from transaction_metadata of an input transaction" );
854 855 856 857 858
                     auto delay = check_authorization( trx.actions, trx.context_free_actions,
                                                       should_check_signatures() ? *trx_meta.signing_keys : flat_set<public_key_type>() );
                     validate_expiration_not_too_far(trx, head_block_time() + delay );

                     trx_meta.delay = delay;
B
Bart Wyatt 已提交
859
                     return &input_metas.at(itr->second);
B
Bart Wyatt 已提交
860
                  } else {
861 862
                     const auto* gtrx = _db.find<generated_transaction_object,by_trx_id>(receipt.id);
                     if (gtrx != nullptr) {
863
                        //ilog( "defer" );
864
                        auto trx = fc::raw::unpack<deferred_transaction>(gtrx->packed_trx.data(), gtrx->packed_trx.size());
865
                        FC_ASSERT( trx.execute_after <= head_block_time() , "deferred transaction executed prematurely" );
866 867
                        validate_not_expired( trx );
                        validate_uniqueness( trx );
868
                        _temp.emplace(trx, gtrx->published, trx.sender, trx.sender_id, gtrx->packed_trx.data(), gtrx->packed_trx.size() );
869
                        _destroy_generated_transaction(*gtrx);
870 871
                        return &*_temp;
                     } else {
872
                        //ilog( "implicit" );
B
Bucky Kittinger 已提交
873 874 875 876 877
                        for ( size_t i=0; i < next_block_trace.implicit_transactions.size(); i++ ) {
                           if ( input_metas[i].id == receipt.id )
                              return &input_metas[i];
                        }
                        FC_ASSERT(false, "implicit transaction not found ${trx}", ("trx", receipt));
878
                     }
879
                  }
880
               };
B
Bart Wyatt 已提交
881

882
               auto *mtrx = make_metadata();
883

884 885 886 887 888
               mtrx->region_id = r.region;
               mtrx->cycle_index = cycle_index;
               mtrx->shard_index = shard_index;
               mtrx->allowed_read_locks.emplace(&shard.read_locks);
               mtrx->allowed_write_locks.emplace(&shard.write_locks);
889
               mtrx->processing_deadline = processing_deadline;
B
Bart Wyatt 已提交
890

891 892 893 894 895 896 897 898 899
               if( mtrx->delay.count() == 0 ) {
                  s_trace.transaction_traces.emplace_back(_apply_transaction(*mtrx));
                  record_locks_for_data_access(s_trace.transaction_traces.back(), used_read_locks, used_write_locks);
               } else {
                  s_trace.transaction_traces.emplace_back(delayed_transaction_processing(*mtrx));
               }
               EOS_ASSERT( receipt.status == s_trace.transaction_traces.back().status, tx_receipt_inconsistent_status,
                           "Received status of transaction from block (${rstatus}) does not match the applied transaction's status (${astatus})",
                           ("rstatus",receipt.status)("astatus",s_trace.transaction_traces.back().status) );
B
Bart Wyatt 已提交
900

901
            } /// for each transaction id
N
Nathan Hourt 已提交
902

B
Bart Wyatt 已提交
903
            EOS_ASSERT( boost::equal( used_read_locks, shard.read_locks ),
B
Bart Wyatt 已提交
904
               block_lock_exception, "Read locks for executing shard: ${s} do not match those listed in the block", ("s", shard_index));
905
            EOS_ASSERT( boost::equal( used_write_locks, shard.write_locks ),
B
Bart Wyatt 已提交
906 907
               block_lock_exception, "Write locks for executing shard: ${s} do not match those listed in the block", ("s", shard_index));

908
            s_trace.finalize_shard();
909 910
            c_trace.shard_traces.emplace_back(move(s_trace));
         } /// for each shard
D
Daniel Larimer 已提交
911

912 913 914
         _apply_cycle_trace(c_trace);
         r_trace.cycle_traces.emplace_back(move(c_trace));
      } /// for each cycle
D
Daniel Larimer 已提交
915

916 917
      next_block_trace.region_traces.emplace_back(move(r_trace));
   } /// for each region
N
Nathan Hourt 已提交
918

919
   FC_ASSERT(next_block.action_mroot == next_block_trace.calculate_action_merkle_root());
920
   FC_ASSERT( transaction_metadata::calculate_transaction_merkle_root(input_metas) == next_block.transaction_mroot, "merkle root does not match" );
N
Nathan Hourt 已提交
921

922
   _finalize_block( next_block_trace, signing_producer );
923
} FC_CAPTURE_AND_RETHROW( (next_block.block_num()) )  }
D
Daniel Larimer 已提交
924

925 926
flat_set<public_key_type> chain_controller::get_required_keys(const transaction& trx,
                                                              const flat_set<public_key_type>& candidate_keys)const
D
Daniel Larimer 已提交
927
{
928
   auto checker = make_auth_checker( [&](const permission_level& p){ return get_permission(p).auth; },
929
                                     noop_permission_visitor(),
930 931
                                     get_global_properties().configuration.max_authority_depth,
                                     candidate_keys);
932

933
   for (const auto& act : trx.actions ) {
D
Daniel Larimer 已提交
934 935 936
      for (const auto& declared_auth : act.authorization) {
         if (!checker.satisfied(declared_auth)) {
            EOS_ASSERT(checker.satisfied(declared_auth), tx_missing_sigs,
D
Daniel Larimer 已提交
937
                       "transaction declares authority '${auth}', but does not have signatures for it.",
D
Daniel Larimer 已提交
938
                       ("auth", declared_auth));
939 940 941 942 943 944 945
         }
      }
   }

   return checker.used_keys();
}

M
Matias Romeo 已提交
946

947 948
class permission_visitor {
public:
949 950 951 952
   permission_visitor(const chain_controller& controller)
   : _chain_controller(controller) {
      _max_delay_stack.emplace_back();
   }
953 954 955

   void operator()(const permission_level& perm_level) {
      const auto obj = _chain_controller.get_permission(perm_level);
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
      if( _max_delay_stack.back() < obj.delay )
         _max_delay_stack.back() = obj.delay;
   }

   void push_undo() {
      _max_delay_stack.emplace_back( _max_delay_stack.back() );
   }

   void pop_undo() {
      FC_ASSERT( _max_delay_stack.size() >= 2, "invariant failure in permission_visitor" );
      _max_delay_stack.pop_back();
   }

   void squash_undo() {
      FC_ASSERT( _max_delay_stack.size() >= 2, "invariant failure in permission_visitor" );
      auto delay_to_keep = _max_delay_stack.back();
      _max_delay_stack.pop_back();
      _max_delay_stack.back() = delay_to_keep;
   }

   fc::microseconds get_max_delay() const {
      FC_ASSERT( _max_delay_stack.size() == 1, "invariant failure in permission_visitor" );
      return _max_delay_stack.back();
979 980 981 982
   }

private:
   const chain_controller& _chain_controller;
983
   vector<fc::microseconds> _max_delay_stack;
984 985
};

986 987 988 989 990
fc::microseconds chain_controller::check_authorization( const vector<action>& actions,
                                                        const vector<action>& context_free_actions,
                                                        const flat_set<public_key_type>& provided_keys,
                                                        bool allow_unused_signatures,
                                                        flat_set<account_name> provided_accounts )const
M
Matias Romeo 已提交
991

D
Daniel Larimer 已提交
992
{
993
   auto checker = make_auth_checker( [&](const permission_level& p){ return get_permission(p).auth; },
994
                                     permission_visitor(*this),
995
                                     get_global_properties().configuration.max_authority_depth,
996 997
                                     provided_keys, provided_accounts );

998
   fc::microseconds max_delay;
N
Nathan Hourt 已提交
999

1000
   for( const auto& act : actions ) {
1001
      for( const auto& declared_auth : act.authorization ) {
D
Daniel Larimer 已提交
1002

1003
         // check a minimum permission if one is set, otherwise assume the contract code will validate
B
Bart Wyatt 已提交
1004
         auto min_permission_name = lookup_minimum_permission(declared_auth.actor, act.account, act.name);
1005
         if( !min_permission_name ) {
1006
            // for updateauth actions, need to determine the permission that is changing
1007
            if( act.account == config::system_account_name && act.name == contracts::updateauth::get_name() ) {
1008 1009
               auto update = act.data_as<contracts::updateauth>();
               const auto permission_to_change = _db.find<permission_object, by_owner>(boost::make_tuple(update.account, update.permission));
1010 1011
               if( permission_to_change != nullptr ) {
                  // Only changes to permissions need to possibly be delayed. New permissions can be added immediately.
1012 1013 1014 1015
                  min_permission_name = update.permission;
               }
            }
         }
1016
         if( min_permission_name ) {
1017
            const auto& min_permission = _db.get<permission_object, by_owner>(boost::make_tuple(declared_auth.actor, *min_permission_name));
1018 1019 1020 1021 1022 1023 1024 1025
            const auto& index = _db.get_index<permission_index>().indices();
            const optional<fc::microseconds> delay = get_permission(declared_auth).satisfies(min_permission, index);
            EOS_ASSERT( delay.valid(),
                        tx_irrelevant_auth,
                        "action declares irrelevant authority '${auth}'; minimum authority is ${min}",
                        ("auth", declared_auth)("min", min_permission.name) );
            if( max_delay < *delay )
               max_delay = *delay;
N
Nathan Hourt 已提交
1026
         }
1027

1028
         if( act.account == config::system_account_name ) {
1029 1030
            // for link changes, we need to also determine the delay associated with an existing link that is being
            // moved or removed
1031
            if( act.name == contracts::linkauth::get_name() ) {
1032
               auto link = act.data_as<contracts::linkauth>();
1033
               if( declared_auth.actor == link.account ) {
1034
                  const auto linked_permission_name = lookup_linked_permission(link.account, link.code, link.type);
1035
                  if( linked_permission_name.valid() && *linked_permission_name != config::eosio_any_name ) {
1036 1037
                     const auto& linked_permission = _db.get<permission_object, by_owner>(boost::make_tuple(link.account, *linked_permission_name));
                     const auto& index = _db.get_index<permission_index>().indices();
1038 1039
                     const optional<fc::microseconds> delay = get_permission(declared_auth).satisfies(linked_permission, index);
                     if( delay.valid() && max_delay < *delay )
1040 1041 1042
                        max_delay = *delay;
                  } // else it is only a new link, so don't need to delay
               }
1043
            } else if( act.name == contracts::unlinkauth::get_name() ) {
1044
               auto unlink = act.data_as<contracts::unlinkauth>();
1045
               if( declared_auth.actor == unlink.account ) {
1046
                  const auto unlinked_permission_name = lookup_linked_permission(unlink.account, unlink.code, unlink.type);
1047
                  if( unlinked_permission_name.valid() && *unlinked_permission_name != config::eosio_any_name ) {
1048 1049
                     const auto& unlinked_permission = _db.get<permission_object, by_owner>(boost::make_tuple(unlink.account, *unlinked_permission_name));
                     const auto& index = _db.get_index<permission_index>().indices();
1050 1051
                     const optional<fc::microseconds> delay = get_permission(declared_auth).satisfies(unlinked_permission, index);
                     if( delay.valid() && max_delay < *delay )
1052 1053 1054
                        max_delay = *delay;
                  }
               }
1055
            }
N
Nathan Hourt 已提交
1056
         }
1057

1058
         if( should_check_signatures() ) {
D
Daniel Larimer 已提交
1059
            EOS_ASSERT(checker.satisfied(declared_auth), tx_missing_sigs,
D
Daniel Larimer 已提交
1060
                       "transaction declares authority '${auth}', but does not have signatures for it.",
D
Daniel Larimer 已提交
1061
                       ("auth", declared_auth));
N
Nathan Hourt 已提交
1062 1063
         }
      }
1064
   }
N
Nathan Hourt 已提交
1065

1066
   for( const auto& act : context_free_actions ) {
1067 1068
      if (act.account == config::system_account_name && act.name == contracts::mindelay::get_name()) {
         const auto mindelay = act.data_as<contracts::mindelay>();
1069 1070
         auto delay = fc::seconds(mindelay.delay);
         if( max_delay < delay )
1071 1072
            max_delay = delay;
      }
1073
   }
N
Nathan Hourt 已提交
1074

1075 1076 1077 1078 1079
   if( !allow_unused_signatures && should_check_signatures() ) {
      EOS_ASSERT( checker.all_keys_used(), tx_irrelevant_sig,
                  "transaction bears irrelevant signatures from these keys: ${keys}",
                  ("keys", checker.unused_keys()) );
   }
1080 1081

   const auto checker_max_delay = checker.get_permission_visitor().get_max_delay();
1082
   if( max_delay < checker_max_delay )
1083 1084 1085
      max_delay = checker_max_delay;

   return max_delay;
N
Nathan Hourt 已提交
1086 1087
}

M
Matias Romeo 已提交
1088 1089 1090 1091 1092
bool chain_controller::check_authorization( account_name account, permission_name permission,
                                         flat_set<public_key_type> provided_keys,
                                         bool allow_unused_signatures)const
{
   auto checker = make_auth_checker( [&](const permission_level& p){ return get_permission(p).auth; },
1093 1094 1095
                                     noop_permission_visitor(),
                                     get_global_properties().configuration.max_authority_depth,
                                     provided_keys);
M
Matias Romeo 已提交
1096 1097 1098

   auto satisfied = checker.satisfied({account, permission});

1099
   if( satisfied && !allow_unused_signatures ) {
M
Matias Romeo 已提交
1100 1101 1102 1103 1104 1105 1106 1107
      EOS_ASSERT(checker.all_keys_used(), tx_irrelevant_sig,
                 "irrelevant signatures from these keys: ${keys}",
                 ("keys", checker.unused_keys()));
   }

   return satisfied;
}

1108 1109 1110 1111
fc::microseconds chain_controller::check_transaction_authorization(const transaction& trx,
                                                                   const vector<signature_type>& signatures,
                                                                   const vector<bytes>& cfd,
                                                                   bool allow_unused_signatures)const
1112
{
1113
   if( should_check_signatures() ) {
1114 1115 1116
      return check_authorization( trx.actions, trx.context_free_actions,
                                  trx.get_signature_keys( signatures, chain_id_type{}, cfd, allow_unused_signatures ),
                                  allow_unused_signatures );
1117
   } else {
1118
      return check_authorization( trx.actions, trx.context_free_actions, flat_set<public_key_type>(), true );
1119
   }
1120 1121
}

1122
optional<permission_name> chain_controller::lookup_minimum_permission(account_name authorizer_account,
D
Daniel Larimer 已提交
1123 1124
                                                                    account_name scope,
                                                                    action_name act_name) const {
1125
#warning TODO: this comment sounds like it is expecting a check ("may") somewhere else, but I have not found anything else
1126 1127
   // updateauth is a special case where any permission _may_ be suitable depending
   // on the contents of the action
1128
   if( scope == config::system_account_name && act_name == contracts::updateauth::get_name() ) {
1129 1130 1131
      return optional<permission_name>();
   }

1132 1133
   try {
      optional<permission_name> linked_permission = lookup_linked_permission(authorizer_account, scope, act_name);
1134
      if( !linked_permission )
1135 1136
         return config::active_name;

1137
      if( *linked_permission == config::eosio_any_name )
1138 1139
         return optional<permission_name>();

1140 1141 1142 1143 1144 1145 1146
      return linked_permission;
   } FC_CAPTURE_AND_RETHROW((authorizer_account)(scope)(act_name))
}

optional<permission_name> chain_controller::lookup_linked_permission(account_name authorizer_account,
                                                                     account_name scope,
                                                                     action_name act_name) const {
N
Nathan Hourt 已提交
1147
   try {
D
Daniel Larimer 已提交
1148 1149 1150
      // First look up a specific link for this message act_name
      auto key = boost::make_tuple(authorizer_account, scope, act_name);
      auto link = _db.find<permission_link_object, by_action_name>(key);
1151 1152 1153
      // If no specific link found, check for a contract-wide default
      if (link == nullptr) {
         get<2>(key) = "";
D
Daniel Larimer 已提交
1154
         link = _db.find<permission_link_object, by_action_name>(key);
1155 1156 1157
      }

      // If no specific or default link found, use active permission
D
Daniel Larimer 已提交
1158
      if (link != nullptr) {
1159
         return link->required_permission;
1160 1161
      }
      return optional<permission_name>();
D
Daniel Larimer 已提交
1162 1163

    //  return optional<permission_name>();
D
Daniel Larimer 已提交
1164
   } FC_CAPTURE_AND_RETHROW((authorizer_account)(scope)(act_name))
N
Nathan Hourt 已提交
1165 1166
}

1167
void chain_controller::validate_uniqueness( const transaction& trx )const {
N
Nathan Hourt 已提交
1168
   if( !should_check_for_duplicate_transactions() ) return;
1169
   auto transaction = _db.find<transaction_object, by_trx_id>(trx.id());
1170
   EOS_ASSERT(transaction == nullptr, tx_duplicate, "Transaction is not unique");
1171
}
1172

1173 1174
void chain_controller::record_transaction(const transaction& trx)
{
1175 1176 1177 1178 1179 1180 1181
   try {
       _db.create<transaction_object>([&](transaction_object& transaction) {
           transaction.trx_id = trx.id();
           transaction.expiration = trx.expiration;
       });
   } catch ( ... ) {
       EOS_ASSERT( false, transaction_exception,
1182
                  "duplicate transaction ${id}",
1183 1184
                  ("id", trx.id() ) );
   }
1185
}
1186

B
Bart Wyatt 已提交
1187 1188
static uint32_t calculate_transaction_cpu_usage( const transaction_trace& trace, const transaction_metadata& meta, const chain_config& chain_configuration ) {
   // calculate the sum of all actions retired
1189
   uint32_t action_cpu_usage = 0;
1190
   uint32_t context_free_actual_cpu_usage = 0;
1191
   for (const auto &at: trace.action_traces) {
1192 1193 1194 1195 1196 1197 1198 1199 1200
      if (at.context_free) {
         context_free_actual_cpu_usage += chain_configuration.base_per_action_cpu_usage + at.cpu_usage;
      } else {
         action_cpu_usage += chain_configuration.base_per_action_cpu_usage + at.cpu_usage;
         if (at.receiver == config::system_account_name &&
             at.act.account == config::system_account_name &&
             at.act.name == N(setcode)) {
            action_cpu_usage += chain_configuration.base_setcode_cpu_usage;
         }
1201 1202 1203
      }
   }

1204

1205
   // charge a system controlled amount for signature verification/recovery
B
Bart Wyatt 已提交
1206
   uint32_t signature_cpu_usage = 0;
1207
   if( meta.signing_keys ) {
B
Bart Wyatt 已提交
1208
      signature_cpu_usage = (uint32_t)meta.signing_keys->size() * chain_configuration.per_signature_cpu_usage;
1209 1210
   }

B
Bart Wyatt 已提交
1211
   // charge a system discounted amount for context free cpu usage
1212 1213
   //uint32_t context_free_cpu_commitment = (uint32_t)(meta.trx().kcpu_usage.value * 1024UL);
   /*
1214 1215 1216 1217
   EOS_ASSERT(context_free_actual_cpu_usage <= context_free_cpu_commitment,
              tx_resource_exhausted,
              "Transaction context free actions can not fit into the cpu usage committed to by the transaction's header! [usage=${usage},commitment=${commit}]",
              ("usage", context_free_actual_cpu_usage)("commit", context_free_cpu_commitment) );
1218
              */
1219

1220
   uint32_t context_free_cpu_usage = (uint32_t)((uint64_t)context_free_actual_cpu_usage * chain_configuration.context_free_discount_cpu_usage_num / chain_configuration.context_free_discount_cpu_usage_den);
B
Bart Wyatt 已提交
1221

1222
   auto actual_usage = chain_configuration.base_per_transaction_cpu_usage +
B
Bart Wyatt 已提交
1223 1224 1225
          action_cpu_usage +
          context_free_cpu_usage +
          signature_cpu_usage;
1226

1227

1228 1229 1230
   if( meta.trx().kcpu_usage.value == 0 ) {
      return actual_usage;
   } else {
1231 1232 1233 1234 1235
      EOS_ASSERT(meta.trx().kcpu_usage.value <= UINT32_MAX / 1024UL, transaction_exception, "declared kcpu usage overflows when expanded to cpu usage");
      uint32_t declared_value = (uint32_t)(meta.trx().kcpu_usage.value * 1024UL);

      EOS_ASSERT( actual_usage <= declared_value, tx_resource_exhausted, "transaction did not declare sufficient cpu usage: ${actual} > ${declared}", ("actual", actual_usage)("declared",declared_value) );
      return declared_value;
1236
   }
B
Bart Wyatt 已提交
1237 1238
}

1239
static uint32_t calculate_transaction_net_usage( const transaction_trace& trace, const transaction_metadata& meta, const chain_config& chain_configuration ) {
B
Bart Wyatt 已提交
1240 1241
   // charge a system controlled per-lock overhead to account for shard bloat
   uint32_t lock_net_usage = uint32_t(trace.read_locks.size() + trace.write_locks.size()) * chain_configuration.per_lock_net_usage;
1242 1243 1244

   EOS_ASSERT(meta.trx().net_usage_words.value <= (UINT32_MAX - chain_configuration.base_per_transaction_net_usage - lock_net_usage) / 8UL, transaction_exception, "declared net_usage_words overflows when expanded to net usage");
   uint32_t trx_wire_net_usage = (uint32_t)(meta.trx().net_usage_words.value * 8UL);
B
Bart Wyatt 已提交
1245 1246

   return chain_configuration.base_per_transaction_net_usage +
1247 1248
          trx_wire_net_usage +
          lock_net_usage;
B
Bart Wyatt 已提交
1249 1250 1251 1252 1253 1254
}

void chain_controller::update_resource_usage( transaction_trace& trace, const transaction_metadata& meta ) {
   const auto& chain_configuration = get_global_properties().configuration;

   trace.cpu_usage = calculate_transaction_cpu_usage(trace, meta, chain_configuration);
1255
   trace.net_usage = calculate_transaction_net_usage(trace, meta, chain_configuration);
B
Bart Wyatt 已提交
1256 1257 1258 1259

   // enforce that the system controlled per tx limits are not violated
   EOS_ASSERT(trace.cpu_usage <= chain_configuration.max_transaction_cpu_usage,
              tx_resource_exhausted, "Transaction exceeds the maximum cpu usage [used: ${used}, max: ${max}]",
1260
              ("used", trace.cpu_usage)("max", chain_configuration.max_transaction_cpu_usage));
B
Bart Wyatt 已提交
1261 1262 1263

   EOS_ASSERT(trace.net_usage <= chain_configuration.max_transaction_net_usage,
              tx_resource_exhausted, "Transaction exceeds the maximum net usage [used: ${used}, max: ${max}]",
1264
              ("used", trace.net_usage)("max", chain_configuration.max_transaction_net_usage));
B
Bart Wyatt 已提交
1265

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
   // determine the accounts to bill
   set<std::pair<account_name, permission_name>> authorizations;
   for( const auto& act : meta.trx().actions )
      for( const auto& auth : act.authorization )
         authorizations.emplace( auth.actor, auth.permission );


   vector<account_name> bill_to_accounts;
   bill_to_accounts.reserve(authorizations.size());
   for( const auto& ap : authorizations ) {
1276
      bill_to_accounts.push_back(ap.first);
1277 1278
   }

1279 1280 1281
   // for account usage, the ordinal is based on possible blocks not actual blocks.  This means that as blocks are
   // skipped account usage will still decay.
   uint32_t ordinal = (uint32_t)(head_block_time().time_since_epoch().count() / fc::milliseconds(config::block_interval_ms).count());
1282
   _resource_limits.add_transaction_usage(bill_to_accounts, trace.cpu_usage, trace.net_usage, ordinal);
1283 1284
}

1285

D
Daniel Larimer 已提交
1286
void chain_controller::validate_tapos(const transaction& trx)const {
N
Nathan Hourt 已提交
1287
   if (!should_check_tapos()) return;
1288

D
Daniel Larimer 已提交
1289
   const auto& tapos_block_summary = _db.get<block_summary_object>((uint16_t)trx.ref_block_num);
1290 1291

   //Verify TaPoS block summary has correct ID prefix, and that this block's time is not past the expiration
1292 1293
   EOS_ASSERT(trx.verify_reference_block(tapos_block_summary.block_id), invalid_ref_block_exception,
              "Transaction's reference block did not match. Is this transaction from a different fork?",
N
Nathan Hourt 已提交
1294 1295
              ("tapos_summary", tapos_block_summary));
}
1296

1297 1298
void chain_controller::validate_referenced_accounts( const transaction& trx )const
{ try {
D
Daniel Larimer 已提交
1299
   for( const auto& act : trx.actions ) {
B
Bart Wyatt 已提交
1300
      require_account(act.account);
D
Daniel Larimer 已提交
1301
      for (const auto& auth : act.authorization )
D
Daniel Larimer 已提交
1302
         require_account(auth.actor);
1303
   }
D
Daniel Larimer 已提交
1304
} FC_CAPTURE_AND_RETHROW() }
D
Daniel Larimer 已提交
1305

1306
void chain_controller::validate_not_expired( const transaction& trx )const
1307
{ try {
D
Daniel Larimer 已提交
1308
   fc::time_point now = head_block_time();
1309

1310
   EOS_ASSERT( now < time_point(trx.expiration),
1311 1312
               expired_tx_exception,
               "Transaction is expired, now is ${now}, expiration is ${trx.exp}",
1313
               ("now",now)("trx.expiration",trx.expiration) );
1314 1315 1316
} FC_CAPTURE_AND_RETHROW((trx)) }

void chain_controller::validate_expiration_not_too_far( const transaction& trx, fc::time_point reference_time )const
1317
{ try {
D
Daniel Larimer 已提交
1318
   const auto& chain_configuration = get_global_properties().configuration;
1319

1320 1321
   EOS_ASSERT( time_point(trx.expiration) <= reference_time + fc::seconds(chain_configuration.max_transaction_lifetime),
               tx_exp_too_far_exception,
1322 1323 1324 1325
               "Transaction expiration is too far in the future relative to the reference time of ${reference_time}, "
               "expiration is ${trx.expiration} and the maximum transaction lifetime is ${max_til_exp} seconds",
               ("trx.expiration",trx.expiration)("reference_time",reference_time)
               ("max_til_exp",chain_configuration.max_transaction_lifetime) );
1326
} FC_CAPTURE_AND_RETHROW((trx)) }
1327

1328

1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
void chain_controller::validate_transaction_without_state( const transaction& trx )const
{ try {
   EOS_ASSERT( !trx.actions.empty(), tx_no_action, "transaction must have at least one action" );

   // Check for at least one authorization in the context-aware actions
   bool has_auth = false;
   for( const auto& act : trx.actions ) {
      has_auth |= !act.authorization.empty();
      if( has_auth ) break;
   }
   EOS_ASSERT( has_auth, tx_no_auths, "transaction must have at least one authorization" );

   // Check that there are no authorizations in any of the context-free actions
   for (const auto &act : trx.context_free_actions) {
      EOS_ASSERT( act.authorization.empty(), cfa_irrelevant_auth, "context-free actions cannot require authorization" );
   }
1345
} FC_CAPTURE_AND_RETHROW((trx)) }
1346

1347 1348
void chain_controller::validate_transaction_with_minimal_state( const transaction& trx )const
{ try {
1349
   validate_transaction_without_state(trx);
1350 1351
   validate_not_expired(trx);
   validate_tapos(trx);
1352
} FC_CAPTURE_AND_RETHROW((trx)) }
1353

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
void chain_controller::validate_transaction_with_minimal_state( const packed_transaction& packed_trx, const transaction* trx_ptr )const
{ try {
   transaction temp;
   if( trx_ptr == nullptr ) {
      temp = packed_trx.get_transaction();
      trx_ptr = &temp;
   }

   validate_transaction_with_minimal_state(*trx_ptr);

   // enforce that the header is accurate as a commitment to net_usage
   uint32_t cfa_sig_net_usage = (uint32_t)(packed_trx.context_free_data.size() + fc::raw::pack_size(packed_trx.signatures));
   uint32_t net_usage_commitment = trx_ptr->net_usage_words.value * 8U;
   uint32_t packed_size = (uint32_t)packed_trx.data.size();
   uint32_t net_usage = cfa_sig_net_usage + packed_size;
   EOS_ASSERT(net_usage <= net_usage_commitment,
                tx_resource_exhausted,
                "Packed Transaction and associated data does not fit into the space committed to by the transaction's header! [usage=${usage},commitment=${commit}]",
                ("usage", net_usage)("commit", net_usage_commitment));
} FC_CAPTURE_AND_RETHROW((packed_trx)) }
1374

1375 1376
void chain_controller::require_scope( const scope_name& scope )const {
   switch( uint64_t(scope) ) {
1377 1378
      case config::eosio_all_scope:
      case config::eosio_auth_scope:
1379 1380 1381 1382 1383 1384
         return; /// built in scopes
      default:
         require_account(scope);
   }
}

D
Daniel Larimer 已提交
1385
void chain_controller::require_account(const account_name& name) const {
N
Nathan Hourt 已提交
1386 1387 1388
   auto account = _db.find<account_object, by_name>(name);
   FC_ASSERT(account != nullptr, "Account not found: ${name}", ("name", name));
}
N
Nathan Hourt 已提交
1389

1390
const producer_object& chain_controller::validate_block_header(uint32_t skip, const signed_block& next_block)const {
1391 1392
   EOS_ASSERT(head_block_id() == next_block.previous, block_validate_exception, "",
              ("head_block_id",head_block_id())("next.prev",next_block.previous));
D
Daniel Larimer 已提交
1393
   EOS_ASSERT(head_block_time() < (fc::time_point)next_block.timestamp, block_validate_exception, "",
1394
              ("head_block_time",head_block_time())("next",next_block.timestamp)("blocknum",next_block.block_num()));
K
Kevin Heifner 已提交
1395
   if (((fc::time_point)next_block.timestamp) > head_block_time() + fc::microseconds(config::block_interval_ms*1000)) {
1396
      elog("head_block_time ${h}, next_block ${t}, block_interval ${bi}",
1397 1398 1399
           ("h", head_block_time())("t", next_block.timestamp)("bi", config::block_interval_ms));
      elog("Did not produce block within block_interval ${bi}ms, took ${t}ms)",
           ("bi", config::block_interval_ms)("t", (time_point(next_block.timestamp) - head_block_time()).count() / 1000));
1400
   }
1401

1402

1403
   if( !is_start_of_round( next_block.block_num() ) )  {
D
Daniel Larimer 已提交
1404
      EOS_ASSERT(!next_block.new_producers, block_validate_exception,
1405
                 "Producer changes may only occur at the end of a round.");
N
Nathan Hourt 已提交
1406
   }
1407

D
Daniel Larimer 已提交
1408
   const producer_object& producer = get_producer(get_scheduled_producer(get_slot_at_time(next_block.timestamp)));
N
Nathan Hourt 已提交
1409

N
Nathan Hourt 已提交
1410
   if(!(skip&skip_producer_signature))
1411 1412 1413
      EOS_ASSERT(next_block.validate_signee(producer.signing_key), block_validate_exception,
                 "Incorrect block producer key: expected ${e} but got ${a}",
                 ("e", producer.signing_key)("a", public_key_type(next_block.signee())));
N
Nathan Hourt 已提交
1414

1415
   if(!(skip&skip_producer_schedule_check)) {
1416 1417 1418
      EOS_ASSERT(next_block.producer == producer.owner, block_validate_exception,
                 "Producer produced block at wrong time",
                 ("block producer",next_block.producer)("scheduled producer",producer.owner));
N
Nathan Hourt 已提交
1419 1420
   }

1421
   EOS_ASSERT( next_block.schedule_version == get_global_properties().active_producers.version, block_validate_exception, "wrong producer schedule version specified" );
1422

N
Nathan Hourt 已提交
1423 1424 1425
   return producer;
}

1426
void chain_controller::create_block_summary(const signed_block& next_block) {
1427
   auto sid = next_block.block_num() & 0xffff;
1428
   _db.modify( _db.get<block_summary_object,by_id>(sid), [&](block_summary_object& p) {
1429 1430
         p.block_id = next_block.id();
   });
N
Nathan Hourt 已提交
1431 1432
}

1433 1434
/**
 *  Takes the top config::producer_count producers by total vote excluding any producer whose
1435
 *  block_signing_key is null.
1436 1437
 */
producer_schedule_type chain_controller::_calculate_producer_schedule()const {
1438
   producer_schedule_type schedule = get_global_properties().new_active_producers;
1439

1440 1441 1442 1443
   const auto& hps = _head_producer_schedule();
   schedule.version = hps.version;
   if( hps != schedule )
      ++schedule.version;
1444 1445 1446 1447 1448 1449
   return schedule;
}

/**
 *  Returns the most recent and/or pending producer schedule
 */
D
Daniel Larimer 已提交
1450
const shared_producer_schedule_type& chain_controller::_head_producer_schedule()const {
1451
   const auto& gpo = get_global_properties();
1452
   if( gpo.pending_active_producers.size() )
1453 1454 1455 1456
      return gpo.pending_active_producers.back().second;
   return gpo.active_producers;
}

1457
void chain_controller::update_global_properties(const signed_block& b) { try {
1458 1459
   // If we're at the end of a round, update the BlockchainConfiguration, producer schedule
   // and "producers" special account authority
1460 1461 1462 1463 1464
   if( is_start_of_round( b.block_num() ) ) {
      auto schedule = _calculate_producer_schedule();
      if( b.new_producers )
      {
          FC_ASSERT( schedule == *b.new_producers, "pending producer set different than expected" );
1465 1466
      }
      const auto& gpo = get_global_properties();
1467 1468 1469

      if( _head_producer_schedule() != schedule ) {
         FC_ASSERT( b.new_producers, "pending producer set changed but block didn't indicate it" );
1470
      }
1471 1472 1473 1474
      _db.modify( gpo, [&]( auto& props ) {
         if( props.pending_active_producers.size() && props.pending_active_producers.back().first == b.block_num() )
            props.pending_active_producers.back().second = schedule;
         else
D
Daniel Larimer 已提交
1475 1476 1477 1478 1479
         {
            props.pending_active_producers.emplace_back( props.pending_active_producers.get_allocator() );// props.pending_active_producers.size()+1, props.pending_active_producers.get_allocator() );
            auto& back = props.pending_active_producers.back();
            back.first = b.block_num();
            back.second = schedule;
1480

D
Daniel Larimer 已提交
1481
         }
1482 1483
      });

1484

1485
      auto active_producers_authority = authority(config::producers_authority_threshold, {}, {});
1486
      for(auto& name : gpo.active_producers.producers ) {
1487
         active_producers_authority.accounts.push_back({{name.producer_name, config::active_name}, 1});
1488 1489
      }

1490
      auto& po = _db.get<permission_object, by_owner>( boost::make_tuple(config::producers_account_name,
1491
                                                                         config::active_name ) );
1492 1493 1494
      _db.modify(po,[active_producers_authority] (permission_object& po) {
         po.auth = active_producers_authority;
      });
1495
   }
1496
} FC_CAPTURE_AND_RETHROW() }
1497

1498
void chain_controller::add_checkpoints( const flat_map<uint32_t,block_id_type>& checkpts ) {
1499
   for (const auto& i : checkpts)
N
Nathan Hourt 已提交
1500 1501 1502
      _checkpoints[i.first] = i.second;
}

1503
bool chain_controller::before_last_checkpoint()const {
N
Nathan Hourt 已提交
1504 1505 1506
   return (_checkpoints.size() > 0) && (_checkpoints.rbegin()->first >= head_block_num());
}

1507
const global_property_object& chain_controller::get_global_properties()const {
1508
   return _db.get<global_property_object>();
N
Nathan Hourt 已提交
1509 1510
}

1511
const dynamic_global_property_object&chain_controller::get_dynamic_global_properties() const {
1512
   return _db.get<dynamic_global_property_object>();
N
Nathan Hourt 已提交
1513 1514
}

D
Daniel Larimer 已提交
1515
time_point chain_controller::head_block_time()const {
N
Nathan Hourt 已提交
1516 1517 1518
   return get_dynamic_global_properties().time;
}

1519
uint32_t chain_controller::head_block_num()const {
N
Nathan Hourt 已提交
1520 1521 1522
   return get_dynamic_global_properties().head_block_number;
}

1523
block_id_type chain_controller::head_block_id()const {
N
Nathan Hourt 已提交
1524 1525 1526
   return get_dynamic_global_properties().head_block_id;
}

D
Daniel Larimer 已提交
1527
account_name chain_controller::head_block_producer() const {
1528 1529 1530
   auto b = _fork_db.fetch_block(head_block_id());
   if( b ) return b->data.producer;

N
Nathan Hourt 已提交
1531
   if (auto head_block = fetch_block_by_id(head_block_id()))
1532
      return head_block->producer;
N
Nathan Hourt 已提交
1533 1534 1535
   return {};
}

1536
const producer_object& chain_controller::get_producer(const account_name& owner_name) const
D
Daniel Larimer 已提交
1537
{ try {
B
Bart Wyatt 已提交
1538
   return _db.get<producer_object, by_owner>(owner_name);
D
Daniel Larimer 已提交
1539
} FC_CAPTURE_AND_RETHROW( (owner_name) ) }
N
Nathan Hourt 已提交
1540

1541
const permission_object&   chain_controller::get_permission( const permission_level& level )const
1542
{ try {
1543
   FC_ASSERT( !level.actor.empty() && !level.permission.empty(), "Invalid permission" );
1544
   return _db.get<permission_object, by_owner>( boost::make_tuple(level.actor,level.permission) );
1545
} EOS_RETHROW_EXCEPTIONS( chain::permission_query_exception, "Failed to retrieve permission: ${level}", ("level", level) ) }
1546

1547
uint32_t chain_controller::last_irreversible_block_num() const {
N
Nathan Hourt 已提交
1548
   return get_dynamic_global_properties().last_irreversible_block_num;
N
Nathan Hourt 已提交
1549 1550
}

D
Daniel Larimer 已提交
1551
void chain_controller::_initialize_indexes() {
1552 1553
   _db.add_index<account_index>();
   _db.add_index<permission_index>();
1554
   _db.add_index<permission_usage_index>();
1555
   _db.add_index<permission_link_index>();
1556
   _db.add_index<action_permission_index>();
D
Daniel Larimer 已提交
1557 1558 1559



1560 1561
   _db.add_index<contracts::table_id_multi_index>();
   _db.add_index<contracts::key_value_index>();
D
Daniel Larimer 已提交
1562
   _db.add_index<contracts::index64_index>();
1563
   _db.add_index<contracts::index128_index>();
1564
   _db.add_index<contracts::index256_index>();
A
arhag 已提交
1565
   _db.add_index<contracts::index_double_index>();
D
Daniel Larimer 已提交
1566

1567 1568 1569 1570
   _db.add_index<global_property_multi_index>();
   _db.add_index<dynamic_global_property_multi_index>();
   _db.add_index<block_summary_multi_index>();
   _db.add_index<transaction_multi_index>();
1571
   _db.add_index<generated_transaction_multi_index>();
1572
   _db.add_index<producer_multi_index>();
1573
   _db.add_index<scope_sequence_multi_index>();
N
Nathan Hourt 已提交
1574 1575
}

D
Daniel Larimer 已提交
1576
void chain_controller::_initialize_chain(contracts::chain_initializer& starter)
N
Nathan Hourt 已提交
1577
{ try {
1578
   if (!_db.find<global_property_object>()) {
N
Nathan Hourt 已提交
1579 1580
      _db.with_write_lock([this, &starter] {
         auto initial_timestamp = starter.get_chain_start_time();
D
Daniel Larimer 已提交
1581 1582 1583
         FC_ASSERT(initial_timestamp != time_point(), "Must initialize genesis timestamp." );
         FC_ASSERT( block_timestamp_type(initial_timestamp) == initial_timestamp,
                    "Genesis timestamp must be divisible by config::block_interval_ms" );
N
Nathan Hourt 已提交
1584

1585
         // Create global properties
1586
         const auto& gp = _db.create<global_property_object>([&starter](global_property_object& p) {
N
Nathan Hourt 已提交
1587 1588
            p.configuration = starter.get_chain_start_configuration();
            p.active_producers = starter.get_chain_start_producers();
1589
            p.new_active_producers = starter.get_chain_start_producers();
1590
         });
1591

1592
         _db.create<dynamic_global_property_object>([&](dynamic_global_property_object& p) {
N
Nathan Hourt 已提交
1593
            p.time = initial_timestamp;
A
arhag 已提交
1594
            //p.recent_slots_filled = uint64_t(-1);
1595
         });
N
Nathan Hourt 已提交
1596

1597 1598
         _resource_limits.initialize_chain();

N
Nathan Hourt 已提交
1599
         // Initialize block summary index
1600 1601
         for (int i = 0; i < 0x10000; i++)
            _db.create<block_summary_object>([&](block_summary_object&) {});
N
Nathan Hourt 已提交
1602

B
Bart Wyatt 已提交
1603
         starter.prepare_database(*this, _db);
1604 1605
      });
   }
N
Nathan Hourt 已提交
1606 1607
} FC_CAPTURE_AND_RETHROW() }

N
Nathan Hourt 已提交
1608

1609
void chain_controller::replay() {
1610
   ilog("Replaying blockchain");
N
Nathan Hourt 已提交
1611
   auto start = fc::time_point::now();
K
Kevin Heifner 已提交
1612

K
Kevin Heifner 已提交
1613
   auto on_exit = fc::make_scoped_exit([&_currently_replaying_blocks = _currently_replaying_blocks](){
K
Kevin Heifner 已提交
1614 1615 1616 1617
      _currently_replaying_blocks = false;
   });
   _currently_replaying_blocks = true;

1618 1619 1620
   auto last_block = _block_log.read_head();
   if (!last_block) {
      elog("No blocks in block log; skipping replay");
N
Nathan Hourt 已提交
1621 1622 1623 1624 1625
      return;
   }

   const auto last_block_num = last_block->block_num();

1626
   ilog("Replaying ${n} blocks...", ("n", last_block_num) );
1627 1628 1629 1630 1631
   for (uint32_t i = 1; i <= last_block_num; ++i) {
      if (i % 5000 == 0)
         std::cerr << "   " << double(i*100)/last_block_num << "%   "<<i << " of " <<last_block_num<<"   \n";
      fc::optional<signed_block> block = _block_log.read_block_by_num(i);
      FC_ASSERT(block, "Could not find block #${n} in block_log!", ("n", i));
D
Daniel Larimer 已提交
1632
      _apply_block(*block, skip_producer_signature |
N
Nathan Hourt 已提交
1633 1634 1635 1636
                          skip_transaction_signatures |
                          skip_transaction_dupe_check |
                          skip_tapos_check |
                          skip_producer_schedule_check |
1637 1638
                          skip_authority_check |
                          received_block);
N
Nathan Hourt 已提交
1639 1640
   }
   auto end = fc::time_point::now();
1641 1642
   ilog("Done replaying ${n} blocks, elapsed time: ${t} sec",
        ("n", head_block_num())("t",double((end-start).count())/1000000.0));
N
Nathan Hourt 已提交
1643

1644
   _db.set_revision(head_block_num());
1645
}
N
Nathan Hourt 已提交
1646

D
Daniel Larimer 已提交
1647
void chain_controller::_spinup_db() {
1648 1649 1650 1651 1652
   // Rewind the database to the last irreversible block
   _db.with_write_lock([&] {
      _db.undo_all();
      FC_ASSERT(_db.revision() == head_block_num(), "Chainbase revision does not match head block num",
                ("rev", _db.revision())("head_block", head_block_num()));
1653

1654 1655
   });
}
N
Nathan Hourt 已提交
1656

D
Daniel Larimer 已提交
1657
void chain_controller::_spinup_fork_db()
N
Nathan Hourt 已提交
1658
{
1659 1660 1661 1662 1663 1664 1665 1666
   fc::optional<signed_block> last_block = _block_log.read_head();
   if(last_block.valid()) {
      _fork_db.start_block(*last_block);
      if (last_block->id() != head_block_id()) {
           FC_ASSERT(head_block_num() == 0, "last block ID does not match current chain state",
                     ("last_block->id", last_block->id())("head_block_num",head_block_num()));
      }
   }
N
Nathan Hourt 已提交
1667 1668
}

D
Daniel Larimer 已提交
1669
/*
1670 1671
ProducerRound chain_controller::calculate_next_round(const signed_block& next_block) {
   auto schedule = _admin->get_next_round(_db);
N
Nathan Hourt 已提交
1672 1673 1674 1675
   auto changes = get_global_properties().active_producers - schedule;
   EOS_ASSERT(boost::range::equal(next_block.producer_changes, changes), block_validate_exception,
              "Unexpected round changes in new block header",
              ("expected changes", changes)("block changes", next_block.producer_changes));
1676

P
Pravin 已提交
1677 1678
   fc::time_point tp = (fc::time_point)next_block.timestamp;
   utilities::rand::random rng(tp.sec_since_epoch());
1679 1680
   rng.shuffle(schedule);
   return schedule;
D
Daniel Larimer 已提交
1681
}*/
1682

1683
void chain_controller::update_global_dynamic_data(const signed_block& b) {
1684
   const dynamic_global_property_object& _dgp = _db.get<dynamic_global_property_object>();
N
Nathan Hourt 已提交
1685

1686 1687 1688
   const auto& bmroot = _dgp.block_merkle_root.get_root();
   FC_ASSERT( bmroot == b.block_mroot, "block merkle root does not match expected value" );

P
Pravin 已提交
1689
   uint32_t missed_blocks = head_block_num() == 0? 1 : get_slot_at_time((fc::time_point)b.timestamp);
1690
   assert(missed_blocks != 0);
N
Nathan Hourt 已提交
1691
   missed_blocks--;
N
Nathan Hourt 已提交
1692

1693 1694
//   if (missed_blocks)
//      wlog("Blockchain continuing after gap of ${b} missed blocks", ("b", missed_blocks));
N
Nathan Hourt 已提交
1695

1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
   if (!(_skip_flags & skip_missed_block_penalty)) {
      for (uint32_t i = 0; i < missed_blocks; ++i) {
         const auto &producer_missed = get_producer(get_scheduled_producer(i + 1));
         if (producer_missed.owner != b.producer) {
            /*
            const auto& producer_account = producer_missed.producer_account(*this);
            if( (fc::time_point::now() - b.timestamp) < fc::seconds(30) )
               wlog( "Producer ${name} missed block ${n} around ${t}", ("name",producer_account.name)("n",b.block_num())("t",b.timestamp) );
               */

            _db.modify(producer_missed, [&](producer_object &w) {
               w.total_missed++;
            });
         }
N
Nathan Hourt 已提交
1710 1711 1712
      }
   }

1713 1714
   const auto& props = get_global_properties();

N
Nathan Hourt 已提交
1715
   // dynamic global properties updating
1716
   _db.modify( _dgp, [&]( dynamic_global_property_object& dgp ){
N
Nathan Hourt 已提交
1717 1718 1719
      dgp.head_block_number = b.block_num();
      dgp.head_block_id = b.id();
      dgp.time = b.timestamp;
1720
      dgp.current_producer = b.producer;
N
Nathan Hourt 已提交
1721 1722
      dgp.current_absolute_slot += missed_blocks+1;

A
arhag 已提交
1723
      /*
N
Nathan Hourt 已提交
1724 1725 1726 1727 1728
      // If we've missed more blocks than the bitmap stores, skip calculations and simply reset the bitmap
      if (missed_blocks < sizeof(dgp.recent_slots_filled) * 8) {
         dgp.recent_slots_filled <<= 1;
         dgp.recent_slots_filled += 1;
         dgp.recent_slots_filled <<= missed_blocks;
1729
      } else
1730
         if(config::percent_100 * get_global_properties().active_producers.producers.size() / blocks_per_round() > config::required_producer_participation)
1731 1732 1733
            dgp.recent_slots_filled = uint64_t(-1);
         else
            dgp.recent_slots_filled = 0;
A
arhag 已提交
1734
      */
1735
      dgp.block_merkle_root.append( head_block_id() );
N
Nathan Hourt 已提交
1736 1737 1738 1739 1740
   });

   _fork_db.set_max_size( _dgp.head_block_number - _dgp.last_irreversible_block_num + 1 );
}

1741
void chain_controller::update_signing_producer(const producer_object& signing_producer, const signed_block& new_block)
N
Nathan Hourt 已提交
1742 1743
{
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();
P
Pravin 已提交
1744
   uint64_t new_block_aslot = dpo.current_absolute_slot + get_slot_at_time( (fc::time_point)new_block.timestamp );
N
Nathan Hourt 已提交
1745

1746
   _db.modify( signing_producer, [&]( producer_object& _wit )
N
Nathan Hourt 已提交
1747 1748 1749 1750 1751 1752
   {
      _wit.last_aslot = new_block_aslot;
      _wit.last_confirmed_block_num = new_block.block_num();
   } );
}

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
void chain_controller::update_permission_usage( const transaction_metadata& meta ) {
   // for any transaction not sent by code, update the affirmative last time a given permission was used
   if (!meta.sender) {
      for( const auto& act : meta.trx().actions ) {
         for( const auto& auth : act.authorization ) {
            const auto *puo = _db.find<permission_usage_object, by_account_permission>(boost::make_tuple(auth.actor, auth.permission));
            if (puo) {
               _db.modify(*puo, [this](permission_usage_object &pu) {
                  pu.last_used = head_block_time();
               });
            } else {
               _db.create<permission_usage_object>([this, &auth](permission_usage_object &pu){
                  pu.account = auth.actor;
                  pu.permission = auth.permission;
                  pu.last_used = head_block_time();
               });
            }
         }
      }
   }
}

1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
void chain_controller::update_or_create_producers( const producer_schedule_type& producers ) {
   for ( auto prod : producers.producers ) {
      if ( _db.find<producer_object, by_owner>(prod.producer_name) == nullptr ) {
         _db.create<producer_object>( [&]( auto& pro ) {
            pro.owner       = prod.producer_name;
            pro.signing_key = prod.block_signing_key;
         });
      }
   }
}

1786
void chain_controller::update_last_irreversible_block()
N
Nathan Hourt 已提交
1787 1788 1789 1790
{
   const global_property_object& gpo = get_global_properties();
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();

N
Nathan Hourt 已提交
1791
   vector<const producer_object*> producer_objs;
1792
   producer_objs.reserve(gpo.active_producers.producers.size());
D
Daniel Larimer 已提交
1793

1794
   std::transform(gpo.active_producers.producers.begin(),
1795
                  gpo.active_producers.producers.end(), std::back_inserter(producer_objs),
D
Daniel Larimer 已提交
1796
                  [this](const producer_key& pk) { return &get_producer(pk.producer_name); });
N
Nathan Hourt 已提交
1797

D
Daniel Larimer 已提交
1798
   static_assert(config::irreversible_threshold_percent > 0, "irreversible threshold must be nonzero");
N
Nathan Hourt 已提交
1799

D
Daniel Larimer 已提交
1800
   size_t offset = EOS_PERCENT(producer_objs.size(), config::percent_100- config::irreversible_threshold_percent);
1801 1802
   std::nth_element(producer_objs.begin(), producer_objs.begin() + offset, producer_objs.end(),
      [](const producer_object* a, const producer_object* b) {
N
Nathan Hourt 已提交
1803
         return a->last_confirmed_block_num < b->last_confirmed_block_num;
1804
      });
N
Nathan Hourt 已提交
1805

1806 1807 1808 1809 1810 1811
   uint32_t new_last_irreversible_block_num = producer_objs[offset]->last_confirmed_block_num;
   // TODO: right now the code cannot handle the head block being irreversible for reasons that are purely
   // implementation details.  We can and should remove this special case once the rest of the logic is fixed.
   if (producer_objs.size() == 1) {
      new_last_irreversible_block_num -= 1;
   }
1812

N
Nathan Hourt 已提交
1813

1814
   if (new_last_irreversible_block_num > dpo.last_irreversible_block_num) {
1815
      _db.modify(dpo, [&](dynamic_global_property_object& _dpo) {
N
Nathan Hourt 已提交
1816
         _dpo.last_irreversible_block_num = new_last_irreversible_block_num;
1817
      });
N
Nathan Hourt 已提交
1818
   }
1819 1820

   // Write newly irreversible blocks to disk. First, get the number of the last block on disk...
1821
   auto old_last_irreversible_block = _block_log.head();
1822
   unsigned last_block_on_disk = 0;
1823 1824 1825
   // If this is null, there are no blocks on disk, so the zero is correct
   if (old_last_irreversible_block)
      last_block_on_disk = old_last_irreversible_block->block_num();
1826

1827
   if (last_block_on_disk < new_last_irreversible_block_num) {
1828 1829 1830 1831
      for (auto block_to_write = last_block_on_disk + 1;
           block_to_write <= new_last_irreversible_block_num;
           ++block_to_write) {
         auto block = fetch_block_by_number(block_to_write);
1832
         FC_ASSERT( block, "unable to find last irreversible block to write" );
1833
         _block_log.append(*block);
K
Kevin Heifner 已提交
1834
         applied_irreversible_block(*block);
1835
      }
1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
   }

   if( new_last_irreversible_block_num > last_block_on_disk ) {
      /// TODO: use upper / lower bound to find
      optional<producer_schedule_type> new_producer_schedule;
      for( const auto& item : gpo.pending_active_producers ) {
         if( item.first < new_last_irreversible_block_num ) {
            new_producer_schedule = item.second;
         }
      }
      if( new_producer_schedule ) {
1847
         update_or_create_producers( *new_producer_schedule );
1848
         _db.modify( gpo, [&]( auto& props ){
1849
              boost::range::remove_erase_if(props.pending_active_producers,
1850
                                            [new_last_irreversible_block_num](const typename decltype(props.pending_active_producers)::value_type& v) -> bool {
1851 1852
                                               return v.first < new_last_irreversible_block_num;
                                            });
1853
              props.active_producers = *new_producer_schedule;
1854 1855 1856 1857
         });
      }
   }

N
Nathan Hourt 已提交
1858 1859
   // Trim fork_database and undo histories
   _fork_db.set_max_size(head_block_num() - new_last_irreversible_block_num + 1);
1860
   _db.commit(new_last_irreversible_block_num);
N
Nathan Hourt 已提交
1861 1862
}

1863
void chain_controller::clear_expired_transactions()
N
Nathan Hourt 已提交
1864 1865
{ try {
   //Look for expired transactions in the deduplication list, and remove them.
D
Daniel Larimer 已提交
1866
   //transactions must have expired by at least two forking windows in order to be removed.
1867
   auto& transaction_idx = _db.get_mutable_index<transaction_multi_index>();
N
Nathan Hourt 已提交
1868
   const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
1869
   while( (!dedupe_index.empty()) && (head_block_time() > fc::time_point(dedupe_index.rbegin()->expiration) ) )
N
Nathan Hourt 已提交
1870
      transaction_idx.remove(*dedupe_index.rbegin());
1871

1872
   //Look for expired transactions in the pending generated list, and remove them.
D
Daniel Larimer 已提交
1873
   //transactions must have expired by at least two forking windows in order to be removed.
1874
   auto& generated_transaction_idx = _db.get_mutable_index<generated_transaction_multi_index>();
B
Bart Wyatt 已提交
1875
   const auto& generated_index = generated_transaction_idx.indices().get<by_expiration>();
B
Bart Wyatt 已提交
1876 1877 1878
   while( (!generated_index.empty()) && (head_block_time() > generated_index.rbegin()->expiration) ) {
      _destroy_generated_transaction(*generated_index.rbegin());
   }
B
Bart Wyatt 已提交
1879

N
Nathan Hourt 已提交
1880 1881 1882 1883
} FC_CAPTURE_AND_RETHROW() }

using boost::container::flat_set;

D
Daniel Larimer 已提交
1884
account_name chain_controller::get_scheduled_producer(uint32_t slot_num)const
N
Nathan Hourt 已提交
1885 1886
{
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();
N
Nathan Hourt 已提交
1887
   uint64_t current_aslot = dpo.current_absolute_slot + slot_num;
1888
   const auto& gpo = _db.get<global_property_object>();
1889
   auto number_of_active_producers = gpo.active_producers.producers.size();
1890 1891
   auto index = current_aslot % (number_of_active_producers * config::producer_repetitions);
   index /= config::producer_repetitions;
1892 1893
   FC_ASSERT( gpo.active_producers.producers.size() > 0, "no producers defined" );

1894
   return gpo.active_producers.producers[index].producer_name;
N
Nathan Hourt 已提交
1895 1896
}

D
Daniel Larimer 已提交
1897
block_timestamp_type chain_controller::get_slot_time(uint32_t slot_num)const
N
Nathan Hourt 已提交
1898
{
P
Pravin 已提交
1899
   if( slot_num == 0)
D
Daniel Larimer 已提交
1900
      return block_timestamp_type();
N
Nathan Hourt 已提交
1901 1902 1903 1904 1905 1906

   const dynamic_global_property_object& dpo = get_dynamic_global_properties();

   if( head_block_num() == 0 )
   {
      // n.b. first block is at genesis_time plus one block interval
P
Pravin 已提交
1907 1908 1909
      auto genesis_time = block_timestamp_type(dpo.time);
      genesis_time.slot += slot_num;
      return (fc::time_point)genesis_time;
N
Nathan Hourt 已提交
1910 1911
   }

D
Daniel Larimer 已提交
1912
   auto head_block_abs_slot = block_timestamp_type(head_block_time());
P
Pravin 已提交
1913
   head_block_abs_slot.slot += slot_num;
D
Daniel Larimer 已提交
1914
   return head_block_abs_slot;
N
Nathan Hourt 已提交
1915 1916
}

D
Daniel Larimer 已提交
1917
uint32_t chain_controller::get_slot_at_time( block_timestamp_type when )const
N
Nathan Hourt 已提交
1918
{
D
Daniel Larimer 已提交
1919
   auto first_slot_time = get_slot_time(1);
N
Nathan Hourt 已提交
1920 1921
   if( when < first_slot_time )
      return 0;
D
Daniel Larimer 已提交
1922
   return block_timestamp_type(when).slot - first_slot_time.slot + 1;
N
Nathan Hourt 已提交
1923 1924
}

1925
uint32_t chain_controller::producer_participation_rate()const
N
Nathan Hourt 已提交
1926
{
A
arhag 已提交
1927 1928 1929
   //const dynamic_global_property_object& dpo = get_dynamic_global_properties();
   //return uint64_t(config::percent_100) * __builtin_popcountll(dpo.recent_slots_filled) / 64;
   return static_cast<uint32_t>(config::percent_100); // Ignore participation rate for now until we construct a better metric.
N
Nathan Hourt 已提交
1930 1931
}

D
Daniel Larimer 已提交
1932 1933
void chain_controller::_set_apply_handler( account_name contract, scope_name scope, action_name action, apply_handler v ) {
   _apply_handlers[contract][make_pair(scope,action)] = v;
1934
}
N
Nathan Hourt 已提交
1935

1936
static void log_handled_exceptions(const transaction& trx) {
B
Bart Wyatt 已提交
1937 1938 1939 1940
   try {
      throw;
   } catch (const checktime_exceeded&) {
      throw;
1941
   } FC_CAPTURE_AND_LOG((trx));
B
Bart Wyatt 已提交
1942 1943
}

1944
transaction_trace chain_controller::__apply_transaction( transaction_metadata& meta )
1945
{ try {
1946
   transaction_trace result(meta.id);
D
Daniel Larimer 已提交
1947 1948 1949 1950 1951 1952

   for (const auto &act : meta.trx().context_free_actions) {
      apply_context context(*this, _db, act, meta);
      context.context_free = true;
      context.exec();
      fc::move_append(result.action_traces, std::move(context.results.applied_actions));
1953
      FC_ASSERT( result.deferred_transaction_requests.size() == 0 );
D
Daniel Larimer 已提交
1954 1955
   }

1956
   for (const auto &act : meta.trx().actions) {
1957
      apply_context context(*this, _db, act, meta);
1958
      context.exec();
1959
      context.results.applied_actions.back().auths_used = act.authorization.size() - context.unused_authorizations().size();
1960
      fc::move_append(result.action_traces, std::move(context.results.applied_actions));
1961
      fc::move_append(result.deferred_transaction_requests, std::move(context.results.deferred_transaction_requests));
1962
   }
B
Bart Wyatt 已提交
1963

1964
   update_resource_usage(result, meta);
B
Bart Wyatt 已提交
1965

1966
   update_permission_usage(meta);
1967
   record_transaction(meta.trx());
1968
   return result;
1969
} FC_CAPTURE_AND_RETHROW() }
B
Bart Wyatt 已提交
1970

1971
transaction_trace chain_controller::_apply_transaction( transaction_metadata& meta ) { try {
1972 1973 1974 1975 1976 1977 1978
   auto execute = [this](transaction_metadata& meta) -> transaction_trace {
      try {
         auto temp_session = _db.start_undo_session(true);
         auto result =  __apply_transaction(meta);
         temp_session.squash();
         return result;
      } catch (...) {
B
Bucky Kittinger 已提交
1979 1980 1981 1982 1983 1984
         if (meta.is_implicit) {
            transaction_trace result(meta.id);
            result.status = transaction_trace::hard_fail;
            return result;
         }

1985 1986 1987 1988
         // if there is no sender, there is no error handling possible, rethrow
         if (!meta.sender) {
            throw;
         }
1989

1990 1991 1992 1993
         // log exceptions we can handle with the error handle, throws otherwise
         log_handled_exceptions(meta.trx());

         return _apply_error(meta);
B
Bart Wyatt 已提交
1994
      }
1995
   };
1996

1997 1998 1999 2000
   auto start = fc::time_point::now();
   auto result = execute(meta);
   result._profiling_us = fc::time_point::now() - start;
   return result;
2001
} FC_CAPTURE_AND_RETHROW( (transaction_header(meta.trx())) ) }
B
Bart Wyatt 已提交
2002 2003 2004 2005 2006 2007 2008

transaction_trace chain_controller::_apply_error( transaction_metadata& meta ) {
   transaction_trace result(meta.id);
   result.status = transaction_trace::soft_fail;

   transaction etrx;
   etrx.actions.emplace_back(vector<permission_level>{{meta.sender_id,config::active_name}},
2009
                             contracts::onerror(meta.raw_data, meta.raw_data + meta.raw_size) );
B
Bart Wyatt 已提交
2010 2011

   try {
2012 2013
      auto temp_session = _db.start_undo_session(true);

2014
      apply_context context(*this, _db, etrx.actions.front(), meta);
D
Daniel Larimer 已提交
2015
      context.exec();
2016
      fc::move_append(result.action_traces, std::move(context.results.applied_actions));
2017
      fc::move_append(result.deferred_transaction_requests, std::move(context.results.deferred_transaction_requests));
B
Bart Wyatt 已提交
2018

B
Bart Wyatt 已提交
2019
      uint32_t act_usage = result.action_traces.size();
2020

B
Bart Wyatt 已提交
2021 2022 2023
      for (auto &at: result.action_traces) {
         at.region_id = meta.region_id;
         at.cycle_index = meta.cycle_index;
2024
      }
2025

2026
      update_resource_usage(result, meta);
2027
      record_transaction(meta.trx());
2028 2029

      temp_session.squash();
B
Bart Wyatt 已提交
2030
      return result;
2031

B
Bart Wyatt 已提交
2032
   } catch (...) {
2033 2034 2035 2036
      // log exceptions we can handle with the error handle, throws otherwise
      log_handled_exceptions(etrx);

      // fall through to marking this tx as hard-failing
B
Bart Wyatt 已提交
2037 2038 2039 2040
   }

   // if we have an objective error, on an error handler, we return hard fail for the trx
   result.status = transaction_trace::hard_fail;
2041 2042 2043
   return result;
}

B
Bart Wyatt 已提交
2044 2045
void chain_controller::_destroy_generated_transaction( const generated_transaction_object& gto ) {
   auto& generated_transaction_idx = _db.get_mutable_index<generated_transaction_multi_index>();
2046
   _resource_limits.add_account_ram_usage(gto.payer, -( config::billable_size_v<generated_transaction_object> + gto.packed_trx.size()));
B
Bart Wyatt 已提交
2047 2048 2049 2050 2051 2052 2053 2054
   generated_transaction_idx.remove(gto);

}

void chain_controller::_create_generated_transaction( const deferred_transaction& dto ) {
   size_t trx_size = fc::raw::pack_size(dto);
   _resource_limits.add_account_ram_usage(
      dto.payer,
2055
      (config::billable_size_v<generated_transaction_object> + (int64_t)trx_size),
B
Bart Wyatt 已提交
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
      "Generated Transaction ${id} from ${s}", _V("id", dto.sender_id)("s",dto.sender)
   );

   _db.create<generated_transaction_object>([&](generated_transaction_object &obj) {
      obj.trx_id = dto.id();
      obj.sender = dto.sender;
      obj.sender_id = dto.sender_id;
      obj.payer = dto.payer;
      obj.expiration = dto.expiration;
      obj.delay_until = dto.execute_after;
      obj.published = head_block_time();
      obj.packed_trx.resize(trx_size);
      fc::datastream<char *> ds(obj.packed_trx.data(), obj.packed_trx.size());
      fc::raw::pack(ds, dto);
   });
}

2073 2074 2075 2076 2077
vector<transaction_trace> chain_controller::push_deferred_transactions( bool flush, uint32_t skip )
{ try {
   if( !_pending_block ) {
      _start_pending_block( true );
   }
B
Bart Wyatt 已提交
2078

2079 2080 2081 2082 2083 2084 2085 2086
   return with_skip_flags(skip, [&]() {
      return _db.with_write_lock([&]() {
         return _push_deferred_transactions( flush );
      });
   });
} FC_CAPTURE_AND_RETHROW() }

vector<transaction_trace> chain_controller::_push_deferred_transactions( bool flush )
B
Bart Wyatt 已提交
2087
{
2088 2089
   FC_ASSERT( _pending_block, " block not started" );

2090 2091 2092 2093 2094 2095
   if (flush && _pending_cycle_trace && _pending_cycle_trace->shard_traces.size() > 0) {
      // TODO: when we go multithreaded this will need a better way to see if there are flushable
      // deferred transactions in the shards
      auto maybe_start_new_cycle = [&]() {
         for (const auto &st: _pending_cycle_trace->shard_traces) {
            for (const auto &tr: st.transaction_traces) {
2096 2097 2098 2099 2100 2101 2102 2103 2104
               for (const auto &req: tr.deferred_transaction_requests) {
                  if ( req.contains<deferred_transaction>() ) {
                     const auto& dt = req.get<deferred_transaction>();
                     if ( fc::time_point(dt.execute_after) <= head_block_time() ) {
                        // force a new cycle and break out
                        _finalize_pending_cycle();
                        _start_pending_cycle();
                        return;
                     }
2105 2106 2107 2108 2109
                  }
               }
            }
         }
      };
B
Bart Wyatt 已提交
2110

2111 2112
      maybe_start_new_cycle();
   }
B
Bart Wyatt 已提交
2113

B
Bart Wyatt 已提交
2114
   const auto& generated_transaction_idx = _db.get_index<generated_transaction_multi_index>();
2115 2116
   auto& generated_index = generated_transaction_idx.indices().get<by_delay>();
   vector<const generated_transaction_object*> candidates;
B
Bart Wyatt 已提交
2117

2118
   for( auto itr = generated_index.begin(); itr != generated_index.end() && (head_block_time() >= itr->delay_until); ++itr) {
2119 2120 2121
      const auto &gtrx = *itr;
      candidates.emplace_back(&gtrx);
   }
B
Bart Wyatt 已提交
2122

2123
   auto deferred_transactions_deadline = fc::time_point::now() + fc::microseconds(config::deferred_transactions_max_time_per_block_us);
2124
   vector<transaction_trace> res;
2125 2126 2127 2128
   for (const auto* trx_p: candidates) {
      if (!is_known_transaction(trx_p->trx_id)) {
         try {
            auto trx = fc::raw::unpack<deferred_transaction>(trx_p->packed_trx.data(), trx_p->packed_trx.size());
2129
            transaction_metadata mtrx (trx, trx_p->published, trx.sender, trx.sender_id, trx_p->packed_trx.data(), trx_p->packed_trx.size(), deferred_transactions_deadline);
2130
            res.push_back( _push_transaction(std::move(mtrx)) );
2131 2132
         } FC_CAPTURE_AND_LOG((trx_p->trx_id)(trx_p->sender));
      }
B
Bart Wyatt 已提交
2133 2134

      _destroy_generated_transaction(*trx_p);
2135

2136 2137 2138
      if ( deferred_transactions_deadline <= fc::time_point::now() ) {
         break;
      }
B
Bart Wyatt 已提交
2139
   }
2140
   return res;
B
Bart Wyatt 已提交
2141 2142
}

D
Daniel Larimer 已提交
2143 2144 2145 2146 2147
const apply_handler* chain_controller::find_apply_handler( account_name receiver, account_name scope, action_name act ) const
{
   auto native_handler_scope = _apply_handlers.find( receiver );
   if( native_handler_scope != _apply_handlers.end() ) {
      auto handler = native_handler_scope->second.find( make_pair( scope, act ) );
2148
      if( handler != native_handler_scope->second.end() )
D
Daniel Larimer 已提交
2149 2150 2151 2152 2153
         return &handler->second;
   }
   return nullptr;
}

2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
template<typename TransactionProcessing>
transaction_trace chain_controller::wrap_transaction_processing( transaction_metadata&& data, TransactionProcessing trx_processing )
{ try {
   FC_ASSERT( _pending_block, " block not started" );

   if (_limits.max_push_transaction_us.count() > 0) {
      auto newval = fc::time_point::now() + _limits.max_push_transaction_us;
      if ( !data.processing_deadline || newval < *data.processing_deadline ) {
         data.processing_deadline = newval;
      }
   }

   const transaction& trx = data.trx();

2168 2169
   //wdump((transaction_header(trx)));

2170 2171 2172 2173 2174 2175 2176 2177
   auto temp_session = _db.start_undo_session(true);

   // for now apply the transaction serially but schedule it according to those invariants

   auto result = trx_processing(data);

   auto& bcycle = _pending_block->regions.back().cycles_summary.back();
   auto& bshard = bcycle.front();
B
Bart Wyatt 已提交
2178
   auto& bshard_trace = _pending_cycle_trace->shard_traces.at(0);
2179

B
Bart Wyatt 已提交
2180
   record_locks_for_data_access(result, bshard_trace.read_locks, bshard_trace.write_locks);
2181 2182 2183

   bshard.transactions.emplace_back( result );

B
Bart Wyatt 已提交
2184
   bshard_trace.append(result);
2185 2186 2187 2188

   // The transaction applied successfully. Merge its changes into the pending block session.
   temp_session.squash();

2189 2190
   //wdump((transaction_header(data.trx())));
   _pending_transaction_metas.emplace_back( move(data) );
2191 2192

   return result;
2193
} FC_CAPTURE_AND_RETHROW( (transaction_header(data.trx())) ) }
2194

D
Daniel Larimer 已提交
2195
} } /// eosio::chain