以太坊源碼研讀0x01GenesisBlock(創(chuàng)世區(qū)塊)

上次講了以太坊在mac下的本地編譯環(huán)境,從這次開始我們從創(chuàng)世區(qū)塊入手來逐步研讀以太坊核心的部分源代碼。

創(chuàng)世命令

geth --datadir data0 init genesis.json

  • geth main -->在/cmd/geth/main.go
  • --datadir data0 -->啟動創(chuàng)世命令后創(chuàng)建的專門儲存節(jié)點數(shù)據(jù)的文件目錄
  • init -->調(diào)用的是cmd/geth/chaincmd.go中的initCommand, initCommand調(diào)用的是initGenesis(ctx *cli.Context)
  • genesis.json -->創(chuàng)世區(qū)塊配置文件,與創(chuàng)世區(qū)塊的數(shù)據(jù)結(jié)構(gòu)一一對應(yīng)

廢話少說讀代碼

Genesis struct

首先,在我們還對源碼結(jié)構(gòu)不太熟悉的情況下,通過全局搜索來尋找關(guān)于創(chuàng)世區(qū)塊的結(jié)構(gòu)定義。

找啊找啊找朋友
// 創(chuàng)世區(qū)塊類結(jié)構(gòu),后面的是區(qū)塊對應(yīng)json字段名稱
type Genesis struct {
    // 配置文件,用于指定鏈的chainId(network id)
    Config     *params.ChainConfig `json:"config"`
    // 隨機數(shù),與Mixhash組合用于滿足POW算法要求
    Nonce      uint64              `json:"nonce"`
    // 時間戳
    Timestamp  uint64              `json:"timestamp"`
    // 區(qū)塊額外信息
    ExtraData  []byte              `json:"extraData"`
    // Gas消耗量限制
    GasLimit   uint64              `json:"gasLimit"   gencodec:"required"`
    // 區(qū)塊難度值
    Difficulty *big.Int            `json:"difficulty" gencodec:"required"`
    // 由上個區(qū)塊的一部分生成的Hash,和Nonce組合用于找到滿足POW算法的條件
    Mixhash    common.Hash         `json:"mixHash"`
    // 礦工地址
    Coinbase   common.Address      `json:"coinbase"`
    // 創(chuàng)世區(qū)塊初始狀態(tài)
    Alloc      GenesisAlloc        `json:"alloc"      gencodec:"required"`

    // These fields are used for consensus tests. Please don't use them
    // in actual genesis blocks.
    /** 下面字段用于共識測試,不要在創(chuàng)世區(qū)塊中使用
    */
    Number     uint64      `json:"number"`
    GasUsed    uint64      `json:"gasUsed"`
    // 父區(qū)塊哈希
    ParentHash common.Hash `json:"parentHash"`
}

SetupGenesisBlock

了解了創(chuàng)世區(qū)塊的數(shù)據(jù)結(jié)構(gòu)后,我們來看一下以太坊是如何啟動創(chuàng)世區(qū)塊的。

/**如果存儲的區(qū)塊鏈配置不兼容,將調(diào)用該方法更新。為了避免沖突,錯誤將會被作為參數(shù)返回,并且新的配置
和原有配置都會被返回。
*/
func SetupGenesisBlock(db ethdb.Database, genesis *Genesis) (*params.ChainConfig, common.Hash, error) {
    if genesis != nil && genesis.Config == nil {
        return params.AllEthashProtocolChanges, common.Hash{}, errGenesisNoConfig
    }

    // Just commit the new block if there is no stored genesis block.
    // 如果沒有存儲的genesis塊,只需提交新塊。
    stored := rawdb.ReadCanonicalHash(db, 0)    // 從數(shù)據(jù)庫中獲取genesis對應(yīng)的區(qū)塊
    if (stored == common.Hash{}) {
        if genesis == nil {
            // genesis和stored都為空,使用主網(wǎng)
            log.Info("Writing default main-net genesis block")
            genesis = DefaultGenesisBlock()
        } else {
            // 使用自定義的genesis配置
            log.Info("Writing custom genesis block")
        }
        // 創(chuàng)世區(qū)塊寫入數(shù)據(jù)庫
        block, err := genesis.Commit(db)
        return genesis.Config, block.Hash(), err
    }

    // Check whether the genesis block is already written.
    // 檢查創(chuàng)世區(qū)塊是否寫入成功
    if genesis != nil {
        // 獲取創(chuàng)世區(qū)塊哈希
        hash := genesis.ToBlock(nil).Hash()
        if hash != stored {
            return genesis.Config, hash, &GenesisMismatchError{stored, hash}
        }
    }

    // Get the existing chain configuration.
    // 獲取當(dāng)前區(qū)塊鏈相關(guān)配置
    newcfg := genesis.configOrDefault(stored)
    storedcfg := rawdb.ReadChainConfig(db, stored)
    if storedcfg == nil {
        // 讀取失敗,說明創(chuàng)世區(qū)塊寫入被中斷
        log.Warn("Found genesis block without chain config")
        rawdb.WriteChainConfig(db, stored, newcfg)
        return newcfg, stored, nil
    }
    // Special case: don't change the existing config of a non-mainnet chain if no new
    // config is supplied. These chains would get AllProtocolChanges (and a compat error)
    // if we just continued here.
    // 特殊情況:如果沒有新的配置,請勿更改非主網(wǎng)鏈的相關(guān)配置
    // 這些鏈會得到AllProtocolChanges以及compat error,如果我們繼續(xù)
    if genesis == nil && stored != params.MainnetGenesisHash {
        return storedcfg, stored, nil
    }

    // Check config compatibility and write the config. Compatibility errors
    // are returned to the caller unless we're already at block zero.
    // 檢查配置兼容性并寫入配置
    // 兼容性錯誤將返回給調(diào)用者,除非我們已經(jīng)處于塊0
    height := rawdb.ReadHeaderNumber(db, rawdb.ReadHeadHeaderHash(db))
    if height == nil {
        return newcfg, stored, fmt.Errorf("missing block number for head header hash")
    }
    compatErr := storedcfg.CheckCompatible(newcfg, *height)
    // 如果compatErr為空并且非高度為0的區(qū)塊,那么久不能更改genesis配置了
    if compatErr != nil && *height != 0 && compatErr.RewindTo != 0 {
        return newcfg, stored, compatErr
    }
    rawdb.WriteChainConfig(db, stored, newcfg)
    return newcfg, stored, nil
}

ToBlock

ToBlock方法使用genesis的數(shù)據(jù),使用基于內(nèi)存的數(shù)據(jù)庫,然后創(chuàng)建了一個block并返回。

// ToBlock, 這個方法使用genesis的數(shù)據(jù),使用基于內(nèi)存的數(shù)據(jù)庫,然后創(chuàng)建了一個block并返回。
func (g *Genesis) ToBlock(db ethdb.Database) *types.Block {
    if db == nil {
        db = ethdb.NewMemDatabase()
    }
    // 用genesis的數(shù)據(jù)給statedb賦值
    statedb, _ := state.New(common.Hash{}, state.NewDatabase(db))
    for addr, account := range g.Alloc {
        statedb.AddBalance(addr, account.Balance)
        statedb.SetCode(addr, account.Code)
        statedb.SetNonce(addr, account.Nonce)
        for key, value := range account.Storage {
            statedb.SetState(addr, key, value)
        }
    }
    root := statedb.IntermediateRoot(false)
    // 填充head值
    head := &types.Header{
        Number:     new(big.Int).SetUint64(g.Number),
        Nonce:      types.EncodeNonce(g.Nonce),
        Time:       new(big.Int).SetUint64(g.Timestamp),
        ParentHash: g.ParentHash,
        Extra:      g.ExtraData,
        GasLimit:   g.GasLimit,
        GasUsed:    g.GasUsed,
        Difficulty: g.Difficulty,
        MixDigest:  g.Mixhash,
        Coinbase:   g.Coinbase,
        Root:       root,
    }
    if g.GasLimit == 0 {
        head.GasLimit = params.GenesisGasLimit
    }
    if g.Difficulty == nil {
        head.Difficulty = params.GenesisDifficulty
    }

    // 數(shù)據(jù)庫提交
    statedb.Commit(false)
    statedb.Database().TrieDB().Commit(root, true)

    return types.NewBlock(head, nil, nil, nil)
}

Commit

上面兩個主要函數(shù)都用到了Commit方法,接下來我們就看下該方法到底做了哪些操作。

// Commit writes the block and state of a genesis specification to the database.
// The block is committed as the canonical head block.
// Commit方法調(diào)用rawdb.WriteChainConfig(db, block.Hash(), config)函數(shù)把給定的genesis的block
// 和state寫入數(shù)據(jù)庫,該block被認(rèn)為是規(guī)范的區(qū)塊鏈頭
func (g *Genesis) Commit(db ethdb.Database) (*types.Block, error) {
    
    // 取到genesis對應(yīng)的block
    block := g.ToBlock(db)
    if block.Number().Sign() != 0 {
        return nil, fmt.Errorf("can't commit genesis block with number > 0")
    }
    // 寫入總難度
    rawdb.WriteTd(db, block.Hash(), block.NumberU64(), g.Difficulty)
    // 寫入?yún)^(qū)塊
    rawdb.WriteBlock(db, block)
    // 寫入?yún)^(qū)塊數(shù)據(jù)
    rawdb.WriteReceipts(db, block.Hash(), block.NumberU64(), nil)
    // 寫入 headerPrefix + num (uint64 big endian) + numSuffix -> hash
    rawdb.WriteCanonicalHash(db, block.Hash(), block.NumberU64())
    rawdb.WriteHeadBlockHash(db, block.Hash())
    rawdb.WriteHeadHeaderHash(db, block.Hash())

    config := g.Config
    if config == nil {
        config = params.AllEthashProtocolChanges
    }
    // 寫入 ethereum-config-hash -> config
    rawdb.WriteChainConfig(db, block.Hash(), config)
    return block, nil
}

各種模式的GenesisBlock


// 各種返回模式的Genesis
// GenesisBlockForTesting creates and writes a block in which addr has the given wei balance.
// GenesisBlockForTesting創(chuàng)建并寫入一個塊,其中addr具有給定的wei余額。
func GenesisBlockForTesting(db ethdb.Database, addr common.Address, balance *big.Int) *types.Block {
    g := Genesis{Alloc: GenesisAlloc{addr: {Balance: balance}}}
    return g.MustCommit(db)
}

// DefaultGenesisBlock returns the Ethereum main net genesis block.
// DefaultGenesisBlock返回以太坊主網(wǎng)絡(luò)創(chuàng)世塊
func DefaultGenesisBlock() *Genesis {
    return &Genesis{
        Config:     params.MainnetChainConfig,
        Nonce:      66,
        ExtraData:  hexutil.MustDecode("0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa"),
        GasLimit:   5000,
        Difficulty: big.NewInt(17179869184),
        Alloc:      decodePrealloc(mainnetAllocData),
    }
}

// DefaultTestnetGenesisBlock returns the Ropsten network genesis block.
// DefaultTestnetGenesisBlock返回Ropsten網(wǎng)絡(luò)創(chuàng)世塊。
func DefaultTestnetGenesisBlock() *Genesis {
    return &Genesis{
        Config:     params.TestnetChainConfig,
        Nonce:      66,
        ExtraData:  hexutil.MustDecode("0x3535353535353535353535353535353535353535353535353535353535353535"),
        GasLimit:   16777216,
        Difficulty: big.NewInt(1048576),
        Alloc:      decodePrealloc(testnetAllocData),
    }
}

// DefaultRinkebyGenesisBlock returns the Rinkeby network genesis block.
// DefaultRinkebyGenesisBlock返回Rinkeby網(wǎng)絡(luò)創(chuàng)世塊。
func DefaultRinkebyGenesisBlock() *Genesis {
    return &Genesis{
        Config:     params.RinkebyChainConfig,
        Timestamp:  1492009146,
        ExtraData:  hexutil.MustDecode("0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
        GasLimit:   4700000,
        Difficulty: big.NewInt(1),
        Alloc:      decodePrealloc(rinkebyAllocData),
    }
}

// DeveloperGenesisBlock returns the 'geth --dev' genesis block. Note, this must
// be seeded with the
// eveloperGenesisBlock返回'geth --dev'創(chuàng)世塊。
func DeveloperGenesisBlock(period uint64, faucet common.Address) *Genesis {
    // Override the default period to the user requested one
    config := *params.AllCliqueProtocolChanges
    config.Clique.Period = period

    // Assemble and return the genesis with the precompiles and faucet pre-funded
    return &Genesis{
        Config:     &config,
        ExtraData:  append(append(make([]byte, 32), faucet[:]...), make([]byte, 65)...),
        GasLimit:   6283185,
        Difficulty: big.NewInt(1),
        Alloc: map[common.Address]GenesisAccount{
            common.BytesToAddress([]byte{1}): {Balance: big.NewInt(1)}, // ECRecover
            common.BytesToAddress([]byte{2}): {Balance: big.NewInt(1)}, // SHA256
            common.BytesToAddress([]byte{3}): {Balance: big.NewInt(1)}, // RIPEMD
            common.BytesToAddress([]byte{4}): {Balance: big.NewInt(1)}, // Identity
            common.BytesToAddress([]byte{5}): {Balance: big.NewInt(1)}, // ModExp
            common.BytesToAddress([]byte{6}): {Balance: big.NewInt(1)}, // ECAdd
            common.BytesToAddress([]byte{7}): {Balance: big.NewInt(1)}, // ECScalarMul
            common.BytesToAddress([]byte{8}): {Balance: big.NewInt(1)}, // ECPairing
            faucet: {Balance: new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 256), big.NewInt(9))},
        },
    }
}

對創(chuàng)世區(qū)塊的源碼分析就到這,下次我們通過聯(lián)盟鏈來大概認(rèn)識下go的以太坊客戶端geth的基本功能,依次來了解以太坊核心功能。

更多以太坊源碼解析請移駕全球最大同性交友網(wǎng),覺得有用記得給個小star哦??????

.
.
.
.

互聯(lián)網(wǎng)顛覆世界,區(qū)塊鏈顛覆互聯(lián)網(wǎng)!

--------------------------------------------------20180904 23:11
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容