美文网首页
EOS源码阅读(区块写入blocks.log)

EOS源码阅读(区块写入blocks.log)

作者: 坠叶飘香 | 来源:发表于2019-01-23 20:49 被阅读0次

eos/libraries/chain/block_log.cpp

1. 以可写方式打开block文件

文件名:blocks.log
inline void check_block_write() {
    if (!block_write) {
        block_stream.close();
        //以可写方式打开block_file文件(文件名为:blocks.log)
        block_stream.open(block_file.generic_string().c_str(), LOG_WRITE);
        block_write = true;
  }
}

2.以可写方式打开index文件

文件名:blocks.index
inline void check_index_write() {
    if (!index_write) {
        index_stream.close();
        index_stream.open(index_file.generic_string().c_str(), LOG_WRITE);
        index_write = true;
  }
}

3.写入一个区块到block和index两个文件中

uint64_t block_log::append(const signed_block_ptr& b) {
      try {
         EOS_ASSERT( my->genesis_written_to_block_log, block_log_append_fail, "Cannot append to block log until the genesis is first written" );

         my->check_block_write();
         my->check_index_write();

         uint64_t pos = my->block_stream.tellp(); //返回当前指针位置

        ** //每个区块的索引占据8字节,所以根据区块高度可以推测这个区块该写入的位置 **
         //sizeof: 返回一个对象或者类型所占的内存字节数
         EOS_ASSERT(my->index_stream.tellp() == sizeof(uint64_t) * (b->block_num() - 1),
                   block_log_append_fail,
                   "Append to index file occuring at wrong position.",
                   ("position", (uint64_t) my->index_stream.tellp())          //得到的位置
                   ("expected", (b->block_num() - 1) * sizeof(uint64_t))); //期望的位置

         auto data = fc::raw::pack(*b);
         my->block_stream.write(data.data(), data.size());    //写区块内容
         my->block_stream.write((char*)&pos, sizeof(pos));   //写区块索引
         my->index_stream.write((char*)&pos, sizeof(pos));  //写区块索引
         my->head = b; //区块头
         my->head_id = b->id(); //区块头的hash

         flush();

         return pos;
      }
      FC_LOG_AND_RETHROW()
   }

相关文章

网友评论

      本文标题:EOS源码阅读(区块写入blocks.log)

      本文链接:https://www.haomeiwen.com/subject/jhgsjqtx.html