github.com/Night-mk/quorum@v21.1.0+incompatible/extension/data_handler.go (about)

     1  package extension
     2  
     3  import (
     4  	"encoding/json"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/ethereum/go-ethereum/common"
    10  	"github.com/ethereum/go-ethereum/log"
    11  )
    12  
    13  const extensionContractData = "activeExtensions.json"
    14  
    15  type DataHandler interface {
    16  	Load() (map[common.Address]*ExtensionContract, error)
    17  
    18  	Save(extensionContracts map[common.Address]*ExtensionContract) error
    19  }
    20  
    21  type JsonFileDataHandler struct {
    22  	saveFile string
    23  }
    24  
    25  func NewJsonFileDataHandler(dataDirectory string) *JsonFileDataHandler {
    26  	return &JsonFileDataHandler{
    27  		saveFile: filepath.Join(dataDirectory, extensionContractData),
    28  	}
    29  }
    30  
    31  func (handler *JsonFileDataHandler) Load() (map[common.Address]*ExtensionContract, error) {
    32  	currentContracts := make(map[common.Address]*ExtensionContract)
    33  	if _, err := os.Stat(handler.saveFile); err == nil || !os.IsNotExist(err) {
    34  		blob, err := ioutil.ReadFile(handler.saveFile)
    35  		if err != nil {
    36  			return nil, err
    37  		}
    38  
    39  		if err = json.Unmarshal(blob, &currentContracts); err != nil {
    40  			return nil, err
    41  		}
    42  	}
    43  	return currentContracts, nil
    44  }
    45  
    46  func (handler *JsonFileDataHandler) Save(extensionContracts map[common.Address]*ExtensionContract) error {
    47  	//no unmarshallable types, so can't error
    48  	output, _ := json.Marshal(&extensionContracts)
    49  
    50  	if errSaving := ioutil.WriteFile(handler.saveFile, output, 0644); errSaving != nil {
    51  		log.Error("Couldn't save outstanding extension contract details")
    52  		return errSaving
    53  	}
    54  	return nil
    55  }