controller.cpp 15.4 KB
Newer Older
D
Daniel Larimer 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
#include <eosio/chain/controller.hpp>
#include <chainbase/chainbase.hpp>

#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/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/resource_limits.hpp>

#include <fc/io/json.hpp>

namespace eosio { namespace chain {

using resource_limits::resource_limits_manager;

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;
   block_state_ptr                    _expected_block_state;

   void push() {
      _db_session.push();
   }
};

struct controller_impl {
   chainbase::database            db;
   block_log                      blog;
   optional<pending_state>        pending;
   block_state_ptr                head; 
   fork_database                  fork_db;            
   //wasm_interface                 wasmif;
   resource_limits_manager        resource_limits;
   controller::config             conf;
   controller&                    self;

   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() {
      /// head = fork_db.get( head->previous );
      /// db.undo();
   }


   controller_impl( const controller::config& cfg, controller& s  )
   :db( cfg.shared_memory_dir, 
        cfg.read_only ? database::read_only : database::read_write,
        cfg.shared_memory_size ),
    blog( cfg.block_log_dir ),
    //wasmif( cfg.wasm_runtime ),
    resource_limits( db ),
    conf( cfg ),
    self( s )
   {
   }

   void init() {
      // ilog( "${c}", ("c",fc::json::to_pretty_string(cfg)) );
      initialize_indicies();

      initialize_fork_db();
      /**
       * The undable state contains state transitions from blocks
       * 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.
       */
      clear_all_undo(); 
   }

   ~controller_impl() {
      pending.reset();
      db.flush();
   }

   void initialize_indicies() {
      db.add_index<account_index>();
      db.add_index<permission_index>();
      db.add_index<permission_usage_index>();
      db.add_index<permission_link_index>();
      db.add_index<action_permission_index>();

      db.add_index<contracts::table_id_multi_index>();
      db.add_index<contracts::key_value_index>();
      db.add_index<contracts::index64_index>();
      db.add_index<contracts::index128_index>();
      db.add_index<contracts::index256_index>();
      db.add_index<contracts::index_double_index>();

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

      resource_limits.initialize_database();
   }

   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();
         /*
         FC_ASSERT(db.revision() == self.head_block_num(), 
                   "Chainbase revision does not match head block num",
                   ("rev", db.revision())("head_block", self.head_block_num()));
                   */
      });
   }

   /**
    *  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.
    */
   void initialize_fork_db() {
      wlog( " Initializing new blockchain with genesis state                  " );
      producer_schedule_type initial_schedule{ 0, {{N(eosio), conf.genesis.initial_key}} };

      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();
      idump((genheader));

      head = std::make_shared<block_state>( genheader, std::make_shared<signed_block>() );
      fork_db.set( head );
      FC_ASSERT( head );
   }


   /**
    *  This method will backup all tranasctions in the current pending block,
    *  undo the pending block, call f(), and then push the pending transactions
    *  on top of the new state.
    */
   template<typename Function>
   auto without_pending_transactions( Function&& f )
   {
#if 0
      vector<transaction_metadata> old_input;

      if( _pending_block )
         old_input = move(_pending_transaction_metas);

      clear_pending();

      /** after applying f() push previously input transactions on top */
      auto on_exit = fc::make_scoped_exit( [&](){
         for( auto& t : old_input ) {
            try {
               if (!is_known_transaction(t.id))
                  _push_transaction( std::move(t) );
            } catch ( ... ){}
         }
      });
#endif
      pending.reset();
      return f();
   }



   block_state_ptr push_block( const signed_block_ptr& b ) {
      return without_pending_transactions( [&](){ 
         return db.with_write_lock( [&](){ 
            return push_block_impl( b );
         });
      });
   }


   block_state_ptr push_block_impl( const signed_block_ptr& b ) {
#if  0
      auto head_state = fork_db.add( b );
      /// check to see if we entered a fork
      if( head_state->header.previous != head_block_id() ) {
          auto branches = fork_db.fetch_branch_from(head_state->id, head_block_id());
          while (head_block_id() != branches.second.back()->header.previous)
             pop_block();

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

                while (ritr != branches.first.rend() ) {
                   fork_db.set_validity( *ritr, false );
                   ++ritr;
                }

                // pop all blocks from the bad fork
                while( head_block_id() != branches.second.back()->header.previous )
                   pop_block();
                
                // re-apply good blocks
                for( auto ritr = branches.second.rbegin(); ritr != branches.second.rend(); ++ritr ) {
                   apply_block( (*ritr) );
                }
                throw *except;
             } // end if exception
          } /// end for each block in branch

          return head_state;
      } /// end if fork

      try {
         apply_block( head_state );
      } catch ( const fc::exception& e ) {
         elog("Failed to push new block:\n${e}", ("e", e.to_detail_string()));
         fork_db.set_validity( head_state, false );
         throw;
      }
      return head;
#endif
   } /// push_block_impl

   bool should_enforce_runtime_limits()const {
      return false;
   }

   /*
   void validate_net_usage( const transaction& trx, uint32_t min_net_usage ) {
      uint32_t net_usage_limit = trx.max_net_usage_words.value * 8; // overflow checked in validate_transaction_without_state
      EOS_ASSERT( net_usage_limit == 0 || min_net_usage <= net_usage_limit,
                  transaction_exception,
                  "Packed transaction and associated data does not fit into the space committed to by the transaction's header! [usage=${usage},commitment=${commit}]",
                  ("usage", min_net_usage)("commit", net_usage_limit));
   } /// validate_net_usage
   */

   void finalize_block( const block_trace& trace ) 
   { try {

      /* TODO RESTORE 
      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() }

   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)
    */
   transaction get_on_block_transaction()
   {
      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());

      transaction trx;
      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;
   }


   /**
    *  apply_block 
    *
    *  This method starts an undo session, whose revision number should match 
    *  the block number. 
    *
    *  It first does some parallel read-only sanity checks on all input transactions.
    *
    *  It then follows the transaction delivery schedule defined by the block_summary. 
    *
   void apply_block( block_state_ptr bstate ) {
      try {
         start_block();
         for( const auto& receipt : bstate.block->transactions ) {
            receipt.trx.visit( [&]( const auto& t ){ 
               apply_transaction( t );
            });
         }
         finalize_block();
         validate_signature();
         commit_block();
      } catch ( const fc::exception& e ) {
         abort_block();
         edump((e.to_detail_string()));
         throw;
      }
   }

   void start_block( block_timestamp_type time ) {
      FC_ASSERT( !pending );
      pending = _db.start_undo_session();
      /// TODO: FC_ASSERT( _db.revision() == blocknum );

      auto trx = get_on_block_transaction();
      apply_transaction( trx );

   }

   vector<transaction_metadata> abort_block() {
      FC_ASSERT( pending.valid() );
      self.abort_apply_block();
      auto tmp = move( pending->_transaction_metas );
      pending.reset();
      return tmp;
   }

   void commit_block() {
      FC_ASSERT( pending.valid() );

      self.applied_block( pending->_pending_block_state );
      pending->push();
      pending.reset();
   }
    */

};



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

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();
   }
   */
}

const chainbase::database& controller::db()const { return my->db; }


void controller::start_block( block_timestamp_type when ) {
  FC_ASSERT( !my->pending );
  my->pending = my->db.start_undo_session(true);

  my->pending->_pending_block_state = std::make_shared<block_state>( my->head->generate_next(when), 
                                                                     std::make_shared<signed_block>() );
  idump((fc::json::to_pretty_string(*my->pending->_pending_block_state)));
}

void controller::finalize_block() {
   /// set trx mroot and act mroot
}

void controller::sign_block( std::function<signature_type( const digest_type& )> signer_callback ) {

}

void controller::commit_block() {
   my->fork_db.add( my->pending->_pending_block_state->block );
   my->pending->push();
   my->pending.reset();
}



void controller::push_block( const signed_block_ptr& b ) {
  //return my->push_block( b );  
}

transaction_trace_ptr   controller::push_transaction( const transaction_metadata_ptr& trx ) { 

}

transaction_trace_ptr controller::push_transaction() {
   return transaction_trace_ptr();
}
transaction_trace_ptr controller::push_transaction( const transaction_id_type& trxid ) {
   return transaction_trace_ptr();
   /// lookup scheduled trx and then apply it...
}

uint32_t controller::head_block_num()const {
   idump((int64_t(my.get())));
   FC_ASSERT( my->head );
   return my->head->block_num;
}
   
} } /// eosio::chain