From d60df6531ac22963dcc0f7b966e76f0fa0400f6d Mon Sep 17 00:00:00 2001 From: stinkymonkeyph Date: Mon, 29 Jul 2024 20:32:43 +0800 Subject: [PATCH] feat: add initial implementation of persistent state --- blockchain/blockchain.go | 11 ++++++++++- blockchain/store.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go index 56d738e..bda00fa 100644 --- a/blockchain/blockchain.go +++ b/blockchain/blockchain.go @@ -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) diff --git a/blockchain/store.go b/blockchain/store.go index bc2782f..622f3d1 100644 --- a/blockchain/store.go +++ b/blockchain/store.go @@ -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 +}