controller.cpp 32.2 KB
Newer Older
D
Daniel Larimer 已提交
1
#include <eosio/chain/controller.hpp>
2
#include <eosio/chain/transaction_context.hpp>
D
Daniel Larimer 已提交
3 4 5 6 7 8 9 10 11 12 13 14

#include <eosio/chain/block_log.hpp>
#include <eosio/chain/fork_database.hpp>

#include <eosio/chain/account_object.hpp>
#include <eosio/chain/scope_sequence_object.hpp>
#include <eosio/chain/block_summary_object.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/contract_table_objects.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/transaction_object.hpp>

15
#include <eosio/chain/authorization_manager.hpp>
D
Daniel Larimer 已提交
16 17
#include <eosio/chain/resource_limits.hpp>

D
Daniel Larimer 已提交
18
#include <chainbase/chainbase.hpp>
D
Daniel Larimer 已提交
19 20
#include <fc/io/json.hpp>

D
Daniel Larimer 已提交
21 22
#include <eosio/chain/eosio_contract.hpp>

D
Daniel Larimer 已提交
23 24 25 26
namespace eosio { namespace chain {

using resource_limits::resource_limits_manager;

D
Daniel Larimer 已提交
27

D
Daniel Larimer 已提交
28 29 30 31 32 33 34 35 36
struct pending_state {
   pending_state( database::session&& s )
   :_db_session( move(s) ){}

   database::session                  _db_session;
   vector<transaction_metadata_ptr>   _applied_transaction_metas;

   block_state_ptr                    _pending_block_state;

D
Daniel Larimer 已提交
37
   vector<action_receipt>             _actions;
D
Daniel Larimer 已提交
38

D
Daniel Larimer 已提交
39

D
Daniel Larimer 已提交
40 41 42 43 44 45
   void push() {
      _db_session.push();
   }
};

struct controller_impl {
D
Daniel Larimer 已提交
46
   controller&                    self;
D
Daniel Larimer 已提交
47 48 49
   chainbase::database            db;
   block_log                      blog;
   optional<pending_state>        pending;
50 51
   block_state_ptr                head;
   fork_database                  fork_db;
D
Daniel Larimer 已提交
52
   wasm_interface                 wasmif;
D
Daniel Larimer 已提交
53
   resource_limits_manager        resource_limits;
54
   authorization_manager          authorization;
D
Daniel Larimer 已提交
55 56
   controller::config             conf;

D
Daniel Larimer 已提交
57 58 59
   typedef pair<scope_name,action_name>                   handler_key;
   map< account_name, map<handler_key, apply_handler> >   apply_handlers;

D
Daniel Larimer 已提交
60 61 62 63 64
   /**
    *  Transactions that were undone by pop_block or abort_block, transactions
    *  are removed from this list if they are re-applied in other blocks. Producers
    *  can query this list when scheduling new transactions into blocks.
    */
65
   map<digest_type, transaction_metadata_ptr>     unapplied_transactions;
D
Daniel Larimer 已提交
66

D
Daniel Larimer 已提交
67 68 69 70 71 72 73 74 75 76 77
   block_id_type head_block_id()const {
      return head->id;
   }
   time_point head_block_time()const {
      return head->header.timestamp;
   }
   const block_header& head_block_header()const {
      return head->header;
   }

   void pop_block() {
D
Daniel Larimer 已提交
78
      for( const auto& t : head->trxs )
79
         unapplied_transactions[t->signed_id] = t;
D
Daniel Larimer 已提交
80
      head = fork_db.get_block( head->header.previous );
D
Daniel Larimer 已提交
81
      db.undo();
D
Daniel Larimer 已提交
82 83 84
   }


D
Daniel Larimer 已提交
85 86 87 88
   void set_apply_handler( account_name contract, scope_name scope, action_name action, apply_handler v ) {
      apply_handlers[contract][make_pair(scope,action)] = v;
   }

D
Daniel Larimer 已提交
89
   controller_impl( const controller::config& cfg, controller& s  )
D
Daniel Larimer 已提交
90 91
   :self(s),
    db( cfg.shared_memory_dir,
D
Daniel Larimer 已提交
92 93 94
        cfg.read_only ? database::read_only : database::read_write,
        cfg.shared_memory_size ),
    blog( cfg.block_log_dir ),
D
Daniel Larimer 已提交
95
    fork_db( cfg.shared_memory_dir ),
D
Daniel Larimer 已提交
96
    wasmif( cfg.wasm_runtime ),
D
Daniel Larimer 已提交
97
    resource_limits( db ),
D
Daniel Larimer 已提交
98 99
    authorization( s, db ),
    conf( cfg )
D
Daniel Larimer 已提交
100
   {
D
Daniel Larimer 已提交
101
      head = fork_db.head();
D
Daniel Larimer 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119


#define SET_APP_HANDLER( contract, scope, action, nspace ) \
   set_apply_handler( #contract, #scope, #action, &BOOST_PP_CAT(apply_, BOOST_PP_CAT(contract, BOOST_PP_CAT(_,action) ) ) )
   SET_APP_HANDLER( eosio, eosio, newaccount, eosio );
   SET_APP_HANDLER( eosio, eosio, setcode, eosio );
   SET_APP_HANDLER( eosio, eosio, setabi, eosio );
   SET_APP_HANDLER( eosio, eosio, updateauth, eosio );
   SET_APP_HANDLER( eosio, eosio, deleteauth, eosio );
   SET_APP_HANDLER( eosio, eosio, linkauth, eosio );
   SET_APP_HANDLER( eosio, eosio, unlinkauth, eosio );
   SET_APP_HANDLER( eosio, eosio, onerror, eosio );
   SET_APP_HANDLER( eosio, eosio, postrecovery, eosio );
   SET_APP_HANDLER( eosio, eosio, passrecovery, eosio );
   SET_APP_HANDLER( eosio, eosio, vetorecovery, eosio );
   SET_APP_HANDLER( eosio, eosio, canceldelay, eosio );


D
Daniel Larimer 已提交
120 121 122 123
   }

   void init() {
      // ilog( "${c}", ("c",fc::json::to_pretty_string(cfg)) );
124
      add_indices();
D
Daniel Larimer 已提交
125 126

      /**
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
      *  The fork database needs an initial block_state to be set before
      *  it can accept any new blocks. This initial block state can be found
      *  in the database (whose head block state should be irreversible) or
      *  it would be the genesis state.
      */
      if( !head ) {
         initialize_fork_db(); // set head to genesis state
#warning What if head is empty because the user deleted forkdb.dat? Will this not corrupt the database?
         db.set_revision( head->block_num );
         initialize_database();
      }

      FC_ASSERT( db.revision() == head->block_num, "fork database is inconsistent with shared memory",
                 ("db",db.revision())("head",head->block_num) );

      /**
       * The undoable state contains state transitions from blocks
D
Daniel Larimer 已提交
144 145 146 147 148
       * in the fork database that could be reversed. Because this
       * is a new startup and the fork database is empty, we must
       * unwind that pending state. This state will be regenerated
       * when we catch up to the head block later.
       */
149
      //clear_all_undo();
D
Daniel Larimer 已提交
150 151 152 153
   }

   ~controller_impl() {
      pending.reset();
D
Daniel Larimer 已提交
154 155 156

      edump((db.revision())(head->block_num));

D
Daniel Larimer 已提交
157 158 159
      db.flush();
   }

160
   void add_indices() {
D
Daniel Larimer 已提交
161
      db.add_index<account_index>();
162
      db.add_index<account_sequence_index>();
D
Daniel Larimer 已提交
163

D
Daniel Larimer 已提交
164 165 166 167 168 169
      db.add_index<table_id_multi_index>();
      db.add_index<key_value_index>();
      db.add_index<index64_index>();
      db.add_index<index128_index>();
      db.add_index<index256_index>();
      db.add_index<index_double_index>();
D
Daniel Larimer 已提交
170 171 172 173 174 175 176 177

      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>();
      db.add_index<generated_transaction_multi_index>();
      db.add_index<scope_sequence_multi_index>();

178 179
      authorization.add_indices();
      resource_limits.add_indices();
D
Daniel Larimer 已提交
180 181 182 183 184 185 186 187 188 189 190
   }

   void abort_pending_block() {
      pending.reset();
   }

   void clear_all_undo() {
      // Rewind the database to the last irreversible block
      db.with_write_lock([&] {
         db.undo_all();
         /*
191
         FC_ASSERT(db.revision() == self.head_block_num(),
D
Daniel Larimer 已提交
192 193 194 195 196 197 198
                   "Chainbase revision does not match head block num",
                   ("rev", db.revision())("head_block", self.head_block_num()));
                   */
      });
   }

   /**
199
    *  Sets fork database head to the genesis state.
D
Daniel Larimer 已提交
200 201
    */
   void initialize_fork_db() {
202 203
      wlog( " Initializing new blockchain with genesis state                  " );
      producer_schedule_type initial_schedule{ 0, {{N(eosio), conf.genesis.initial_key}} };
D
Daniel Larimer 已提交
204

205 206 207 208 209 210 211 212
      block_header_state genheader;
      genheader.active_schedule       = initial_schedule;
      genheader.pending_schedule      = initial_schedule;
      genheader.pending_schedule_hash = fc::sha256::hash(initial_schedule);
      genheader.header.timestamp      = conf.genesis.initial_timestamp;
      genheader.header.action_mroot   = conf.genesis.compute_chain_id();
      genheader.id                    = genheader.header.id();
      genheader.block_num             = genheader.header.block_num();
D
Daniel Larimer 已提交
213

214 215
      head = std::make_shared<block_state>( genheader );
      signed_block genblock(genheader.header);
D
Daniel Larimer 已提交
216

217 218 219
      edump((genheader.header));
      edump((genblock));
      blog.append( genblock );
220

221
      fork_db.set( head );
D
Daniel Larimer 已提交
222 223
   }

224
   void create_native_account( account_name name, const authority& owner, const authority& active, bool is_privileged = false ) {
225
      db.create<account_object>([&](auto& a) {
D
Daniel Larimer 已提交
226 227
         a.name = name;
         a.creation_date = conf.genesis.initial_timestamp;
228
         a.privileged = is_privileged;
D
Daniel Larimer 已提交
229 230

         if( name == config::system_account_name ) {
D
Daniel Larimer 已提交
231
            a.set_abi(eosio_contract_abi(abi_def()));
D
Daniel Larimer 已提交
232 233
         }
      });
234 235 236 237
      db.create<account_sequence_object>([&](auto & a) {
        a.name = name;
      });

238 239 240 241
      const auto& owner_permission  = authorization.create_permission(name, config::owner_name, 0,
                                                                      owner, conf.genesis.initial_timestamp );
      const auto& active_permission = authorization.create_permission(name, config::active_name, owner_permission.id,
                                                                      active, conf.genesis.initial_timestamp );
D
Daniel Larimer 已提交
242 243

      resource_limits.initialize_account(name);
244 245 246 247 248 249 250 251
      resource_limits.add_pending_account_ram_usage(
         name,
         (int64_t)(config::billable_size_v<permission_object> + owner_permission.auth.get_billable_size())
      );
      resource_limits.add_pending_account_ram_usage(
         name,
         (int64_t)(config::billable_size_v<permission_object> + active_permission.auth.get_billable_size())
      );
D
Daniel Larimer 已提交
252 253 254 255 256 257 258
   }

   void initialize_database() {
      // Initialize block summary index
      for (int i = 0; i < 0x10000; i++)
         db.create<block_summary_object>([&](block_summary_object&) {});

259 260 261 262 263
      const auto& tapos_block_summary = db.get<block_summary_object>(1);
      db.modify( tapos_block_summary, [&]( auto& bs ) {
        bs.block_id = head->id;
      });

264 265 266 267
      db.create<global_property_object>([&](auto& gpo ){
        gpo.configuration = conf.genesis.initial_configuration;
      });
      db.create<dynamic_global_property_object>([](auto&){});
268 269 270 271 272 273

      authorization.initialize_database();
      resource_limits.initialize_database();

      authority system_auth(conf.genesis.initial_key);
      create_native_account( config::system_account_name, system_auth, system_auth, true );
D
Daniel Larimer 已提交
274 275 276 277 278

      auto empty_authority = authority(0, {}, {});
      auto active_producers_authority = authority(0, {}, {});
      active_producers_authority.accounts.push_back({{config::system_account_name, config::active_name}, 1});

279 280
      create_native_account( config::nobody_account_name, empty_authority, empty_authority );
      create_native_account( config::producers_account_name, empty_authority, active_producers_authority );
D
Daniel Larimer 已提交
281 282
   }

283 284 285 286 287 288 289
   void set_pending_tapos() {
      const auto& tapos_block_summary = db.get<block_summary_object>((uint16_t)pending->_pending_block_state->block_num);
      db.modify( tapos_block_summary, [&]( auto& bs ) {
        bs.block_id = pending->_pending_block_state->id;
      });
   }

D
Daniel Larimer 已提交
290
   void commit_block( bool add_to_fork_db ) {
291 292 293 294
      set_pending_tapos();
      resource_limits.process_account_limit_updates();
      resource_limits.process_block_usage( pending->_pending_block_state->block_num );

D
Daniel Larimer 已提交
295 296 297
      if( add_to_fork_db ) {
         pending->_pending_block_state->validated = true;
         head = fork_db.add( pending->_pending_block_state );
298
      }
299

D
Daniel Larimer 已提交
300 301
      pending->push();
      pending.reset();
302
      self.accepted_block( head );
D
Daniel Larimer 已提交
303
   }
D
Daniel Larimer 已提交
304

D
Daniel Larimer 已提交
305 306 307 308 309 310 311 312 313 314 315 316
   void apply_onerror( const generated_transaction_object& gto ) {
      /*
      try {
         signed_transaction etrx;
         etrx.actions.emplace_back(vector<permission_level>{{gto.sender,config::active_name}},
                                   contracts::onerror( gto.sender_id, gto.packed_trx.data(), gto.packed_trx.size()) );

         db.remove( gto );
      }
      */
   }

D
Daniel Larimer 已提交
317 318
   transaction_trace_ptr push_scheduled_transaction( const generated_transaction_object& gto ) {
      fc::datastream<const char*> ds( gto.packed_trx.data(), gto.packed_trx.size() );
D
Daniel Larimer 已提交
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

      optional<fc::exception> except;
      try {
         signed_transaction dtrx;
         fc::raw::unpack(ds,static_cast<transaction&>(dtrx) );
       
         transaction_context trx_context( self, dtrx, gto.trx_id );
         trx_context.processing_deadline = fc::time_point::now() + conf.limits.max_push_transaction_us;
         trx_context.published      = gto.published;

         /*
         trx_context.exec();
         auto& acts = pending->_actions;
         fc::move_append( acts, move(trx_context.executed) );

         db.remove( gto );

         pending->_pending_block_state->block->transactions.emplace_back( gto.trx_id );
         pending->_pending_block_state->block->transactions.back().kcpu_usage = trx.total_cpu_usage;

         return move(trx_context.trace);
         */
      } catch( const fc::exception& e ) {
         except = e;
      }
      if( except ) {
         apply_onerror( gto );
      }
      return transaction_trace_ptr();
   } /// push_scheduled_transaction
D
Daniel Larimer 已提交
349

350
   transaction_trace_ptr push_transaction( const transaction_metadata_ptr& trx ) {
351
      unapplied_transactions.erase( trx->signed_id );
D
Daniel Larimer 已提交
352
      record_transaction( trx ); /// checks for dupes
353

D
Daniel Larimer 已提交
354
      auto trace = apply_transaction( trx );
355 356

      pending->_pending_block_state->block->transactions.emplace_back( trx->packed_trx );
D
Daniel Larimer 已提交
357
      trace->receipt = pending->_pending_block_state->block->transactions.back();
358 359 360
      pending->_pending_block_state->trxs.emplace_back(trx);
      self.accepted_transaction(trx);

D
Daniel Larimer 已提交
361
      return trace;
D
Daniel Larimer 已提交
362
   }
D
Daniel Larimer 已提交
363

D
Daniel Larimer 已提交
364 365 366 367 368
   transaction_trace_ptr apply_transaction( const signed_transaction& trx, 
                                            const transaction_id_type& id, 
                                            uint32_t net_usage = 0,
                                            bool implicit = false ) {
      transaction_context trx_context( self, trx, id );
369
      trx_context.processing_deadline = fc::time_point::now() + conf.limits.max_push_transaction_us;
D
Daniel Larimer 已提交
370
      trx_context.net_usage = net_usage;
D
Daniel Larimer 已提交
371

D
Daniel Larimer 已提交
372
      trx_context.exec();
D
Daniel Larimer 已提交
373 374 375
      auto& acts = pending->_actions;
      fc::move_append( acts, move(trx_context.executed) );

376
      return move(trx_context.trace);
D
Daniel Larimer 已提交
377 378
   }

D
Daniel Larimer 已提交
379 380 381 382
   transaction_trace_ptr apply_transaction( const transaction_metadata_ptr& trx, bool implicit = false ) {
      return apply_transaction( trx->trx, trx->id, self.validate_net_usage(trx), implicit );
   }

D
Daniel Larimer 已提交
383

D
Daniel Larimer 已提交
384 385
   void record_transaction( const transaction_metadata_ptr& trx ) {
      try {
D
Daniel Larimer 已提交
386
          db.create<transaction_object>([&](transaction_object& transaction) {
D
Daniel Larimer 已提交
387 388 389 390 391
              transaction.trx_id = trx->id;
              transaction.expiration = trx->trx.expiration;
          });
      } catch ( ... ) {
          EOS_ASSERT( false, transaction_exception,
D
Daniel Larimer 已提交
392
                     "duplicate transaction ${id}", ("id", trx->id ) );
D
Daniel Larimer 已提交
393
      }
394
   } /// record_transaction
D
Daniel Larimer 已提交
395

396 397
   void start_block( block_timestamp_type when ) {
     FC_ASSERT( !pending );
D
Daniel Larimer 已提交
398

399
     FC_ASSERT( db.revision() == head->block_num );
D
Daniel Larimer 已提交
400

401 402
     pending = db.start_undo_session(true);
     pending->_pending_block_state = std::make_shared<block_state>( *head, when );
D
Daniel Larimer 已提交
403

404 405 406 407 408 409 410
     try {
        auto onbtrx = std::make_shared<transaction_metadata>( get_on_block_transaction() );
        apply_transaction( onbtrx, true );
     } catch ( ... ) {
        ilog( "on block transaction failed, but shouldn't impact block generation, system contract needs update" );
     }
   } // start_block
D
Daniel Larimer 已提交
411 412


D
Daniel Larimer 已提交
413

414 415
   void sign_block( const std::function<signature_type( const digest_type& )>& signer_callback ) {
      auto p = pending->_pending_block_state;
416
      p->sign( signer_callback );
417 418
      static_cast<signed_block_header&>(*p->block) = p->header;
   } /// sign_block
D
Daniel Larimer 已提交
419

420
   void apply_block( const signed_block_ptr& b ) {
421 422 423 424 425 426 427 428 429 430
      try {
         start_block( b->timestamp );

         for( const auto& receipt : b->transactions ) {
            if( receipt.trx.contains<packed_transaction>() ) {
               auto& pt = receipt.trx.get<packed_transaction>();
               auto mtrx = std::make_shared<transaction_metadata>(pt);
               push_transaction( mtrx );
            }
         }
D
Daniel Larimer 已提交
431

432 433
         finalize_block();
         sign_block( [&]( const auto& ){ return b->producer_signature; } );
D
Daniel Larimer 已提交
434

435 436 437
         // this is implied by the signature passing
         //FC_ASSERT( b->id() == pending->_pending_block_state->block->id(),
         //           "applying block didn't produce expected block id" );
D
Daniel Larimer 已提交
438

439 440
         commit_block(false);
         return;
D
Daniel Larimer 已提交
441
      } catch ( const fc::exception& e ) {
442 443
         edump((e.to_detail_string()));
         abort_block();
D
Daniel Larimer 已提交
444 445
         throw;
      }
446 447 448 449 450 451
   } /// apply_block

   void push_block( const signed_block_ptr& b ) {

      auto new_header_state = fork_db.add( b );
      self.accepted_block_header( new_header_state );
452

453 454 455 456
      auto new_head = fork_db.head();

      if( new_head->header.previous == head->id ) {
         try {
457
            abort_block();
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
            apply_block( b );
            fork_db.set_validity( new_head, true );
            head = new_head;
         } catch ( const fc::exception& e ) {
            fork_db.set_validity( new_head, false );
            throw;
         }
      } else {
         auto branches = fork_db.fetch_branch_from( new_head->id, head->id );

         while( head_block_id() != branches.second.back()->header.previous )
            pop_block();

         for( auto ritr = branches.first.rbegin(); ritr != branches.first.rend(); ++ritr) {
            optional<fc::exception> except;
            try {
               apply_block( (*ritr)->block );
            }
            catch (const fc::exception& e) { except = e; }
            if (except) {
               wlog("exception thrown while switching forks ${e}", ("e",except->to_detail_string()));
479

480 481 482 483
               while (ritr != branches.first.rend() ) {
                  fork_db.set_validity( *ritr, false );
                  ++ritr;
               }
484

485 486 487
               // pop all blocks from the bad fork
               while( head_block_id() != branches.second.back()->header.previous )
                  pop_block();
488

489 490 491 492 493 494 495 496 497 498
               // re-apply good blocks
               for( auto ritr = branches.second.rbegin(); ritr != branches.second.rend(); ++ritr ) {
                  apply_block( (*ritr)->block );
               }
               throw *except;
            } // end if exception
         } /// end for each block in branch
      }
   } /// push_block

499
   void abort_block() {
500
      if( pending ) {
501 502
         for( const auto& t : pending->_applied_transaction_metas )
            unapplied_transactions[t->signed_id] = t;
503 504
         pending.reset();
      }
505 506
   }

D
Daniel Larimer 已提交
507 508 509 510 511

   bool should_enforce_runtime_limits()const {
      return false;
   }

D
Daniel Larimer 已提交
512 513 514 515 516 517 518 519
   void set_action_merkle() {
      vector<digest_type> action_digests;
      action_digests.reserve( pending->_actions.size() );
      for( const auto& a : pending->_actions )
         action_digests.emplace_back( a.digest() );

      pending->_pending_block_state->header.action_mroot = merkle( move(action_digests) );
   }
D
Daniel Larimer 已提交
520

D
Daniel Larimer 已提交
521 522
   void set_trx_merkle() {
      vector<digest_type> trx_digests;
D
Daniel Larimer 已提交
523 524 525
      const auto& trxs = pending->_pending_block_state->block->transactions;
      trx_digests.reserve( trxs.size() );
      for( const auto& a : trxs )
D
Daniel Larimer 已提交
526
         trx_digests.emplace_back( a.digest() );
D
Daniel Larimer 已提交
527

D
Daniel Larimer 已提交
528
      pending->_pending_block_state->header.transaction_mroot = merkle( move(trx_digests) );
D
Daniel Larimer 已提交
529 530 531
   }


532
   void finalize_block()
D
Daniel Larimer 已提交
533
   { try {
534
      ilog( "finalize block ${p} ${t} schedule_version: ${v} lib: ${lib} ${np}  ${signed}",
535 536 537 538 539
            ("p",pending->_pending_block_state->header.producer)
            ("t",pending->_pending_block_state->header.timestamp)
            ("v",pending->_pending_block_state->header.schedule_version)
            ("lib",pending->_pending_block_state->dpos_last_irreversible_blocknum)
            ("np",pending->_pending_block_state->header.new_producers)
540
            ("signed", pending->_pending_block_state->block_signing_key)
541
            );
D
Daniel Larimer 已提交
542 543 544 545 546 547 548

      set_action_merkle();
      set_trx_merkle();

      auto p = pending->_pending_block_state;
      p->id = p->header.id();

D
Daniel Larimer 已提交
549
      create_block_summary();
D
Daniel Larimer 已提交
550

D
Daniel Larimer 已提交
551

552
      /* TODO RESTORE
D
Daniel Larimer 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
      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();

      update_last_irreversible_block();

      resource_limits.process_account_limit_updates();

      const auto& chain_config = self.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}}
      );

      */
   } FC_CAPTURE_AND_RETHROW() }

D
Daniel Larimer 已提交
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

   void create_block_summary() {
      auto p = pending->_pending_block_state;
      auto sid = p->block_num & 0xffff;
      db.modify( db.get<block_summary_object,by_id>(sid), [&](block_summary_object& bso ) {
          bso.block_id = p->id;
      });
   }

   /**
    *  This method only works for blocks within the TAPOS range, (last 65K blocks). It
    *  will return block_id_type() for older blocks.
    */
   block_id_type get_block_id_for_num( uint32_t block_num ) {
      auto sid = block_num & 0xffff;
      auto id  = db.get<block_summary_object,by_id>(sid).block_id;
      auto num = block_header::num_from_id( id );
      if( num == block_num ) return id;
      return block_id_type();
   }

D
Daniel Larimer 已提交
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
   void clear_expired_transactions() {
      //Look for expired transactions in the deduplication list, and remove them.
      auto& transaction_idx = db.get_mutable_index<transaction_multi_index>();
      const auto& dedupe_index = transaction_idx.indices().get<by_expiration>();
      while( (!dedupe_index.empty()) && (head_block_time() > fc::time_point(dedupe_index.begin()->expiration) ) ) {
         transaction_idx.remove(*dedupe_index.begin());
      }

      // Look for expired transactions in the pending generated list, and remove them.
      // TODO: expire these by sending error to handler
      auto& generated_transaction_idx = db.get_mutable_index<generated_transaction_multi_index>();
      const auto& generated_index = generated_transaction_idx.indices().get<by_expiration>();
      while( (!generated_index.empty()) && (head_block_time() > generated_index.begin()->expiration) ) {
      // TODO:   destroy_generated_transaction(*generated_index.begin());
      }
   }

   /*
   bool should_check_tapos()const { return true; }

   void validate_tapos( const transaction& trx )const {
      if( !should_check_tapos() ) return;

      const auto& tapos_block_summary = db.get<block_summary_object>((uint16_t)trx.ref_block_num);

      //Verify TaPoS block summary has correct ID prefix, and that this block's time is not past the expiration
      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?",
                 ("tapos_summary", tapos_block_summary));
   }
   */


   /**
    *  At the start of each block we notify the system contract with a transaction that passes in
    *  the block header of the prior block (which is currently our head block)
    */
D
Daniel Larimer 已提交
632
   signed_transaction get_on_block_transaction()
D
Daniel Larimer 已提交
633 634 635 636 637 638 639
   {
      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}};
      on_block_act.data = fc::raw::pack(head_block_header());

D
Daniel Larimer 已提交
640
      signed_transaction trx;
D
Daniel Larimer 已提交
641 642 643 644 645 646
      trx.actions.emplace_back(std::move(on_block_act));
      trx.set_reference_block(head_block_id());
      trx.expiration = head_block_time() + fc::seconds(1);
      return trx;
   }

647
}; /// controller_impl
D
Daniel Larimer 已提交
648

649
const resource_limits_manager&   controller::get_resource_limits_manager()const
D
Daniel Larimer 已提交
650 651 652
{
   return my->resource_limits;
}
653
resource_limits_manager&         controller::get_mutable_resource_limits_manager()
D
Daniel Larimer 已提交
654 655 656
{
   return my->resource_limits;
}
D
Daniel Larimer 已提交
657

658 659 660 661 662 663 664 665
const authorization_manager&   controller::get_authorization_manager()const
{
   return my->authorization;
}
authorization_manager&         controller::get_mutable_authorization_manager()
{
   return my->authorization;
}
D
Daniel Larimer 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690

controller::controller( const controller::config& cfg )
:my( new controller_impl( cfg, *this ) )
{
   my->init();
}

controller::~controller() {
}


void controller::startup() {
   my->head = my->fork_db.head();
   if( !my->head ) {
   }

   /*
   auto head = my->blog.read_head();
   if( head && head_block_num() < head->block_num() ) {
      wlog( "\nDatabase in inconsistant state, replaying block log..." );
      //replay();
   }
   */
}

D
Daniel Larimer 已提交
691
chainbase::database& controller::db()const { return my->db; }
D
Daniel Larimer 已提交
692 693 694


void controller::start_block( block_timestamp_type when ) {
695
   my->start_block(when);
D
Daniel Larimer 已提交
696 697 698
}

void controller::finalize_block() {
D
Daniel Larimer 已提交
699
   my->finalize_block();
D
Daniel Larimer 已提交
700 701
}

702 703
void controller::sign_block( const std::function<signature_type( const digest_type& )>& signer_callback ) {
   my->sign_block( signer_callback );
D
Daniel Larimer 已提交
704 705 706
}

void controller::commit_block() {
D
Daniel Larimer 已提交
707
   my->commit_block(true);
D
Daniel Larimer 已提交
708 709
}

D
Daniel Larimer 已提交
710 711 712
block_state_ptr controller::head_block_state()const {
   return my->head;
}
713

D
Daniel Larimer 已提交
714 715 716 717
block_state_ptr controller::pending_block_state()const {
   if( my->pending ) return my->pending->_pending_block_state;
   return block_state_ptr();
}
D
Daniel Larimer 已提交
718

719 720
void controller::abort_block() {
   my->abort_block();
D
Daniel Larimer 已提交
721 722
}

D
Daniel Larimer 已提交
723
void controller::push_block( const signed_block_ptr& b ) {
724
   my->push_block( b );
D
Daniel Larimer 已提交
725 726
}

727
transaction_trace_ptr controller::push_transaction( const transaction_metadata_ptr& trx ) {
728
   return my->push_transaction(trx);
D
Daniel Larimer 已提交
729 730
}

731
transaction_trace_ptr controller::push_next_scheduled_transaction() {
D
Daniel Larimer 已提交
732 733 734 735
   const auto& idx = db().get_index<generated_transaction_multi_index,by_delay>();
   //if( idx.begin() != idx.end() ) 
      //return my->push_scheduled( *idx.begin() );

736
   return transaction_trace_ptr();
D
Daniel Larimer 已提交
737
}
738
transaction_trace_ptr controller::push_scheduled_transaction( const transaction_id_type& trxid ) {
D
Daniel Larimer 已提交
739
   /// lookup scheduled trx and then apply it...
740
   return transaction_trace_ptr();
D
Daniel Larimer 已提交
741 742 743 744 745
}

uint32_t controller::head_block_num()const {
   return my->head->block_num;
}
D
Daniel Larimer 已提交
746 747 748
block_id_type controller::head_block_id()const {
   return my->head->id;
}
D
Daniel Larimer 已提交
749

D
Daniel Larimer 已提交
750
time_point controller::head_block_time()const {
751 752 753 754 755 756
   return my->head_block_time();
}

time_point controller::pending_block_time()const {
   FC_ASSERT( my->pending, "no pending block" );
   return my->pending->_pending_block_state->header.timestamp;
D
Daniel Larimer 已提交
757 758
}

D
Daniel Larimer 已提交
759 760 761 762
void     controller::record_transaction( const transaction_metadata_ptr& trx ) {
   my->record_transaction( trx );
}

D
Daniel Larimer 已提交
763 764 765
const dynamic_global_property_object& controller::get_dynamic_global_properties()const {
  return my->db.get<dynamic_global_property_object>();
}
D
Daniel Larimer 已提交
766 767 768
const global_property_object& controller::get_global_properties()const {
  return my->db.get<global_property_object>();
}
D
Daniel Larimer 已提交
769 770 771 772

/**
 *  This method reads the current dpos_irreverible block number, if it is higher
 *  than the last block number of the log, it grabs the next block from the
773
 *  fork database, saves it to disk, then removes the block from the fork database.
D
Daniel Larimer 已提交
774 775 776 777
 *
 *  Any forks built off of a different block with the same number are also pruned.
 */
void controller::log_irreversible_blocks() {
778
   if( !my->blog.head() )
D
Daniel Larimer 已提交
779
      my->blog.read_head();
780

D
Daniel Larimer 已提交
781 782 783 784 785 786 787 788 789
   const auto& log_head = my->blog.head();
   auto lib = my->head->dpos_last_irreversible_blocknum;

   if( lib > 1 ) {
      while( log_head && log_head->block_num() < lib ) {
         auto lhead = log_head->block_num();
         auto blk_id = my->get_block_id_for_num( lhead + 1 );
         auto blk = my->fork_db.get_block( blk_id );
         FC_ASSERT( blk, "unable to find block state", ("id",blk_id));
790
         irreversible_block( blk );
D
Daniel Larimer 已提交
791
         my->blog.append( *blk->block );
D
Daniel Larimer 已提交
792 793
         my->fork_db.prune( blk );
         my->db.commit( lhead );
D
Daniel Larimer 已提交
794 795 796
      }
   }
}
797 798 799 800 801 802 803 804 805
signed_block_ptr controller::fetch_block_by_id( block_id_type id )const {
   auto state = my->fork_db.get_block(id);
   if( state ) return state->block;
   auto bptr = fetch_block_by_number( block_header::num_from_id(id) );
   if( bptr->id() == id ) return bptr;
   return signed_block_ptr();
}

signed_block_ptr controller::fetch_block_by_number( uint32_t block_num )const  {
D
Daniel Larimer 已提交
806 807 808 809 810 811 812 813
   optional<signed_block> b = my->blog.read_block_by_num(block_num);
   if( b ) return std::make_shared<signed_block>( move(*b) );

   auto blk_id = my->get_block_id_for_num( block_num );
   auto blk_state =  my->fork_db.get_block( blk_id );
   if( blk_state ) return blk_state->block;
   return signed_block_ptr();
}
D
Daniel Larimer 已提交
814 815 816 817 818 819 820 821 822

void controller::pop_block() {
   auto prev = my->fork_db.get_block( my->head->header.previous );
   FC_ASSERT( prev, "attempt to pop beyond last irreversible block" );
   my->db.undo();
   my->head = prev;
}


D
Daniel Larimer 已提交
823 824 825
void controller::set_active_producers( const producer_schedule_type& sch ) {
   FC_ASSERT( !my->pending->_pending_block_state->header.new_producers, "this block has already set new producers" );
   FC_ASSERT( !my->pending->_pending_block_state->pending_schedule.producers.size(), "there is already a pending schedule, wait for it to become active" );
826
   my->pending->_pending_block_state->set_new_producers( sch );
D
Daniel Larimer 已提交
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
}
const producer_schedule_type& controller::active_producers()const {
   return my->pending->_pending_block_state->active_schedule;
}

const producer_schedule_type& controller::pending_producers()const {
   return my->pending->_pending_block_state->pending_schedule;
}

const apply_handler* controller::find_apply_handler( account_name receiver, account_name scope, action_name act ) const
{
   auto native_handler_scope = my->apply_handlers.find( receiver );
   if( native_handler_scope != my->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;
}
wasm_interface& controller::get_wasm_interface() {
   return my->wasmif;
}
D
Daniel Larimer 已提交
849

850
const account_object& controller::get_account( account_name name )const
D
Daniel Larimer 已提交
851 852 853
{ try {
   return my->db.get<account_object, by_name>(name);
} FC_CAPTURE_AND_RETHROW( (name) ) }
D
Daniel Larimer 已提交
854

855 856 857 858 859 860 861 862 863 864
const map<digest_type, transaction_metadata_ptr>&  controller::unapplied_transactions()const {
   return my->unapplied_transactions;
}


void controller::validate_referenced_accounts( const transaction& trx )const {
   for( const auto& a : trx.context_free_actions ) {
      get_account( a.account );
      FC_ASSERT( a.authorization.size() == 0 );
   }
D
Daniel Larimer 已提交
865
   bool one_auth = false;
866 867
   for( const auto& a : trx.actions ) {
      get_account( a.account );
868
      for( const auto& auth : a.authorization ) {
D
Daniel Larimer 已提交
869
         one_auth = true;
870 871 872
         get_account( auth.actor );
      }
   }
D
Daniel Larimer 已提交
873
   EOS_ASSERT( one_auth, tx_no_auths, "transaction must have at least one authorization" );
874 875 876 877 878 879 880 881 882 883 884 885 886 887
}

void controller::validate_expiration( const transaction& trx )const { try {
   const auto& chain_configuration = get_global_properties().configuration;

   EOS_ASSERT( time_point(trx.expiration) >= pending_block_time(), expired_tx_exception, "transaction has expired" );
   EOS_ASSERT( time_point(trx.expiration) <= pending_block_time() + fc::seconds(chain_configuration.max_transaction_lifetime),
               tx_exp_too_far_exception,
               "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",pending_block_time())
               ("max_til_exp",chain_configuration.max_transaction_lifetime) );
} FC_CAPTURE_AND_RETHROW((trx)) }

D
Daniel Larimer 已提交
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
uint64_t controller::validate_net_usage( const transaction_metadata_ptr& trx )const {
   const auto& cfg = get_global_properties().configuration;

   auto actual_net_usage = cfg.base_per_transaction_net_usage + trx->packed_trx.get_billable_size();

   actual_net_usage = ((actual_net_usage + 7)/8) * 8; // Round up to nearest multiple of 8

   uint32_t net_usage_limit = trx->trx.max_net_usage_words.value * 8UL; // overflow checked in validate_transaction_without_state
   EOS_ASSERT( net_usage_limit == 0 || actual_net_usage <= net_usage_limit, tx_resource_exhausted,
               "declared net usage limit of transaction is too low: ${actual_net_usage} > ${declared_limit}",
               ("actual_net_usage", actual_net_usage)("declared_limit",net_usage_limit) );

   return actual_net_usage;
}

903 904 905 906 907 908 909
void controller::validate_tapos( const transaction& trx )const { try {
   const auto& tapos_block_summary = db().get<block_summary_object>((uint16_t)trx.ref_block_num);

   //Verify TaPoS block summary has correct ID prefix, and that this block's time is not past the expiration
   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?",
              ("tapos_summary", tapos_block_summary));
910 911
} FC_CAPTURE_AND_RETHROW() }

912

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