Skip to content

Commit

Permalink
feat: add initial implementation of persistent state
Browse files Browse the repository at this point in the history
  • Loading branch information
stinkymonkeyph committed Jul 29, 2024
1 parent e80c0a6 commit d60df65
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
11 changes: 10 additions & 1 deletion blockchain/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,16 @@ type Blockchain struct {
}

func NewBlockchain(genesisBlock *Block) *Blockchain {
bc := new(Blockchain)
state, err := ReadFromDb()
bc := &Blockchain{}

if err != nil {
bc = new(Blockchain)
} else {
log.Println("Found existing blockchain state, persisting state from datastore")
bc = &state
}

bc.TransactionPool = []*Transaction{}
bc.Blocks = append(bc.Blocks, genesisBlock)

Expand Down
36 changes: 36 additions & 0 deletions blockchain/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,39 @@ func PutIntoDb(bc *Blockchain) error {

return nil
}

func ReadFromDb() (Blockchain, error) {
var bc Blockchain

db, err := badger.Open(badger.DefaultOptions(constants.DB_PATH))

if err != nil {
return bc, err
}

defer db.Close()

err = db.View(func(txn *badger.Txn) error {
item, err := txn.Get([]byte(constants.DB_KEY))
if err != nil {
return err
}
val, err := item.ValueCopy(nil)
if err != nil {
return err
}

err = json.Unmarshal(val, &bc)

if err != nil {
return err
}
return nil
})

if err != nil {
return bc, err
}

return bc, nil
}

0 comments on commit d60df65

Please sign in to comment.