github.com/klaytn/klaytn@v1.12.1/reward/staking_info_db.go (about)

     1  // Copyright 2020 The klaytn Authors
     2  // This file is part of the klaytn library.
     3  //
     4  // The klaytn 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 klaytn 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 klaytn library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package reward
    18  
    19  import (
    20  	"encoding/json"
    21  	"errors"
    22  )
    23  
    24  var ErrStakingDBNotSet = errors.New("stakingInfoDB is not set")
    25  
    26  type stakingInfoDB interface {
    27  	HasStakingInfo(blockNum uint64) (bool, error)
    28  	ReadStakingInfo(blockNum uint64) ([]byte, error)
    29  	WriteStakingInfo(blockNum uint64, stakingInfo []byte) error
    30  }
    31  
    32  // HasStakingInfoFromDB returns existence of staking information from miscdb.
    33  func HasStakingInfoFromDB(blockNumber uint64) (bool, error) {
    34  	if stakingManager.stakingInfoDB == nil {
    35  		return false, ErrStakingDBNotSet
    36  	}
    37  	return stakingManager.stakingInfoDB.HasStakingInfo(blockNumber)
    38  }
    39  
    40  func getStakingInfoFromDB(blockNum uint64) (*StakingInfo, error) {
    41  	if stakingManager.stakingInfoDB == nil {
    42  		return nil, ErrStakingDBNotSet
    43  	}
    44  
    45  	jsonByte, err := stakingManager.stakingInfoDB.ReadStakingInfo(blockNum)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	stakingInfo := new(StakingInfo)
    51  	if err = json.Unmarshal(jsonByte, stakingInfo); err != nil {
    52  		return nil, err
    53  	}
    54  	return stakingInfo, nil
    55  }
    56  
    57  func AddStakingInfoToDB(stakingInfo *StakingInfo) error {
    58  	if stakingManager.stakingInfoDB == nil {
    59  		return ErrStakingDBNotSet
    60  	}
    61  
    62  	marshaledStakingInfo, err := json.Marshal(stakingInfo)
    63  	if err != nil {
    64  		return err
    65  	}
    66  
    67  	err = stakingManager.stakingInfoDB.WriteStakingInfo(stakingInfo.BlockNum, marshaledStakingInfo)
    68  	if err != nil {
    69  		return err
    70  	}
    71  
    72  	return nil
    73  }