Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement/consensus/database.go #23 #33

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 61 additions & 19 deletions consensus/database.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,63 @@
package consensus

// uses config mmodule
import (
"errors"
"github.com/BlocSoc-iitr/selene/config"
"os"
"path/filepath"
)
type Database interface {
new()
save_checkpoint()
load_checkpoint()
}

// NOTE: parameters are not included
type FileDB struct{ Database }

func (f FileDB) new() FileDB {}
func (f FileDB) save_checkpoint() FileDB {}
func (f FileDB) load_checkpoint() FileDB {}

type ConfigDB struct{ Database }

func (cdb ConfigDB) new() ConfigDB {}
func (cdb ConfigDB) save_checkpoint() ConfigDB {}
func (cdb ConfigDB) load_checkpoint() ConfigDB {}
New(cfg *config.BaseConfig) (Database, error)
SaveCheckpoint(checkpoint []byte) error
LoadCheckpoint() ([]byte, error)
}
type FileDB struct {
DataDir string
defaultCheckpoint [32]byte
}
func (f *FileDB) New(cfg *config.BaseConfig) (Database, error) {
if cfg.DataDir == nil || *cfg.DataDir == "" {
return nil, errors.New("data directory is not set in the config")
}
return &FileDB{
DataDir: *cfg.DataDir,
defaultCheckpoint: cfg.DefaultCheckpoint,
}, nil
}
func (f *FileDB) SaveCheckpoint(checkpoint []byte) error {
err := os.MkdirAll(f.DataDir, os.ModePerm)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(f.DataDir, "checkpoint"), checkpoint, 0644)
}
func (f *FileDB) LoadCheckpoint() ([]byte, error) {
data, err := os.ReadFile(filepath.Join(f.DataDir, "checkpoint"))
if err != nil {
if os.IsNotExist(err) {
return f.defaultCheckpoint[:], nil
}
return nil, err
}
if len(data) == 32 {
return data, nil
}
return f.defaultCheckpoint[:], nil
}
type ConfigDB struct {
checkpoint [32]byte
}
func (c *ConfigDB) New(cfg *config.BaseConfig) (Database, error) {
checkpoint := cfg.DefaultCheckpoint
if cfg.DataDir == nil {
return nil, errors.New("data directory is not set in the config")
}
return &ConfigDB{
checkpoint: checkpoint,
}, nil
}
func (c *ConfigDB) SaveCheckpoint(checkpoint []byte) error {
return nil
}
func (c *ConfigDB) LoadCheckpoint() ([]byte, error) {
return c.checkpoint[:], nil
}
Loading