美文网首页比特币源码学习笔记
比特币源码阅读(区块-CBlock)

比特币源码阅读(区块-CBlock)

作者: 坠叶飘香 | 来源:发表于2018-07-26 20:26 被阅读0次
    1. CBlock


      CBlock

    源码:
    src/primitives/block.h

    class CBlock : public CBlockHeader
    {
    public:
        // network and disk
        std::vector<CTransactionRef> vtx; //vector<CTransaction> 比CBlockHeader多了这个
    
        // memory only
        mutable bool fChecked;
    
        CBlock()
        {
            SetNull();
        }
    
        CBlock(const CBlockHeader &header)
        {
            SetNull();
            *(static_cast<CBlockHeader*>(this)) = header; //强制转换
        }
    
        ADD_SERIALIZE_METHODS;
    
        template <typename Stream, typename Operation>
        inline void SerializationOp(Stream& s, Operation ser_action) {
            READWRITEAS(CBlockHeader, *this);
            READWRITE(vtx);
        }
    
        void SetNull()
        {
            CBlockHeader::SetNull();
            vtx.clear();
            fChecked = false;
        }
    
        CBlockHeader GetBlockHeader() const
        {
            CBlockHeader block;
            block.nVersion       = nVersion;
            block.hashPrevBlock  = hashPrevBlock;
            block.hashMerkleRoot = hashMerkleRoot;
            block.nTime          = nTime;
            block.nBits          = nBits;
            block.nNonce         = nNonce;
            return block;
        }
    
        std::string ToString() const;
    };
    

    2.区块hash的取值规则:

    计算hash时不算vtx
    具体计算规则可参考:https://en.bitcoin.it/wiki/Block_hashing_algorithm
    src/primitives/block.cpp

    #include <primitives/block.h>
    
    #include <hash.h>
    #include <tinyformat.h>
    #include <utilstrencodings.h>
    #include <crypto/common.h>
    
    uint256 CBlockHeader::GetHash() const
    {
        return SerializeHash(*this); //前面看到this的赋值是header对象 (具体实现呢?)
    }
    
    std::string CBlock::ToString() const
    {
        std::stringstream s;
        s << strprintf("CBlock(hash=%s, ver=0x%08x, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
            GetHash().ToString(),
            nVersion,
            hashPrevBlock.ToString(),
            hashMerkleRoot.ToString(),
            nTime, nBits, nNonce,
            vtx.size());
        for (const auto& tx : vtx) {
            s << "  " << tx->ToString() << "\n";
        }
        return s.str();
    }
    

    相关文章

      网友评论

        本文标题:比特币源码阅读(区块-CBlock)

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