chain_controller.cpp 65.2 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>
7
#include <eosio/chain/contracts/staked_balance_objects.hpp>
N
Nathan Hourt 已提交
8

B
Bart Wyatt 已提交
9 10
#include <eosio/chain/block_summary_object.hpp>
#include <eosio/chain/global_property_object.hpp>
11
#include <eosio/chain/contracts/contract_table_objects.hpp>
B
Bart Wyatt 已提交
12 13 14 15 16 17
#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 已提交
18
#include <eosio/chain/contracts/chain_initializer.hpp>
19
#include <eosio/chain/contracts/producer_objects.hpp>
20
#include <eosio/chain/scope_sequence_object.hpp>
21
#include <eosio/chain/merkle.hpp>
N
Nathan Hourt 已提交
22

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

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

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

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

#include <fstream>
#include <functional>
#include <iostream>
40
#include <chrono>
N
Nathan Hourt 已提交
41

P
Pravin 已提交
42
namespace eosio { namespace chain {
D
Daniel Larimer 已提交
43

44 45 46 47
bool is_start_of_round( block_num_type block_num ) {
  return (block_num % config::blocks_per_round) == 0; 
}

D
Daniel Larimer 已提交
48 49 50 51 52 53 54 55
chain_controller::chain_controller( const chain_controller::controller_config& cfg )
:_db( cfg.shared_memory_dir, 
      (cfg.read_only ? database::read_only : database::read_write), 
      cfg.shared_memory_size), 
 _block_log(cfg.block_log_dir) 
{
   _initialize_indexes();

56 57 58
   for (auto& f : cfg.applied_irreversible_block_callbacks)
      applied_irreversible_block.connect(f);

D
Daniel Larimer 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
   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();
}

80
bool chain_controller::is_known_block(const block_id_type& id)const
N
Nathan Hourt 已提交
81
{
82
   return _fork_db.is_known_block(id) || _block_log.read_block_by_id(id);
N
Nathan Hourt 已提交
83 84 85 86 87 88
}
/**
 * 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.
 */
89
bool chain_controller::is_known_transaction(const transaction_id_type& id)const
N
Nathan Hourt 已提交
90
{
91
   const auto& trx_idx = _db.get_index<transaction_multi_index, by_trx_id>();
N
Nathan Hourt 已提交
92 93 94
   return trx_idx.find( id ) != trx_idx.end();
}

95
block_id_type chain_controller::get_block_id_for_num(uint32_t block_num)const
N
Nathan Hourt 已提交
96
{ try {
97 98
   if (const auto& block = fetch_block_by_number(block_num))
      return block->id();
N
Nathan Hourt 已提交
99

100 101 102
   FC_THROW_EXCEPTION(unknown_block_exception, "Could not find block");
} FC_CAPTURE_AND_RETHROW((block_num)) }

103
optional<signed_block> chain_controller::fetch_block_by_id(const block_id_type& id)const
N
Nathan Hourt 已提交
104
{
105 106
   auto b = _fork_db.fetch_block(id);
   if(b) return b->data;
107
   return _block_log.read_block_by_id(id);
N
Nathan Hourt 已提交
108 109
}

110
optional<signed_block> chain_controller::fetch_block_by_number(uint32_t num)const
N
Nathan Hourt 已提交
111
{
112
   if (const auto& block = _block_log.read_block_by_num(num))
113 114
      return *block;

N
Nathan Hourt 已提交
115
   // Not in _block_log, so it must be since the last irreversible block. Grab it from _fork_db instead
116 117 118 119 120 121 122 123
   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 已提交
124 125 126
   return optional<signed_block>();
}

D
Daniel Larimer 已提交
127
/*
D
Daniel Larimer 已提交
128
const signed_transaction& chain_controller::get_recent_transaction(const transaction_id_type& trx_id) const
N
Nathan Hourt 已提交
129
{
130
   auto& index = _db.get_index<transaction_multi_index, by_trx_id>();
N
Nathan Hourt 已提交
131 132 133 134
   auto itr = index.find(trx_id);
   FC_ASSERT(itr != index.end());
   return itr->trx;
}
D
Daniel Larimer 已提交
135
*/
N
Nathan Hourt 已提交
136

137
std::vector<block_id_type> chain_controller::get_block_ids_on_fork(block_id_type head_of_fork) const
N
Nathan Hourt 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
{
  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;
}

155

N
Nathan Hourt 已提交
156 157 158 159 160 161
/**
 * 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 已提交
162
void chain_controller::push_block(const signed_block& new_block, uint32_t skip)
D
Daniel Larimer 已提交
163
{ try {
D
Daniel Larimer 已提交
164
   with_skip_flags( skip, [&](){ 
D
Daniel Larimer 已提交
165
      return without_pending_transactions( [&]() {
166
         return _db.with_write_lock( [&]() {
167
            return _push_block(new_block);
168
         } );
N
Nathan Hourt 已提交
169 170
      });
   });
171
} FC_CAPTURE_AND_RETHROW((new_block)) }
N
Nathan Hourt 已提交
172

173
bool chain_controller::_push_block(const signed_block& new_block)
N
Nathan Hourt 已提交
174
{ try {
N
Nathan Hourt 已提交
175
   uint32_t skip = _skip_flags;
176
   if (!(skip&skip_fork_db)) {
N
Nathan Hourt 已提交
177
      /// TODO: if the block is greater than the head block and before the next maintenance interval
N
Nathan Hourt 已提交
178 179 180 181
      // 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.
182
      if (new_head->data.previous != head_block_id()) {
N
Nathan Hourt 已提交
183 184
         //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
185 186
         if (new_head->data.block_num() > head_block_num()) {
            wlog("Switching to fork: ${id}", ("id",new_head->data.id()));
N
Nathan Hourt 已提交
187 188 189
            auto branches = _fork_db.fetch_branch_from(new_head->data.id(), head_block_id());

            // pop blocks until we hit the forked block
190
            while (head_block_id() != branches.second.back()->data.previous)
N
Nathan Hourt 已提交
191 192 193
               pop_block();

            // push all blocks on the new fork
194 195
            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()));
N
Nathan Hourt 已提交
196 197
                optional<fc::exception> except;
                try {
198
                   auto session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
199
                   _apply_block((*ritr)->data, skip);
N
Nathan Hourt 已提交
200 201
                   session.push();
                }
202 203 204
                catch (const fc::exception& e) { except = e; }
                if (except) {
                   wlog("exception thrown while switching forks ${e}", ("e",except->to_detail_string()));
N
Nathan Hourt 已提交
205
                   // remove the rest of branches.first from the fork_db, those blocks are invalid
206 207
                   while (ritr != branches.first.rend()) {
                      _fork_db.remove((*ritr)->data.id());
N
Nathan Hourt 已提交
208 209
                      ++ritr;
                   }
210
                   _fork_db.set_head(branches.second.front());
N
Nathan Hourt 已提交
211 212

                   // pop all blocks from the bad fork
213
                   while (head_block_id() != branches.second.back()->data.previous)
N
Nathan Hourt 已提交
214 215 216
                      pop_block();

                   // restore all blocks from the good fork
217
                   for (auto ritr = branches.second.rbegin(); ritr != branches.second.rend(); ++ritr) {
218
                      auto session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
219
                      _apply_block((*ritr)->data, skip);
N
Nathan Hourt 已提交
220 221 222 223 224
                      session.push();
                   }
                   throw *except;
                }
            }
D
Daniel Larimer 已提交
225
            return true; //swithced fork
N
Nathan Hourt 已提交
226
         }
D
Daniel Larimer 已提交
227
         else return false; // didn't switch fork
N
Nathan Hourt 已提交
228 229 230 231
      }
   }

   try {
232
      auto session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
233
      _apply_block(new_block, skip);
N
Nathan Hourt 已提交
234 235 236 237 238 239 240 241
      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;
242
} FC_CAPTURE_AND_RETHROW((new_block)) }
N
Nathan Hourt 已提交
243 244 245 246 247 248 249 250 251 252

/**
 * 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.
 */
253
transaction_trace chain_controller::push_transaction(const signed_transaction& trx, uint32_t skip)
N
Nathan Hourt 已提交
254
{ try {
255 256
   return with_skip_flags(skip, [&]() {
      return _db.with_write_lock([&]() {
257
         return _push_transaction(trx);
D
Daniel Larimer 已提交
258
      });
N
Nathan Hourt 已提交
259 260
   });
} FC_CAPTURE_AND_RETHROW((trx)) }
N
Nathan Hourt 已提交
261

262
transaction_trace chain_controller::_push_transaction(const signed_transaction& trx) {
B
Bart Wyatt 已提交
263
   check_transaction_authorization(trx);
264
   transaction_metadata   mtrx( trx, get_chain_id(), head_block_time());
B
Bart Wyatt 已提交
265 266 267 268 269 270 271 272 273 274 275 276

   auto result = _push_transaction(mtrx);

   _pending_block->input_transactions.push_back(trx);

   // notify anyone listening to pending transactions
   on_pending_transaction(trx);

   return result;

}

B
Bart Wyatt 已提交
277 278 279 280
static void record_locks_for_data_access(const vector<action_trace>& action_traces, vector<shard_lock>& read_locks, vector<shard_lock>& write_locks ) {
   for (const auto& at: action_traces) {
      for (const auto& access: at.data_access) {
         if (access.type == data_access_info::read) {
281
            read_locks.emplace_back(shard_lock{access.code, access.scope});
B
Bart Wyatt 已提交
282
         } else {
283
            write_locks.emplace_back(shard_lock{access.code, access.scope});
B
Bart Wyatt 已提交
284 285 286 287 288
         }
      }
   }
}

B
Bart Wyatt 已提交
289 290 291
transaction_trace chain_controller::_push_transaction( transaction_metadata& data )
{
   const transaction& trx = data.trx;
292 293
   // 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.
D
Daniel Larimer 已提交
294
   if( !_pending_block ) {
D
Daniel Larimer 已提交
295
      _start_pending_block();
D
Daniel Larimer 已提交
296
   }
297

298
   auto temp_session = _db.start_undo_session(true);
D
Daniel Larimer 已提交
299

B
Bart Wyatt 已提交
300
   // for now apply the transaction serially but schedule it according to those invariants
301
   validate_referenced_accounts(trx);
N
Nathan Hourt 已提交
302

303 304
   auto cyclenum = _pending_block->regions.back().cycles_summary.size() - 1;

305 306 307
   /// 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
B
Bart Wyatt 已提交
308 309 310
   // set cycle, shard, region etc
   data.region_id = 0;
   data.cycle_index = cyclenum;
B
Bart Wyatt 已提交
311
   data.shard_index = 0;
B
Bart Wyatt 已提交
312
   auto result = _apply_transaction( data );
313

314
   auto& bcycle = _pending_block->regions.back().cycles_summary.back();
B
Bart Wyatt 已提交
315
   auto& bshard = bcycle.front();
316

B
Bart Wyatt 已提交
317
   record_locks_for_data_access(result.action_traces, bshard.read_locks, bshard.write_locks);
318

319 320
   fc::deduplicate(bshard.read_locks);
   fc::deduplicate(bshard.write_locks);
321

B
Bart Wyatt 已提交
322
   bshard.transactions.emplace_back( result );
323

B
Bart Wyatt 已提交
324
   _pending_cycle_trace->shard_traces.at(0).append(result);
B
Bart Wyatt 已提交
325

N
Nathan Hourt 已提交
326 327 328
   // The transaction applied successfully. Merge its changes into the pending block session.
   temp_session.squash();

B
Bart Wyatt 已提交
329
   return result;
N
Nathan Hourt 已提交
330 331
}

332 333 334 335 336 337
void chain_controller::_start_pending_block()
{
   FC_ASSERT( !_pending_block );
   _pending_block         = signed_block();
   _pending_block_trace   = block_trace(*_pending_block);
   _pending_block_session = _db.start_undo_session(true);
338 339
   _pending_block->regions.resize(1);
   _pending_block_trace->region_traces.resize(1);
340 341 342
   _start_pending_cycle();
}

343 344
/**
 *  Wraps up all work for current shards, starts a new cycle, and
345
 *  executes any pending transactions
346
 */
347
void chain_controller::_start_pending_cycle() {
348
   _pending_block->regions.back().cycles_summary.resize( _pending_block->regions[0].cycles_summary.size() + 1 );
349 350
   _pending_cycle_trace = cycle_trace();
   _start_pending_shard();
351 352

   /// TODO: check for deferred transactions and schedule them
353
} // _start_pending_cycle
354

355
void chain_controller::_start_pending_shard()
B
Bart Wyatt 已提交
356
{
357
   auto& bcycle = _pending_block->regions.back().cycles_summary.back();
358 359 360
   bcycle.resize( bcycle.size()+1 );

   _pending_cycle_trace->shard_traces.resize(_pending_cycle_trace->shard_traces.size() + 1 );
B
Bart Wyatt 已提交
361 362
}

363 364
void chain_controller::_finalize_pending_cycle()
{
365 366 367 368
   for( auto& shard : _pending_cycle_trace->shard_traces ) {
      shard.calculate_root();
   }

369
   _apply_cycle_trace(*_pending_cycle_trace);
370
   _pending_block_trace->region_traces.back().cycle_traces.emplace_back(std::move(*_pending_cycle_trace));
371 372
   _pending_cycle_trace.reset();
}
B
Bart Wyatt 已提交
373

374 375 376 377 378
void chain_controller::_apply_cycle_trace( const cycle_trace& res )
{
   for (const auto&st: res.shard_traces) {
      for (const auto &tr: st.transaction_traces) {
         for (const auto &dt: tr.deferred_transactions) {
379
            _db.create<generated_transaction_object>([&](generated_transaction_object &obj) {
380 381 382 383 384
               obj.trx_id = dt.id();
               obj.sender = dt.sender;
               obj.sender_id = dt.sender_id;
               obj.expiration = dt.expiration;
               obj.delay_until = dt.execute_after;
385
               obj.published = head_block_time();
386 387 388 389 390 391
               obj.packed_trx.resize(fc::raw::pack_size(dt));
               fc::datastream<char *> ds(obj.packed_trx.data(), obj.packed_trx.size());
               fc::raw::pack(ds, dt);
            });
         }

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
         if (tr.canceled_deferred.size() > 0 ) {
            auto &generated_transaction_idx = _db.get_mutable_index<generated_transaction_multi_index>();
            const auto &generated_index = generated_transaction_idx.indices().get<by_sender_id>();
            for (const auto &dr: tr.canceled_deferred) {
               while(!generated_index.empty()) {
                  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 ) {
                     break;
                  }

                  generated_transaction_idx.remove(*itr);
               }
            }
         }

407 408 409 410
         ///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 已提交
411
                  "[(${a},${n})->${r}]",
412
                  fc::mutable_variant_object()
B
Bart Wyatt 已提交
413 414
                     ("a", ar.act.account)
                     ("n", ar.act.name)
415 416 417 418 419
                     ("r", ar.receiver));
               std::cerr << prefix << ": CONSOLE OUTPUT BEGIN =====================" << std::endl;
               std::cerr << ar.console;
               std::cerr << prefix << ": CONSOLE OUTPUT END   =====================" << std::endl;
            }
420
         }
B
Bart Wyatt 已提交
421 422 423 424
      }
   }
}

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
/**
 *  After applying all transactions successfully we can update
 *  the current block time, block number, producer stats, etc
 */
void chain_controller::_finalize_block( const block_trace& trace ) { try {
   const auto& b = trace.block;
   const producer_object& signing_producer = validate_block_header(_skip_flags, b);

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

   create_block_summary(b);
   clear_expired_transactions();

441
   applied_block( trace ); //emit
442 443 444 445 446
   if (_currently_replaying_blocks)
     applied_irreversible_block(b);

} FC_CAPTURE_AND_RETHROW( (trace.block) ) }

447
signed_block chain_controller::generate_block(
D
Daniel Larimer 已提交
448 449 450
   block_timestamp_type when,
   account_name producer,
   const private_key_type& block_signing_private_key,
N
Nathan Hourt 已提交
451 452 453
   uint32_t skip /* = 0 */
   )
{ try {
N
Nathan Hourt 已提交
454
   return with_skip_flags( skip, [&](){
D
Daniel Larimer 已提交
455
      return _db.with_write_lock( [&](){
D
Daniel Larimer 已提交
456
         return _generate_block( when, producer, block_signing_private_key );
D
Daniel Larimer 已提交
457
      });
N
Nathan Hourt 已提交
458
   });
D
Daniel Larimer 已提交
459
} FC_CAPTURE_AND_RETHROW( (when) ) }
N
Nathan Hourt 已提交
460

D
Daniel Larimer 已提交
461 462 463 464 465
signed_block chain_controller::_generate_block( block_timestamp_type when, 
                                              account_name producer, 
                                              const private_key_type& block_signing_key )
{ try {
   uint32_t skip     = _skip_flags;
N
Nathan Hourt 已提交
466 467
   uint32_t slot_num = get_slot_at_time( when );
   FC_ASSERT( slot_num > 0 );
D
Daniel Larimer 已提交
468
   account_name scheduled_producer = get_scheduled_producer( slot_num );
N
Nathan Hourt 已提交
469
   FC_ASSERT( scheduled_producer == producer );
N
Nathan Hourt 已提交
470

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

D
Daniel Larimer 已提交
473
   if( !_pending_block ) {
D
Daniel Larimer 已提交
474
      _start_pending_block();
475 476
   }

477
   _finalize_pending_cycle();
478

D
Daniel Larimer 已提交
479 480
   if( !(skip & skip_producer_signature) )
      FC_ASSERT( producer_obj.signing_key == block_signing_key.get_public_key() );
N
Nathan Hourt 已提交
481

482 483 484 485 486 487 488
      _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 = _pending_block->calculate_transaction_merkle_root();
      _pending_block->action_mroot = _pending_block_trace->calculate_action_merkle_root();

489

490
      if( is_start_of_round( _pending_block->block_num() ) ) {
491 492 493
      auto latest_producer_schedule = _calculate_producer_schedule();
      if( latest_producer_schedule != _head_producer_schedule() )
         _pending_block->new_producers = latest_producer_schedule;
494 495
   }

N
Nathan Hourt 已提交
496
   if( !(skip & skip_producer_signature) )
D
Daniel Larimer 已提交
497
      _pending_block->sign( block_signing_key );
N
Nathan Hourt 已提交
498

499
   _finalize_block( *_pending_block_trace );
D
Daniel Larimer 已提交
500

501 502
   _pending_block_session->push();

D
Daniel Larimer 已提交
503 504
   auto result = move( *_pending_block );

505
   _pending_block_trace.reset();
506 507 508
   _pending_block.reset();
   _pending_block_session.reset();

D
Daniel Larimer 已提交
509
   if (!(skip&skip_fork_db)) {
D
Daniel Larimer 已提交
510
      _fork_db.push_block(result);
N
Nathan Hourt 已提交
511
   }
D
Daniel Larimer 已提交
512
   return result;
N
Nathan Hourt 已提交
513

N
Nathan Hourt 已提交
514
} FC_CAPTURE_AND_RETHROW( (producer) ) }
N
Nathan Hourt 已提交
515 516

/**
N
Nathan Hourt 已提交
517
 * Removes the most recent block from the database and undoes any changes it made.
N
Nathan Hourt 已提交
518
 */
519
void chain_controller::pop_block()
N
Nathan Hourt 已提交
520
{ try {
D
Daniel Larimer 已提交
521
   _pending_block_session.reset();
N
Nathan Hourt 已提交
522 523 524 525 526
   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();
527
   _db.undo();
N
Nathan Hourt 已提交
528 529
} FC_CAPTURE_AND_RETHROW() }

530
void chain_controller::clear_pending()
N
Nathan Hourt 已提交
531
{ try {
532
   _pending_block_trace.reset();
D
Daniel Larimer 已提交
533
   _pending_block.reset();
D
Daniel Larimer 已提交
534
   _pending_block_session.reset();
N
Nathan Hourt 已提交
535 536 537 538
} FC_CAPTURE_AND_RETHROW() }

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

D
Daniel Larimer 已提交
539
void chain_controller::_apply_block(const signed_block& next_block, uint32_t skip)
N
Nathan Hourt 已提交
540 541
{
   auto block_num = next_block.block_num();
542 543 544 545 546
   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 已提交
547

548
      if (_checkpoints.rbegin()->first >= block_num)
N
Nathan Hourt 已提交
549 550
         skip = ~0;// WE CAN SKIP ALMOST EVERYTHING
   }
N
Nathan Hourt 已提交
551 552 553

   with_applying_block([&] {
      with_skip_flags(skip, [&] {
D
Daniel Larimer 已提交
554
         __apply_block(next_block);
N
Nathan Hourt 已提交
555 556
      });
   });
N
Nathan Hourt 已提交
557 558
}

559 560
static void validate_shard_locks(const vector<shard_lock>& locks, const string& tag) {
   if (locks.size() < 2) {
561 562 563
      return;
   }

B
Bart Wyatt 已提交
564
   for (auto cur = locks.begin() + 1; cur != locks.end(); ++cur) {
565
      auto prev = cur - 1;
B
Bart Wyatt 已提交
566 567
      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));
568 569
   }
}
570

D
Daniel Larimer 已提交
571
void chain_controller::__apply_block(const signed_block& next_block)
N
Nathan Hourt 已提交
572
{ try {
N
Nathan Hourt 已提交
573
   uint32_t skip = _skip_flags;
N
Nathan Hourt 已提交
574

D
Daniel Larimer 已提交
575 576 577
   /*
   FC_ASSERT((skip & skip_merkle_check) 
             || next_block.transaction_merkle_root == next_block.calculate_merkle_root(),
578 579
             "", ("next_block.transaction_merkle_root", next_block.transaction_merkle_root)
             ("calc",next_block.calculate_merkle_root())("next_block",next_block)("id",next_block.id()));
D
Daniel Larimer 已提交
580
             */
N
Nathan Hourt 已提交
581 582

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

584 585 586 587
   /// 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 );

588 589 590 591 592

   /// cache the input tranasction ids so that they can be looked up when executing the
   /// summary
   map<transaction_id_type,const signed_transaction*> trx_index;
   for( const auto& t : next_block.input_transactions ) {
593
      trx_index[t.get_transaction().id()] = &t;
594
   }
595 596

   block_trace next_block_trace(next_block);
597 598
   next_block_trace.region_traces.reserve(next_block.regions.size());

599
   for( const auto& r : next_block.regions ) {
600 601 602
      region_trace r_trace;
      r_trace.cycle_traces.reserve(r.cycles_summary.size());

603
      for (uint32_t cycle_index = 0; cycle_index < r.cycles_summary.size(); cycle_index++) {
604
         const auto& cycle = r.cycles_summary.at(cycle_index);
605 606 607
         cycle_trace c_trace;
         c_trace.shard_traces.reserve(cycle.size());

608 609
         // validate that no read_scope is used as a write scope in this cycle and that no two shards
         // share write scopes
610 611
         set<shard_lock> read_locks;
         map<shard_lock, uint32_t> write_locks;
612 613 614 615 616

         for (uint32_t shard_index = 0; shard_index < cycle.size(); shard_index++) {
            const auto& shard = cycle.at(shard_index);

            // Validate that the shards scopes are correct and available
617 618 619 620
            validate_shard_locks(shard.read_locks,  "read");
            validate_shard_locks(shard.write_locks, "write");

            for (const auto& s: shard.read_locks) {
B
Bart Wyatt 已提交
621
               EOS_ASSERT(write_locks.count(s) == 0, block_concurrency_exception,
622 623 624
                  "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);
625 626
            }

627
            for (const auto& s: shard.write_locks) {
B
Bart Wyatt 已提交
628
               EOS_ASSERT(write_locks.count(s) == 0, block_concurrency_exception,
629
                  "shard ${i} requires write lock \"${a}::${s}\" which is locked for write by shard ${j}",
B
Bart Wyatt 已提交
630 631 632 633
                  ("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));
634
               write_locks[s] = shard_index;
635 636
            }

B
Bart Wyatt 已提交
637 638 639
            vector<shard_lock> used_read_locks;
            vector<shard_lock> used_write_locks;

640
            shard_trace s_trace;
B
Bart Wyatt 已提交
641
            for (const auto& receipt : shard.transactions) {
642
                auto make_metadata = [&](){
643 644
                  auto itr = trx_index.find(receipt.id);
                  if( itr != trx_index.end() ) {
645
                     return transaction_metadata( *itr->second, get_chain_id(), next_block.timestamp );
B
Bart Wyatt 已提交
646
                  } else {
647
                     const auto& gtrx = _db.get<generated_transaction_object,by_trx_id>(receipt.id);
B
Bart Wyatt 已提交
648
                     auto trx = fc::raw::unpack<deferred_transaction>(gtrx.packed_trx.data(), gtrx.packed_trx.size());
649
                     return transaction_metadata(trx, gtrx.published, trx.sender, trx.sender_id, gtrx.packed_trx.data(), gtrx.packed_trx.size() );
650
                  }
651
               };
B
Bart Wyatt 已提交
652

653 654 655 656
               auto mtrx = make_metadata();
               mtrx.region_id = r.region;
               mtrx.cycle_index = cycle_index;
               mtrx.shard_index = shard_index;
B
Bart Wyatt 已提交
657 658
               mtrx.allowed_read_locks.emplace(&shard.read_locks);
               mtrx.allowed_write_locks.emplace(&shard.write_locks);
B
Bart Wyatt 已提交
659

660
               s_trace.transaction_traces.emplace_back(_apply_transaction(mtrx));
B
Bart Wyatt 已提交
661
               record_locks_for_data_access(s_trace.transaction_traces.back().action_traces, used_read_locks, used_write_locks);
662 663

               FC_ASSERT(receipt.status == s_trace.transaction_traces.back().status);
B
Bart Wyatt 已提交
664

665 666 667 668 669
               // validate_referenced_accounts(trx);
               // Check authorization, and allow irrelevant signatures.
               // If the block producer let it slide, we'll roll with it.
               // check_transaction_authorization(trx, true);
            } /// for each transaction id
N
Nathan Hourt 已提交
670

B
Bart Wyatt 已提交
671 672 673 674 675 676 677 678 679 680
            // Validate that the producer didn't list extra locks to bloat the size of the block
            // TODO: this check can be removed when blocks are irreversible
            fc::deduplicate(used_read_locks);
            fc::deduplicate(used_write_locks);

            EOS_ASSERT(std::equal(used_read_locks.cbegin(), used_read_locks.cend(), shard.read_locks.begin()),
               block_lock_exception, "Read locks for executing shard: ${s} do not match those listed in the block", ("s", shard_index));
            EOS_ASSERT(std::equal(used_write_locks.cbegin(), used_write_locks.cend(), shard.write_locks.begin()),
               block_lock_exception, "Write locks for executing shard: ${s} do not match those listed in the block", ("s", shard_index));

681 682 683
            s_trace.calculate_root();
            c_trace.shard_traces.emplace_back(move(s_trace));
         } /// for each shard
D
Daniel Larimer 已提交
684

685 686 687
         _apply_cycle_trace(c_trace);
         r_trace.cycle_traces.emplace_back(move(c_trace));
      } /// for each cycle
D
Daniel Larimer 已提交
688

689 690
      next_block_trace.region_traces.emplace_back(move(r_trace));
   } /// for each region
N
Nathan Hourt 已提交
691

692
   FC_ASSERT(next_block.action_mroot == next_block_trace.calculate_action_merkle_root());
N
Nathan Hourt 已提交
693

694 695
   _finalize_block( next_block_trace );
} FC_CAPTURE_AND_RETHROW( (next_block.block_num()) )  }
D
Daniel Larimer 已提交
696

697
flat_set<public_key_type> chain_controller::get_required_keys(const signed_transaction& trx,
B
Bart Wyatt 已提交
698
                                                              const flat_set<public_key_type>& candidate_keys)const 
D
Daniel Larimer 已提交
699
{
700
   auto checker = make_auth_checker( [&](const permission_level& p){ return get_permission(p).auth; },
701 702
                                     get_global_properties().configuration.max_authority_depth,
                                     candidate_keys);
703

704 705
   const auto decompressed = trx.get_transaction();
   for (const auto& act : decompressed.actions ) {
D
Daniel Larimer 已提交
706 707 708
      for (const auto& declared_auth : act.authorization) {
         if (!checker.satisfied(declared_auth)) {
            EOS_ASSERT(checker.satisfied(declared_auth), tx_missing_sigs,
D
Daniel Larimer 已提交
709
                       "transaction declares authority '${auth}', but does not have signatures for it.",
D
Daniel Larimer 已提交
710
                       ("auth", declared_auth));
711 712 713 714 715 716 717
         }
      }
   }

   return checker.used_keys();
}

718
void chain_controller::check_authorization( const vector<action>& actions,
719 720 721
                                            flat_set<public_key_type> provided_keys,
                                            bool allow_unused_signatures,
                                            flat_set<account_name>    provided_accounts  )const
D
Daniel Larimer 已提交
722
{
723
   auto checker = make_auth_checker( [&](const permission_level& p){ return get_permission(p).auth; },
724
                                     get_global_properties().configuration.max_authority_depth,
725 726
                                     provided_keys, provided_accounts );

N
Nathan Hourt 已提交
727

728
   for( const auto& act : actions ) {
729
      for( const auto& declared_auth : act.authorization ) {
D
Daniel Larimer 已提交
730

731
         // check a minimum permission if one is set, otherwise assume the contract code will validate
B
Bart Wyatt 已提交
732
         auto min_permission_name = lookup_minimum_permission(declared_auth.actor, act.account, act.name);
733 734 735 736 737 738 739 740 741 742 743
         if (min_permission_name) {
            const auto& min_permission = _db.get<permission_object, by_owner>(boost::make_tuple(declared_auth.actor, *min_permission_name));


            if ((_skip_flags & skip_authority_check) == false) {
               const auto &index = _db.get_index<permission_index>().indices();
               EOS_ASSERT(get_permission(declared_auth).satisfies(min_permission, index),
                          tx_irrelevant_auth,
                          "action declares irrelevant authority '${auth}'; minimum authority is ${min}",
                          ("auth", declared_auth)("min", min_permission.name));
            }
N
Nathan Hourt 已提交
744 745
         }
         if ((_skip_flags & skip_transaction_signatures) == false) {
D
Daniel Larimer 已提交
746
            EOS_ASSERT(checker.satisfied(declared_auth), tx_missing_sigs,
D
Daniel Larimer 已提交
747
                       "transaction declares authority '${auth}', but does not have signatures for it.",
D
Daniel Larimer 已提交
748
                       ("auth", declared_auth));
N
Nathan Hourt 已提交
749 750
         }
      }
751
   }
N
Nathan Hourt 已提交
752

753
   if (!allow_unused_signatures && (_skip_flags & skip_transaction_signatures) == false)
754
      EOS_ASSERT(checker.all_keys_used(), tx_irrelevant_sig,
755 756
                 "transaction bears irrelevant signatures from these keys: ${keys}", 
                 ("keys", checker.unused_keys()));
N
Nathan Hourt 已提交
757 758
}

759 760 761
void chain_controller::check_transaction_authorization(const signed_transaction& trx, 
                                                       bool allow_unused_signatures)const 
{
762 763
   auto decompressed = trx.get_transaction();
   check_authorization( decompressed.actions, trx.get_signature_keys( chain_id_type{} ), allow_unused_signatures );
764 765
}

766
optional<permission_name> chain_controller::lookup_minimum_permission(account_name authorizer_account,
D
Daniel Larimer 已提交
767 768
                                                                    account_name scope,
                                                                    action_name act_name) const {
769 770 771 772 773 774
   // updateauth is a special case where any permission _may_ be suitable depending
   // on the contents of the action
   if (scope == config::system_account_name && act_name == N(updateauth)) {
      return optional<permission_name>();
   }

N
Nathan Hourt 已提交
775
   try {
D
Daniel Larimer 已提交
776 777 778
      // 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);
779 780 781
      // If no specific link found, check for a contract-wide default
      if (link == nullptr) {
         get<2>(key) = "";
D
Daniel Larimer 已提交
782
         link = _db.find<permission_link_object, by_action_name>(key);
783 784 785 786
      }

      // If no specific or default link found, use active permission
      if (link != nullptr)
787 788 789
         return link->required_permission;
      else
         return N(active);
D
Daniel Larimer 已提交
790
   } FC_CAPTURE_AND_RETHROW((authorizer_account)(scope)(act_name))
N
Nathan Hourt 已提交
791 792
}

D
Daniel Larimer 已提交
793
void chain_controller::validate_uniqueness( const signed_transaction& trx )const {
N
Nathan Hourt 已提交
794
   if( !should_check_for_duplicate_transactions() ) return;
N
Nathan Hourt 已提交
795

796
   auto transaction = _db.find<transaction_object, by_trx_id>(trx.get_transaction().id());
D
Daniel Larimer 已提交
797
   EOS_ASSERT(transaction == nullptr, tx_duplicate, "transaction is not unique");
798
}
799

800
void chain_controller::record_transaction(const transaction& trx) {
801 802
   //Insert transaction into unique transactions database.
    _db.create<transaction_object>([&](transaction_object& transaction) {
D
Daniel Larimer 已提交
803 804
        transaction.trx_id = trx.id(); 
        transaction.expiration = trx.expiration;
805 806 807 808
    });
}


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

D
Daniel Larimer 已提交
812
   const auto& tapos_block_summary = _db.get<block_summary_object>((uint16_t)trx.ref_block_num);
813 814

   //Verify TaPoS block summary has correct ID prefix, and that this block's time is not past the expiration
D
Daniel Larimer 已提交
815
   EOS_ASSERT(trx.verify_reference_block(tapos_block_summary.block_id), transaction_exception,
D
Daniel Larimer 已提交
816
              "transaction's reference block did not match. Is this transaction from a different fork?",
N
Nathan Hourt 已提交
817 818
              ("tapos_summary", tapos_block_summary));
}
819

D
Daniel Larimer 已提交
820 821 822
void chain_controller::validate_referenced_accounts( const transaction& trx )const 
{ try { 
   for( const auto& act : trx.actions ) {
B
Bart Wyatt 已提交
823
      require_account(act.account);
D
Daniel Larimer 已提交
824
      for (const auto& auth : act.authorization )
D
Daniel Larimer 已提交
825
         require_account(auth.actor);
826
   }
D
Daniel Larimer 已提交
827
} FC_CAPTURE_AND_RETHROW() }
D
Daniel Larimer 已提交
828

D
Daniel Larimer 已提交
829
void chain_controller::validate_expiration( const transaction& trx ) const
830
{ try {
D
Daniel Larimer 已提交
831
   fc::time_point now = head_block_time();
D
Daniel Larimer 已提交
832
   const auto& chain_configuration = get_global_properties().configuration;
833

D
Daniel Larimer 已提交
834
   EOS_ASSERT( time_point(trx.expiration) <= now + fc::seconds(chain_configuration.max_transaction_lifetime),
D
Daniel Larimer 已提交
835
              transaction_exception, "transaction expiration is too far in the future",
836
              ("trx.expiration",trx.expiration)("now",now)
D
Daniel Larimer 已提交
837 838
              ("max_til_exp",chain_configuration.max_transaction_lifetime));
   EOS_ASSERT( now <= time_point(trx.expiration), transaction_exception, "transaction is expired",
839 840
              ("now",now)("trx.exp",trx.expiration));
} FC_CAPTURE_AND_RETHROW((trx)) }
841

842

843 844
void chain_controller::require_scope( const scope_name& scope )const {
   switch( uint64_t(scope) ) {
845 846
      case config::eosio_all_scope:
      case config::eosio_auth_scope:
847 848 849 850 851 852
         return; /// built in scopes
      default:
         require_account(scope);
   }
}

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

858
const producer_object& chain_controller::validate_block_header(uint32_t skip, const signed_block& next_block)const {
859 860
   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 已提交
861
   EOS_ASSERT(head_block_time() < (fc::time_point)next_block.timestamp, block_validate_exception, "",
862
              ("head_block_time",head_block_time())("next",next_block.timestamp)("blocknum",next_block.block_num()));
K
Kevin Heifner 已提交
863
   if (((fc::time_point)next_block.timestamp) > head_block_time() + fc::microseconds(config::block_interval_ms*1000)) {
864
      elog("head_block_time ${h}, next_block ${t}, block_interval ${bi}",
865 866 867
           ("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));
868
   }
D
Daniel Larimer 已提交
869 870
   if (next_block.block_num() % config::blocks_per_round != 0) {
      EOS_ASSERT(!next_block.new_producers, block_validate_exception,
871
                 "Producer changes may only occur at the end of a round.");
N
Nathan Hourt 已提交
872
   }
D
Daniel Larimer 已提交
873 874
   
   const producer_object& producer = get_producer(get_scheduled_producer(get_slot_at_time(next_block.timestamp)));
N
Nathan Hourt 已提交
875

N
Nathan Hourt 已提交
876
   if(!(skip&skip_producer_signature))
877 878 879
      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 已提交
880

881
   if(!(skip&skip_producer_schedule_check)) {
882 883 884
      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 已提交
885 886
   }

887 888 889
   
   FC_ASSERT( next_block.calculate_transaction_merkle_root() == next_block.transaction_mroot, "merkle root does not match" );

N
Nathan Hourt 已提交
890 891 892
   return producer;
}

893
void chain_controller::create_block_summary(const signed_block& next_block) {
894
   auto sid = next_block.block_num() & 0xffff;
895
   _db.modify( _db.get<block_summary_object,by_id>(sid), [&](block_summary_object& p) {
896 897
         p.block_id = next_block.id();
   });
N
Nathan Hourt 已提交
898 899
}

900 901 902 903 904 905 906 907 908
/**
 *  Takes the top config::producer_count producers by total vote excluding any producer whose
 *  block_signing_key is null.  
 */
producer_schedule_type chain_controller::_calculate_producer_schedule()const {
   const auto& producers_by_vote = _db.get_index<contracts::producer_votes_multi_index,contracts::by_votes>();
   auto itr = producers_by_vote.begin();
   producer_schedule_type schedule;
   uint32_t count = 0;
909 910 911
   while( itr != producers_by_vote.end() && count < schedule.producers.size() ) {
      schedule.producers[count].producer_name = itr->owner_name;
      schedule.producers[count].block_signing_key = get_producer(itr->owner_name).signing_key;
912
      ++itr;
913
      if( schedule.producers[count].block_signing_key != public_key_type() ) {
914 915 916
         ++count;
      }
   }
917 918 919 920
   const auto& hps = _head_producer_schedule();
   schedule.version = hps.version;
   if( hps != schedule )
      ++schedule.version;
921 922 923 924 925 926 927 928 929 930 931 932 933
   return schedule;
}

/**
 *  Returns the most recent and/or pending producer schedule
 */
const producer_schedule_type& chain_controller::_head_producer_schedule()const {
   const auto& gpo = get_global_properties();
   if( gpo.pending_active_producers.size() ) 
      return gpo.pending_active_producers.back().second;
   return gpo.active_producers;
}

934
void chain_controller::update_global_properties(const signed_block& b) { try {
935 936
   // If we're at the end of a round, update the BlockchainConfiguration, producer schedule
   // and "producers" special account authority
937 938 939 940 941
   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" );
942 943 944
      }

      const auto& gpo = get_global_properties();
945 946 947

      if( _head_producer_schedule() != schedule ) {
         FC_ASSERT( b.new_producers, "pending producer set changed but block didn't indicate it" );
948
      }
949 950 951 952 953 954 955 956
      _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
            props.pending_active_producers.push_back( make_pair(b.block_num(),schedule) );
      });


957

958
      auto active_producers_authority = authority(config::producers_authority_threshold, {}, {});
959
      for(auto& name : gpo.active_producers.producers ) {
960
         active_producers_authority.accounts.push_back({{name.producer_name, config::active_name}, 1});
961 962
      }

D
Daniel Larimer 已提交
963
      auto& po = _db.get<permission_object, by_owner>( boost::make_tuple(config::producers_account_name, 
964
                                                                         config::active_name ) );
965 966 967
      _db.modify(po,[active_producers_authority] (permission_object& po) {
         po.auth = active_producers_authority;
      });
968
   }
969
} FC_CAPTURE_AND_RETHROW() } 
970

971
void chain_controller::add_checkpoints( const flat_map<uint32_t,block_id_type>& checkpts ) {
972
   for (const auto& i : checkpts)
N
Nathan Hourt 已提交
973 974 975
      _checkpoints[i.first] = i.second;
}

976
bool chain_controller::before_last_checkpoint()const {
N
Nathan Hourt 已提交
977 978 979
   return (_checkpoints.size() > 0) && (_checkpoints.rbegin()->first >= head_block_num());
}

980
const global_property_object& chain_controller::get_global_properties()const {
981
   return _db.get<global_property_object>();
N
Nathan Hourt 已提交
982 983
}

984
const dynamic_global_property_object&chain_controller::get_dynamic_global_properties() const {
985
   return _db.get<dynamic_global_property_object>();
N
Nathan Hourt 已提交
986 987
}

D
Daniel Larimer 已提交
988
time_point chain_controller::head_block_time()const {
N
Nathan Hourt 已提交
989 990 991
   return get_dynamic_global_properties().time;
}

992
uint32_t chain_controller::head_block_num()const {
N
Nathan Hourt 已提交
993 994 995
   return get_dynamic_global_properties().head_block_number;
}

996
block_id_type chain_controller::head_block_id()const {
N
Nathan Hourt 已提交
997 998 999
   return get_dynamic_global_properties().head_block_id;
}

D
Daniel Larimer 已提交
1000
account_name chain_controller::head_block_producer() const {
1001 1002 1003
   auto b = _fork_db.fetch_block(head_block_id());
   if( b ) return b->data.producer;

N
Nathan Hourt 已提交
1004
   if (auto head_block = fetch_block_by_id(head_block_id()))
1005
      return head_block->producer;
N
Nathan Hourt 已提交
1006 1007 1008
   return {};
}

D
Daniel Larimer 已提交
1009 1010
const producer_object& chain_controller::get_producer(const account_name& owner_name) const 
{ try {
B
Bart Wyatt 已提交
1011
   return _db.get<producer_object, by_owner>(owner_name);
D
Daniel Larimer 已提交
1012
} FC_CAPTURE_AND_RETHROW( (owner_name) ) }
N
Nathan Hourt 已提交
1013

1014 1015 1016 1017 1018
const permission_object&   chain_controller::get_permission( const permission_level& level )const 
{ try {
   return _db.get<permission_object, by_owner>( boost::make_tuple(level.actor,level.permission) );
} FC_CAPTURE_AND_RETHROW( (level) ) }

1019
uint32_t chain_controller::last_irreversible_block_num() const {
N
Nathan Hourt 已提交
1020
   return get_dynamic_global_properties().last_irreversible_block_num;
N
Nathan Hourt 已提交
1021 1022
}

D
Daniel Larimer 已提交
1023
void chain_controller::_initialize_indexes() {
1024 1025
   _db.add_index<account_index>();
   _db.add_index<permission_index>();
1026
   _db.add_index<permission_usage_index>();
1027
   _db.add_index<permission_link_index>();
1028
   _db.add_index<action_permission_index>();
1029 1030 1031 1032 1033
   _db.add_index<contracts::table_id_multi_index>();
   _db.add_index<contracts::key_value_index>();
   _db.add_index<contracts::keystr_value_index>();
   _db.add_index<contracts::key128x128_value_index>();
   _db.add_index<contracts::key64x64x64_value_index>();
1034 1035 1036 1037 1038

   _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>();
1039
   _db.add_index<generated_transaction_multi_index>();
1040
   _db.add_index<producer_multi_index>();
1041
   _db.add_index<scope_sequence_multi_index>();
1042 1043
   _db.add_index<bandwidth_usage_index>();
   _db.add_index<compute_usage_index>();
N
Nathan Hourt 已提交
1044 1045
}

D
Daniel Larimer 已提交
1046
void chain_controller::_initialize_chain(contracts::chain_initializer& starter)
N
Nathan Hourt 已提交
1047
{ try {
1048
   if (!_db.find<global_property_object>()) {
N
Nathan Hourt 已提交
1049 1050
      _db.with_write_lock([this, &starter] {
         auto initial_timestamp = starter.get_chain_start_time();
D
Daniel Larimer 已提交
1051 1052 1053
         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 已提交
1054

1055
         // Create global properties
1056
         const auto& gp = _db.create<global_property_object>([&starter](global_property_object& p) {
N
Nathan Hourt 已提交
1057 1058
            p.configuration = starter.get_chain_start_configuration();
            p.active_producers = starter.get_chain_start_producers();
1059
         });
1060

1061
         _db.create<dynamic_global_property_object>([&](dynamic_global_property_object& p) {
N
Nathan Hourt 已提交
1062
            p.time = initial_timestamp;
1063
            p.recent_slots_filled = uint64_t(-1);
1064 1065
            p.virtual_net_bandwidth = gp.configuration.max_block_size * (config::blocksize_average_window_ms / config::block_interval_ms );
            p.virtual_act_bandwidth = gp.configuration.max_block_acts * (config::blocksize_average_window_ms / config::block_interval_ms );
1066
         });
N
Nathan Hourt 已提交
1067

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

D
Daniel Larimer 已提交
1072 1073
         auto acts = starter.prepare_database(*this, _db);

1074 1075 1076
         // create a block for our genesis transaction to send to applied_irreversible_block below
         signed_block block{};
         block.producer = config::system_account_name;
1077 1078 1079 1080 1081 1082 1083
         block_trace btrace{block};
         btrace.region_traces.emplace_back();
         auto& rtrace = btrace.region_traces.back();
         rtrace.cycle_traces.emplace_back();
         auto& ctrace = rtrace.cycle_traces.back();
         ctrace.shard_traces.emplace_back();
         auto& strace = ctrace.shard_traces.back();
1084

1085
         transaction genesis_setup_transaction; // not actually signed, signature checking is skipped
D
Daniel Larimer 已提交
1086
         genesis_setup_transaction.actions = move(acts);
1087
         block.input_transactions.emplace_back(genesis_setup_transaction, signed_transaction::zlib);
D
Daniel Larimer 已提交
1088 1089

         ilog( "applying genesis transaction" );
1090
         with_skip_flags(skip_scope_check | skip_transaction_signatures | skip_authority_check | received_block | genesis_setup, 
D
Daniel Larimer 已提交
1091
         [&](){ 
1092
            transaction_metadata tmeta( genesis_setup_transaction );
1093 1094
            transaction_trace ttrace = __apply_transaction( tmeta );
            strace.append(ttrace);
1095
         });
1096 1097

         // TODO: Should we write this genesis block instead of faking it on startup?
1098 1099
         strace.calculate_root();
         applied_block(btrace);
1100 1101
         applied_irreversible_block(block);

1102
         ilog( "done applying genesis transaction" );
1103 1104
      });
   }
N
Nathan Hourt 已提交
1105 1106
} FC_CAPTURE_AND_RETHROW() }

N
Nathan Hourt 已提交
1107

1108
void chain_controller::replay() {
1109
   ilog("Replaying blockchain");
N
Nathan Hourt 已提交
1110
   auto start = fc::time_point::now();
K
Kevin Heifner 已提交
1111

K
Kevin Heifner 已提交
1112
   auto on_exit = fc::make_scoped_exit([&_currently_replaying_blocks = _currently_replaying_blocks](){
K
Kevin Heifner 已提交
1113 1114 1115 1116
      _currently_replaying_blocks = false;
   });
   _currently_replaying_blocks = true;

1117 1118 1119
   auto last_block = _block_log.read_head();
   if (!last_block) {
      elog("No blocks in block log; skipping replay");
N
Nathan Hourt 已提交
1120 1121 1122 1123 1124
      return;
   }

   const auto last_block_num = last_block->block_num();

1125
   ilog("Replaying ${n} blocks...", ("n", last_block_num) );
1126 1127 1128 1129 1130
   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 已提交
1131
      _apply_block(*block, skip_producer_signature |
N
Nathan Hourt 已提交
1132 1133 1134 1135
                          skip_transaction_signatures |
                          skip_transaction_dupe_check |
                          skip_tapos_check |
                          skip_producer_schedule_check |
1136 1137
                          skip_authority_check |
                          received_block);
N
Nathan Hourt 已提交
1138 1139
   }
   auto end = fc::time_point::now();
1140 1141
   ilog("Done replaying ${n} blocks, elapsed time: ${t} sec",
        ("n", head_block_num())("t",double((end-start).count())/1000000.0));
N
Nathan Hourt 已提交
1142

1143
   _db.set_revision(head_block_num());
1144
}
N
Nathan Hourt 已提交
1145

D
Daniel Larimer 已提交
1146
void chain_controller::_spinup_db() {
1147 1148 1149 1150 1151
   // 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()));
1152

1153 1154
   });
}
N
Nathan Hourt 已提交
1155

D
Daniel Larimer 已提交
1156
void chain_controller::_spinup_fork_db()
N
Nathan Hourt 已提交
1157
{
1158 1159 1160 1161 1162 1163 1164 1165
   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 已提交
1166 1167
}

D
Daniel Larimer 已提交
1168
/*
1169 1170
ProducerRound chain_controller::calculate_next_round(const signed_block& next_block) {
   auto schedule = _admin->get_next_round(_db);
N
Nathan Hourt 已提交
1171 1172 1173 1174
   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));
P
Pravin 已提交
1175 1176 1177
   
   fc::time_point tp = (fc::time_point)next_block.timestamp;
   utilities::rand::random rng(tp.sec_since_epoch());
1178 1179
   rng.shuffle(schedule);
   return schedule;
D
Daniel Larimer 已提交
1180
}*/
1181

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

1185 1186 1187
   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 已提交
1188
   uint32_t missed_blocks = head_block_num() == 0? 1 : get_slot_at_time((fc::time_point)b.timestamp);
1189
   assert(missed_blocks != 0);
N
Nathan Hourt 已提交
1190
   missed_blocks--;
N
Nathan Hourt 已提交
1191

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

1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
   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 已提交
1209 1210 1211
      }
   }

1212 1213
   const auto& props = get_global_properties();

N
Nathan Hourt 已提交
1214
   // dynamic global properties updating
1215
   _db.modify( _dgp, [&]( dynamic_global_property_object& dgp ){
N
Nathan Hourt 已提交
1216 1217 1218
      dgp.head_block_number = b.block_num();
      dgp.head_block_id = b.id();
      dgp.time = b.timestamp;
1219
      dgp.current_producer = b.producer;
N
Nathan Hourt 已提交
1220
      dgp.current_absolute_slot += missed_blocks+1;
1221 1222 1223 1224 1225
      dgp.average_block_size.add_usage( fc::raw::pack_size(b), b.timestamp );

      dgp.update_virtual_net_bandwidth( props.configuration );
      dgp.update_virtual_act_bandwidth( props.configuration );

N
Nathan Hourt 已提交
1226 1227 1228 1229 1230 1231

      // 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;
1232 1233 1234 1235 1236
      } else
         if(config::percent_100 * get_global_properties().active_producers.producers.size() / config::blocks_per_round > config::required_producer_participation)
            dgp.recent_slots_filled = uint64_t(-1);
         else
            dgp.recent_slots_filled = 0;
1237
      dgp.block_merkle_root.append( head_block_id() ); 
N
Nathan Hourt 已提交
1238 1239 1240 1241 1242
   });

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

1243
void chain_controller::update_signing_producer(const producer_object& signing_producer, const signed_block& new_block)
N
Nathan Hourt 已提交
1244 1245
{
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();
P
Pravin 已提交
1246
   uint64_t new_block_aslot = dpo.current_absolute_slot + get_slot_at_time( (fc::time_point)new_block.timestamp );
N
Nathan Hourt 已提交
1247

1248
   _db.modify( signing_producer, [&]( producer_object& _wit )
N
Nathan Hourt 已提交
1249 1250 1251 1252 1253 1254
   {
      _wit.last_aslot = new_block_aslot;
      _wit.last_confirmed_block_num = new_block.block_num();
   } );
}

1255
void chain_controller::update_last_irreversible_block()
N
Nathan Hourt 已提交
1256 1257 1258 1259
{
   const global_property_object& gpo = get_global_properties();
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();

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

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

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

D
Daniel Larimer 已提交
1268
   size_t offset = EOS_PERCENT(producer_objs.size(), config::percent_100- config::irreversible_threshold_percent);
1269 1270
   std::nth_element(producer_objs.begin(), producer_objs.begin() + offset, producer_objs.end(),
      [](const producer_object* a, const producer_object* b) {
N
Nathan Hourt 已提交
1271
         return a->last_confirmed_block_num < b->last_confirmed_block_num;
1272
      });
N
Nathan Hourt 已提交
1273

N
Nathan Hourt 已提交
1274
   uint32_t new_last_irreversible_block_num = producer_objs[offset]->last_confirmed_block_num;
N
Nathan Hourt 已提交
1275

1276
   if (new_last_irreversible_block_num > dpo.last_irreversible_block_num) {
1277
      _db.modify(dpo, [&](dynamic_global_property_object& _dpo) {
N
Nathan Hourt 已提交
1278
         _dpo.last_irreversible_block_num = new_last_irreversible_block_num;
1279
      });
N
Nathan Hourt 已提交
1280
   }
1281 1282

   // Write newly irreversible blocks to disk. First, get the number of the last block on disk...
1283
   auto old_last_irreversible_block = _block_log.head();
1284 1285 1286 1287
   int last_block_on_disk = 0;
   // 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();
1288

1289
   if (last_block_on_disk < new_last_irreversible_block_num) {
1290 1291 1292 1293 1294
      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);
         assert(block);
1295
         _block_log.append(*block);
K
Kevin Heifner 已提交
1296
         applied_irreversible_block(*block);
1297
      }
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
   }

   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 ) {
         _db.modify( gpo, [&]( auto& props ){
1310
              boost::range::remove_erase_if(props.pending_active_producers,
1311
                                            [new_last_irreversible_block_num](const typename decltype(props.pending_active_producers)::value_type& v) -> bool {
1312 1313
                                               return v.first < new_last_irreversible_block_num;
                                            });
1314
              props.active_producers = *new_producer_schedule;
1315 1316 1317 1318
         });
      }
   }

N
Nathan Hourt 已提交
1319 1320 1321

   // Trim fork_database and undo histories
   _fork_db.set_max_size(head_block_num() - new_last_irreversible_block_num + 1);
1322
   _db.commit(new_last_irreversible_block_num);
N
Nathan Hourt 已提交
1323 1324
}

1325
void chain_controller::clear_expired_transactions()
N
Nathan Hourt 已提交
1326 1327
{ try {
   //Look for expired transactions in the deduplication list, and remove them.
D
Daniel Larimer 已提交
1328
   //transactions must have expired by at least two forking windows in order to be removed.
D
Daniel Larimer 已提交
1329
   /*
1330
   auto& transaction_idx = _db.get_mutable_index<transaction_multi_index>();
N
Nathan Hourt 已提交
1331
   const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
D
Daniel Larimer 已提交
1332
   while( (!dedupe_index.empty()) && (head_block_time() > dedupe_index.rbegin()->expiration) )
N
Nathan Hourt 已提交
1333
      transaction_idx.remove(*dedupe_index.rbegin());
B
Bart Wyatt 已提交
1334
      */
1335
   //Look for expired transactions in the pending generated list, and remove them.
D
Daniel Larimer 已提交
1336
   //transactions must have expired by at least two forking windows in order to be removed.
1337
   auto& generated_transaction_idx = _db.get_mutable_index<generated_transaction_multi_index>();
B
Bart Wyatt 已提交
1338 1339
   const auto& generated_index = generated_transaction_idx.indices().get<by_expiration>();
   while( (!generated_index.empty()) && (head_block_time() > generated_index.rbegin()->expiration) )
1340
      generated_transaction_idx.remove(*generated_index.rbegin());
B
Bart Wyatt 已提交
1341

N
Nathan Hourt 已提交
1342 1343 1344 1345
} FC_CAPTURE_AND_RETHROW() }

using boost::container::flat_set;

D
Daniel Larimer 已提交
1346
account_name chain_controller::get_scheduled_producer(uint32_t slot_num)const
N
Nathan Hourt 已提交
1347 1348
{
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();
N
Nathan Hourt 已提交
1349
   uint64_t current_aslot = dpo.current_absolute_slot + slot_num;
1350
   const auto& gpo = _db.get<global_property_object>();
D
Daniel Larimer 已提交
1351 1352 1353 1354
   //auto number_of_active_producers = gpo.active_producers.size();
   auto index = current_aslot % (config::blocks_per_round); //TODO configure number of repetitions by producer
   index /= config::producer_repititions;

1355
   return gpo.active_producers.producers[index].producer_name;
N
Nathan Hourt 已提交
1356 1357
}

D
Daniel Larimer 已提交
1358
block_timestamp_type chain_controller::get_slot_time(uint32_t slot_num)const
N
Nathan Hourt 已提交
1359
{
P
Pravin 已提交
1360
   if( slot_num == 0)
D
Daniel Larimer 已提交
1361
      return block_timestamp_type();
N
Nathan Hourt 已提交
1362 1363 1364 1365 1366 1367

   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 已提交
1368 1369 1370
      auto genesis_time = block_timestamp_type(dpo.time);
      genesis_time.slot += slot_num;
      return (fc::time_point)genesis_time;
N
Nathan Hourt 已提交
1371 1372
   }

D
Daniel Larimer 已提交
1373
   auto head_block_abs_slot = block_timestamp_type(head_block_time());
P
Pravin 已提交
1374
   head_block_abs_slot.slot += slot_num;
D
Daniel Larimer 已提交
1375
   return head_block_abs_slot;
N
Nathan Hourt 已提交
1376 1377
}

D
Daniel Larimer 已提交
1378
uint32_t chain_controller::get_slot_at_time( block_timestamp_type when )const
N
Nathan Hourt 已提交
1379
{
D
Daniel Larimer 已提交
1380
   auto first_slot_time = get_slot_time(1);
N
Nathan Hourt 已提交
1381 1382
   if( when < first_slot_time )
      return 0;
D
Daniel Larimer 已提交
1383
   return block_timestamp_type(when).slot - first_slot_time.slot + 1;
N
Nathan Hourt 已提交
1384 1385
}

1386
uint32_t chain_controller::producer_participation_rate()const
N
Nathan Hourt 已提交
1387 1388
{
   const dynamic_global_property_object& dpo = get_dynamic_global_properties();
D
Daniel Larimer 已提交
1389
   return uint64_t(config::percent_100) * __builtin_popcountll(dpo.recent_slots_filled) / 64;
N
Nathan Hourt 已提交
1390 1391
}

D
Daniel Larimer 已提交
1392 1393
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;
1394
}
N
Nathan Hourt 已提交
1395

1396
static void log_handled_exceptions(const transaction& trx) {
B
Bart Wyatt 已提交
1397 1398 1399 1400
   try {
      throw;
   } catch (const checktime_exceeded&) {
      throw;
1401
   } FC_CAPTURE_AND_LOG((trx));
B
Bart Wyatt 已提交
1402 1403
}

1404 1405 1406
transaction_trace chain_controller::__apply_transaction( transaction_metadata& meta ) {
   transaction_trace result(meta.id);
   for (const auto &act : meta.trx.actions) {
B
Bart Wyatt 已提交
1407
      apply_context context(*this, _db, act, meta);
1408 1409 1410
      context.exec();
      fc::move_append(result.action_traces, std::move(context.results.applied_actions));
      fc::move_append(result.deferred_transactions, std::move(context.results.generated_transactions));
1411
      fc::move_append(result.canceled_deferred, std::move(context.results.canceled_deferred));
1412
   }
B
Bart Wyatt 已提交
1413

1414
   uint32_t act_usage = result.action_traces.size();
1415

1416 1417 1418 1419
   for (auto &at: result.action_traces) {
      at.region_id = meta.region_id;
      at.cycle_index = meta.cycle_index;
      if (at.receiver == config::system_account_name &&
B
Bart Wyatt 已提交
1420
          at.act.account == config::system_account_name &&
1421 1422
          at.act.name == N(setcode)) {
         act_usage += config::setcode_act_usage;
B
Bart Wyatt 已提交
1423
      }
1424
   }
B
Bart Wyatt 已提交
1425

1426
   update_usage(meta, act_usage);
1427
   record_transaction(meta.trx);
1428 1429
   return result;
}
B
Bart Wyatt 已提交
1430

1431 1432 1433 1434 1435 1436
transaction_trace chain_controller::_apply_transaction( transaction_metadata& meta ) {
   try {
      auto temp_session = _db.start_undo_session(true);
      auto result = __apply_transaction(meta);
      temp_session.squash();
      return result;
B
Bart Wyatt 已提交
1437 1438
   } catch (...) {
      // if there is no sender, there is no error handling possible, rethrow
1439
      if (!meta.sender) {
B
Bart Wyatt 已提交
1440 1441
         throw;
      }
1442 1443
      // log exceptions we can handle with the error handle, throws otherwise
      log_handled_exceptions(meta.trx);
1444

B
Bart Wyatt 已提交
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
      return _apply_error( meta );
   }
}

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}},
                             contracts::onerror(meta.generated_data, meta.generated_data + meta.generated_size) );

   try {
1458 1459
      auto temp_session = _db.start_undo_session(true);

B
Bart Wyatt 已提交
1460
      apply_context context(*this, _db, etrx.actions.front(), meta);
D
Daniel Larimer 已提交
1461
      context.exec();
1462
      fc::move_append(result.action_traces, std::move(context.results.applied_actions));
B
Bart Wyatt 已提交
1463 1464
      fc::move_append(result.deferred_transactions, std::move(context.results.generated_transactions));

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

B
Bart Wyatt 已提交
1467 1468 1469
      for (auto &at: result.action_traces) {
         at.region_id = meta.region_id;
         at.cycle_index = meta.cycle_index;
1470
      }
1471

B
Bart Wyatt 已提交
1472 1473
      update_usage(meta, act_usage);
      record_transaction(meta.trx);
1474 1475

      temp_session.squash();
B
Bart Wyatt 已提交
1476
      return result;
1477

B
Bart Wyatt 已提交
1478
   } catch (...) {
1479 1480 1481 1482
      // 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 已提交
1483 1484 1485 1486
   }

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

1490
void chain_controller::push_deferred_transactions( bool flush )
B
Bart Wyatt 已提交
1491
{
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
   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) {
               for (const auto &dt: tr.deferred_transactions) {
                  if (fc::time_point(dt.execute_after) <= head_block_time()) {
                     // force a new cycle and break out
                     _finalize_pending_cycle();
                     _start_pending_cycle();
                     return;
                  }
               }
            }
         }
      };
B
Bart Wyatt 已提交
1509

1510 1511
      maybe_start_new_cycle();
   }
B
Bart Wyatt 已提交
1512

1513 1514 1515
   auto& generated_transaction_idx = _db.get_mutable_index<generated_transaction_multi_index>();
   auto& generated_index = generated_transaction_idx.indices().get<by_delay>();
   vector<const generated_transaction_object*> candidates;
B
Bart Wyatt 已提交
1516

1517 1518 1519 1520
   for( auto itr = generated_index.rbegin(); itr != generated_index.rend() && (head_block_time() >= itr->delay_until); ++itr) {
      const auto &gtrx = *itr;
      candidates.emplace_back(&gtrx);
   }
B
Bart Wyatt 已提交
1521

1522 1523 1524 1525
   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());
1526
            transaction_metadata mtrx (trx, trx_p->published, trx.sender, trx.sender_id, trx_p->packed_trx.data(), trx_p->packed_trx.size());
1527 1528 1529 1530 1531 1532
            _push_transaction(mtrx);
            generated_transaction_idx.remove(*trx_p);
         } FC_CAPTURE_AND_LOG((trx_p->trx_id)(trx_p->sender));
      } else {
         generated_transaction_idx.remove(*trx_p);
      }
B
Bart Wyatt 已提交
1533 1534 1535 1536
   }
}


1537 1538 1539 1540 1541
/**
 *  @param act_usage The number of "actions" delivered directly or indirectly by applying meta.trx
 */
void chain_controller::update_usage( transaction_metadata& meta, uint32_t act_usage )
{
1542
   set<std::pair<account_name, permission_name>> authorizing_accounts;
1543

1544
   for( const auto& act : meta.trx.actions )
1545
      for( const auto& auth : act.authorization )
1546
         authorizing_accounts.emplace( auth.actor, auth.permission );
1547

1548 1549 1550
   auto trx_size = meta.bandwidth_usage + config::fixed_bandwidth_overhead_per_transaction;

   const auto& dgpo = get_dynamic_global_properties();
1551

1552 1553 1554 1555
   if( meta.signing_keys ) {
      act_usage += meta.signing_keys->size();
   }

1556 1557
   auto head_time = head_block_time();
   for( const auto& authaccnt : authorizing_accounts ) {
1558
      const auto& buo = _db.get<bandwidth_usage_object,by_owner>( authaccnt.first );
1559
      _db.modify( buo, [&]( auto& bu ){
1560
          bu.bytes.add_usage( trx_size, head_time );
1561
          bu.acts.add_usage( act_usage, head_time );
1562
      });
1563
      const auto& sbo = _db.get<contracts::staked_balance_object, contracts::by_owner_name>(authaccnt.first);
1564 1565
      // TODO enable this after fixing divide by 0 with virtual_net_bandwidth and total_staked_tokens
      /// note: buo.bytes.value is in ubytes and virtual_net_bandwidth is in bytes, so
1566 1567 1568
      //  we convert to fixed int uin128_t with 60 bits of precision, divide by rate limiting precision
      //  then divide by virtual max_block_size which gives us % of virtual max block size in fixed width

1569 1570 1571 1572 1573 1574 1575 1576
      uint128_t  used_ubytes        = buo.bytes.value;
      uint128_t  used_uacts         = buo.acts.value;
      uint128_t  virtual_max_ubytes = dgpo.virtual_net_bandwidth * config::rate_limiting_precision;
      uint128_t  virtual_max_uacts  = dgpo.virtual_act_bandwidth * config::rate_limiting_precision;
      uint64_t   user_stake         = sbo.staked_balance;
      
      if( !(_skip_flags & genesis_setup) ) {
         FC_ASSERT( (used_ubytes * dgpo.total_staked_tokens) <=  (user_stake * virtual_max_ubytes), "authorizing account '${n}' has insufficient net bandwidth for this transaction",
1577
                    ("n",name(authaccnt.first))
1578 1579 1580 1581 1582 1583
                    ("used_bytes",double(used_ubytes)/1000000.)
                    ("user_stake",user_stake)
                    ("virtual_max_bytes", double(virtual_max_ubytes)/1000000. )
                    ("total_staked_tokens", dgpo.total_staked_tokens)
                    );
         FC_ASSERT( (used_uacts * dgpo.total_staked_tokens)  <=  (user_stake * virtual_max_uacts),  "authorizing account '${n}' has insufficient compute bandwidth for this transaction",
1584
                    ("n",name(authaccnt.first))
1585 1586 1587 1588 1589 1590
                    ("used_acts",double(used_uacts)/1000000.)
                    ("user_stake",user_stake)
                    ("virtual_max_uacts", double(virtual_max_uacts)/1000000. )
                    ("total_staked_tokens", dgpo.total_staked_tokens)
                    );
      }
1591 1592 1593

      // for any transaction not sent by code, update the affirmative last time a given permission was used
      if (!meta.sender) {
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
         const auto *puo = _db.find<permission_usage_object, by_account_permission>(boost::make_tuple(authaccnt.first, authaccnt.second));
         if (puo) {
            _db.modify(*puo, [this](permission_usage_object &pu) {
               pu.last_used = head_block_time();
            });
         } else {
            _db.create<permission_usage_object>([this, &authaccnt](permission_usage_object &pu){
               pu.account = authaccnt.first;
               pu.permission = authaccnt.second;
               pu.last_used = head_block_time();
            });
         }
1606
      }
1607 1608
   }

1609 1610 1611 1612
   _db.modify( dgpo, [&]( auto& props ) {
      props.average_block_acts.add_usage( act_usage, head_time );
   });

D
Daniel Larimer 已提交
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
}

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 ) );
      if( handler != native_handler_scope->second.end() ) 
         return &handler->second;
   }
   return nullptr;
}

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