github.com/johnathanhowell/sia@v0.5.1-beta.0.20160524050156-83dcc3d37c94/modules/miner/persist.go (about)

     1  package miner
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  
     7  	"github.com/NebulousLabs/Sia/modules"
     8  	"github.com/NebulousLabs/Sia/persist"
     9  	"github.com/NebulousLabs/Sia/types"
    10  )
    11  
    12  const (
    13  	logFile      = modules.MinerDir + ".log"
    14  	settingsFile = modules.MinerDir + ".json"
    15  )
    16  
    17  var (
    18  	settingsMetadata = persist.Metadata{
    19  		Header:  "Miner Settings",
    20  		Version: "0.5.0",
    21  	}
    22  )
    23  
    24  type (
    25  	// persist contains all of the persistent miner data.
    26  	persistence struct {
    27  		RecentChange  modules.ConsensusChangeID
    28  		Height        types.BlockHeight
    29  		Target        types.Target
    30  		Address       types.UnlockHash
    31  		BlocksFound   []types.BlockID
    32  		UnsolvedBlock types.Block
    33  	}
    34  )
    35  
    36  // initSettings loads the settings file if it exists and creates it if it
    37  // doesn't.
    38  func (m *Miner) initSettings() error {
    39  	filename := filepath.Join(m.persistDir, settingsFile)
    40  	_, err := os.Stat(filename)
    41  	if os.IsNotExist(err) {
    42  		return m.save()
    43  	} else if err != nil {
    44  		return err
    45  	}
    46  	return m.load()
    47  }
    48  
    49  // initPersist initializes the persistence of the miner.
    50  func (m *Miner) initPersist() error {
    51  	// Create the miner directory.
    52  	err := os.MkdirAll(m.persistDir, 0700)
    53  	if err != nil {
    54  		return err
    55  	}
    56  
    57  	// Add a logger.
    58  	m.log, err = persist.NewFileLogger(filepath.Join(m.persistDir, logFile))
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	return m.initSettings()
    64  }
    65  
    66  // load loads the miner persistence from disk.
    67  func (m *Miner) load() error {
    68  	return persist.LoadFile(settingsMetadata, &m.persist, filepath.Join(m.persistDir, settingsFile))
    69  }
    70  
    71  // save saves the miner persistence to disk.
    72  func (m *Miner) save() error {
    73  	return persist.SaveFile(settingsMetadata, m.persist, filepath.Join(m.persistDir, settingsFile))
    74  }
    75  
    76  // saveSync saves the miner persistence to disk, and then syncs to disk.
    77  func (m *Miner) saveSync() error {
    78  	return persist.SaveFileSync(settingsMetadata, m.persist, filepath.Join(m.persistDir, settingsFile))
    79  }