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

     1  package consensus
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"path/filepath"
     7  
     8  	"github.com/NebulousLabs/Sia/build"
     9  	"github.com/NebulousLabs/Sia/modules"
    10  	"github.com/NebulousLabs/Sia/persist"
    11  
    12  	"github.com/NebulousLabs/bolt"
    13  )
    14  
    15  const (
    16  	// DatabaseFilename contains the filename of the database that will be used
    17  	// when managing consensus.
    18  	DatabaseFilename = modules.ConsensusDir + ".db"
    19  	logFile          = modules.ConsensusDir + ".log"
    20  )
    21  
    22  // loadDB pulls all the blocks that have been saved to disk into memory, using
    23  // them to fill out the ConsensusSet.
    24  func (cs *ConsensusSet) loadDB() error {
    25  	// Open the database - a new bolt database will be created if none exists.
    26  	err := cs.openDB(filepath.Join(cs.persistDir, DatabaseFilename))
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	// Walk through initialization for Sia.
    32  	return cs.db.Update(func(tx *bolt.Tx) error {
    33  		// Check if the database has been initialized.
    34  		if !dbInitialized(tx) {
    35  			return cs.initDB(tx)
    36  		}
    37  
    38  		// Check that inconsistencies have not been detected in the database.
    39  		if inconsistencyDetected(tx) {
    40  			return errors.New("database contains inconsistencies")
    41  		}
    42  
    43  		// Check that the genesis block is correct - typically only incorrect
    44  		// in the event of developer binaries vs. release binaires.
    45  		genesisID, err := getPath(tx, 0)
    46  		if build.DEBUG && err != nil {
    47  			panic(err)
    48  		}
    49  		if genesisID != cs.blockRoot.Block.ID() {
    50  			return errors.New("Blockchain has wrong genesis block, exiting.")
    51  		}
    52  		return nil
    53  	})
    54  }
    55  
    56  // initPersist initializes the persistence structures of the consensus set, in
    57  // particular loading the database and preparing to manage subscribers.
    58  func (cs *ConsensusSet) initPersist() error {
    59  	// Create the consensus directory.
    60  	err := os.MkdirAll(cs.persistDir, 0700)
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	// Initialize the logger.
    66  	cs.log, err = persist.NewFileLogger(filepath.Join(cs.persistDir, logFile))
    67  	if err != nil {
    68  		return err
    69  	}
    70  
    71  	// Try to load an existing database from disk - a new one will be created
    72  	// if one does not exist.
    73  	err = cs.loadDB()
    74  	if err != nil {
    75  		return err
    76  	}
    77  	return nil
    78  }