github.com/amazechain/amc@v0.1.3/modules/rawdb/accessors_metadata.go (about)

     1  // Copyright 2023 The AmazeChain Authors
     2  // This file is part of the AmazeChain library.
     3  //
     4  // The AmazeChain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The AmazeChain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rawdb
    18  
    19  import (
    20  	"encoding/json"
    21  	"fmt"
    22  	"github.com/amazechain/amc/common/types"
    23  	"github.com/amazechain/amc/log"
    24  	"github.com/amazechain/amc/modules"
    25  
    26  	"github.com/amazechain/amc/params"
    27  	"github.com/ledgerwatch/erigon-lib/kv"
    28  )
    29  
    30  // ReadChainConfig retrieves the consensus settings based on the given genesis hash.
    31  func ReadChainConfig(db kv.Getter, hash types.Hash) (*params.ChainConfig, error) {
    32  	data, err := db.GetOne(modules.ChainConfig, modules.ConfigKey(hash))
    33  	if err != nil {
    34  		return nil, fmt.Errorf("fetch ChainConfig from db ,error: %v", err)
    35  	}
    36  	if len(data) == 0 {
    37  		return nil, fmt.Errorf("ChainConfig are empty")
    38  	}
    39  	var config params.ChainConfig
    40  	if err := json.Unmarshal(data, &config); err != nil {
    41  		return nil, fmt.Errorf("invalid chain config JSON err: %v", err)
    42  	}
    43  	return &config, nil
    44  }
    45  
    46  // WriteChainConfig writes the chain config settings to the database.
    47  func WriteChainConfig(db kv.RwTx, hash types.Hash, cfg *params.ChainConfig) error {
    48  	if cfg == nil {
    49  		return fmt.Errorf("invalid cfg")
    50  	}
    51  	data, err := json.Marshal(cfg)
    52  	if err != nil {
    53  		log.Error("Failed to JSON encode chain config", "err", err)
    54  		return err
    55  	}
    56  	if err := db.Put(modules.ChainConfig, modules.ConfigKey(hash), data); err != nil {
    57  		log.Error("Failed to store chain config", "err", err)
    58  		return err
    59  	}
    60  	return nil
    61  }