certichain

Blockchain built from scratch for verifying document's legitimacy.
Log | Files | Refs | README | LICENSE

commit 9b25ec66706414de2a9c5d82821622719b78cbf6
parent 51d116ead12acb209476193bcfc1610ee7b60122
Author: Shivakumar <[email protected]>
Date:   Sat, 30 May 2026 15:36:26 +0530

feat(storage): add badger store and unit tests

Signed-off-by: Shivakumar <[email protected]>

Diffstat:
Ainternal/storage/badger.go | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainternal/storage/memory.go | 166+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainternal/storage/storage_test.go | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainternal/storage/store.go | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
4 files changed, 574 insertions(+), 0 deletions(-)

diff --git a/internal/storage/badger.go b/internal/storage/badger.go @@ -0,0 +1,176 @@ +// Copyright 2026 Shivakumar (Certichain) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package storage + +import ( + "errors" + "fmt" + + "github.com/dgraph-io/badger/v4" +) + +// badgerStore is the concrete implementation of the Store interface using BadgerDB. +type badgerStore struct { + db *badger.DB +} + +// NewBadgerStore opens or creates a BadgerDB at the given path. +// It returns a Store interface to prevent callers from depending on the concrete type. +func NewBadgerStore(path string) (Store, error) { + opts := badger.DefaultOptions(path). + WithLogger(nil). // Suppress verbose Badger logs + WithSyncWrites(true) // Ensure writes are flushed to disk + + db, err := badger.Open(opts) + if err != nil { + return nil, fmt.Errorf("storage: failed to open badger at %s: %w", path, err) + } + + return &badgerStore{db: db}, nil +} + +// Get reads a value by its key. Returns ErrNotFound if the key does not exist. +func (s *badgerStore) Get(key []byte) ([]byte, error) { + if s.db == nil { + return nil, ErrClosed + } + if len(key) == 0 { + return nil, ErrEmptyKey + } + + var val []byte + err := s.db.View(func(txn *badger.Txn) error { + item, err := txn.Get(key) + if err != nil { + return err + } + val, err = item.ValueCopy(nil) + return err + }) + if err != nil { + if errors.Is(err, badger.ErrKeyNotFound) { + return nil, ErrNotFound + } + return nil, fmt.Errorf("storage: get failed: %w", err) + } + + return val, nil +} + +// Set writes a key-value pair. Validates that both key and value are non-empty. +func (s *badgerStore) Set(key, value []byte) error { + if s.db == nil { + return ErrClosed + } + if len(key) == 0 { + return ErrEmptyKey + } + if len(value) == 0 { + return ErrEmptyValue + } + + err := s.db.Update(func(txn *badger.Txn) error { + return txn.Set(key, value) + }) + if err != nil { + return fmt.Errorf("storage: set failed: %w", err) + } + return nil +} + +// Delete removes a key from the database. +func (s *badgerStore) Delete(key []byte) error { + if s.db == nil { + return ErrClosed + } + if len(key) == 0 { + return ErrEmptyKey + } + + err := s.db.Update(func(txn *badger.Txn) error { + return txn.Delete(key) + }) + if err != nil { + return fmt.Errorf("storage: delete failed: %w", err) + } + return nil +} + +// Has checks for the existence of a key without reading its value. +func (s *badgerStore) Has(key []byte) (bool, error) { + if s.db == nil { + return false, ErrClosed + } + if len(key) == 0 { + return false, ErrEmptyKey + } + + err := s.db.View(func(txn *badger.Txn) error { + _, err := txn.Get(key) + return err + }) + + if err == nil { + return true, nil + } + if errors.Is(err, badger.ErrKeyNotFound) { + return false, nil + } + + return false, fmt.Errorf("storage: has check failed: %w", err) +} + +// Iterate loops over all keys starting with the given prefix, executing fn for each. +// Iteration stops if fn returns an error. +func (s *badgerStore) Iterate(prefix []byte, fn func(key, value []byte) error) error { + if s.db == nil { + return ErrClosed + } + + return s.db.View(func(txn *badger.Txn) error { + opts := badger.DefaultIteratorOptions + it := txn.NewIterator(opts) + defer it.Close() + + for it.Seek(prefix); it.ValidForPrefix(prefix); it.Next() { + item := it.Item() + key := item.KeyCopy(nil) + val, err := item.ValueCopy(nil) + if err != nil { + return fmt.Errorf("storage: iteration value read failed: %w", err) + } + + if err := fn(key, val); err != nil { + return err + } + } + return nil + }) +} + +// Close gracefully shuts down the database. It is safe to call multiple times. +func (s *badgerStore) Close() error { + if s.db == nil { + return nil + } + + err := s.db.Close() + s.db = nil // Prevent subsequent operations from using a closed DB + + if err != nil { + return fmt.Errorf("storage: close failed: %w", err) + } + return nil +} diff --git a/internal/storage/memory.go b/internal/storage/memory.go @@ -0,0 +1,166 @@ +// Copyright 2026 Shivakumar (Certichain) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package storage + +import ( + "bytes" + "slices" + "strings" + "sync" +) + +// memoryStore is an in-memory implementation of the Store interface. +// It is intended for testing and should not be used in production. +type memoryStore struct { + mu sync.RWMutex + data map[string][]byte + closed bool +} + +// newMemoryStore creates a new instance of an in-memory store. +// It is unexported to ensure it is only used for internal tests. +func newMemoryStore() Store { + return &memoryStore{ + data: make(map[string][]byte), + } +} + +// Get retrieves a value from the map. +func (m *memoryStore) Get(key []byte) ([]byte, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if m.closed { + return nil, ErrClosed + } + if len(key) == 0 { + return nil, ErrEmptyKey + } + + val, ok := m.data[string(key)] + if !ok { + return nil, ErrNotFound + } + + // Return a clone to mimic Badger's ValueCopy behavior and ensure immutability. + return bytes.Clone(val), nil +} + +// Set stores a value in the map. +func (m *memoryStore) Set(key, value []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + + if m.closed { + return ErrClosed + } + if len(key) == 0 { + return ErrEmptyKey + } + if len(value) == 0 { + return ErrEmptyValue + } + + // Store a clone to prevent the caller from modifying the data later. + m.data[string(key)] = bytes.Clone(value) + + return nil +} + +// Delete removes a key from the map. +func (m *memoryStore) Delete(key []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + + if m.closed { + return ErrClosed + } + if len(key) == 0 { + return ErrEmptyKey + } + + delete(m.data, string(key)) + return nil +} + +// Has checks if a key exists in the map. +func (m *memoryStore) Has(key []byte) (bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + if m.closed { + return false, ErrClosed + } + if len(key) == 0 { + return false, ErrEmptyKey + } + + _, ok := m.data[string(key)] + return ok, nil +} + +// Iterate simulates prefix iteration by sorting map keys. +func (m *memoryStore) Iterate(prefix []byte, fn func(key, value []byte) error) error { + m.mu.RLock() + if m.closed { + m.mu.RUnlock() + return ErrClosed + } + + // Extract keys that match the prefix. + var keys []string + prefixStr := string(prefix) + for k := range m.data { + if strings.HasPrefix(k, prefixStr) { + keys = append(keys, k) + } + } + slices.Sort(keys) + m.mu.RUnlock() + + // Execute callback on sorted keys. + for _, k := range keys { + m.mu.RLock() + if m.closed { + m.mu.RUnlock() + return ErrClosed + } + val, ok := m.data[k] + if !ok { + // Key might have been deleted between the lock cycles. + m.mu.RUnlock() + continue + } + // Safe clones for the callback. + cpKey := []byte(k) + cpVal := bytes.Clone(val) + m.mu.RUnlock() + + if err := fn(cpKey, cpVal); err != nil { + return err + } + } + + return nil +} + +// Close marks the store as closed. +func (m *memoryStore) Close() error { + m.mu.Lock() + defer m.mu.Unlock() + + m.closed = true + return nil +} diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go @@ -0,0 +1,175 @@ +// Copyright 2026 Shivakumar (Certichain) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package storage + +import ( + "bytes" + "errors" + "testing" +) + +// runStoreSuite defines a comprehensive set of tests that any Store implementation must pass. +func runStoreSuite(t *testing.T, s Store) { + t.Run("Set and Get returns same value", func(t *testing.T) { + key, want := []byte("KEY"), []byte("VAL") + if err := s.Set(key, want); err != nil { + t.Fatalf("failed to set: %v", err) + } + + got, err := s.Get(key) + if err != nil { + t.Fatalf("failed to get: %v", err) + } + + if !bytes.Equal(got, want) { + t.Errorf("value mismatch: got %s, want %s", got, want) + } + }) + + t.Run("Get missing key returns ErrNotFound", func(t *testing.T) { + if _, err := s.Get([]byte("MISSING")); !errors.Is(err, ErrNotFound) { + t.Errorf("expected ErrNotFound, got %v", err) + } + }) + + t.Run("Has behavior", func(t *testing.T) { + key := []byte("HAS_KEY") + + // Check before set + has, err := s.Has(key) + if err != nil { + t.Fatalf("Has failed: %v", err) + } + if has { + t.Error("Has returned true for non-existent key") + } + + // Check after set + if err := s.Set(key, []byte("VAL")); err != nil { + t.Fatalf("Set failed: %v", err) + } + has, err = s.Has(key) + if err != nil { + t.Fatalf("Has failed: %v", err) + } + if !has { + t.Error("Has returned false for existing key") + } + }) + + t.Run("Delete removes key", func(t *testing.T) { + key := []byte("DEL_KEY") + s.Set(key, []byte("VAL")) + + if err := s.Delete(key); err != nil { + t.Fatalf("Delete failed: %v", err) + } + + if _, err := s.Get(key); !errors.Is(err, ErrNotFound) { + t.Errorf("expected ErrNotFound after delete, got %v", err) + } + + // Delete on non-existent key should not error + if err := s.Delete([]byte("NON_EXISTENT")); err != nil { + t.Errorf("Delete non-existent key returned error: %v", err) + } + }) + + t.Run("Empty key guards", func(t *testing.T) { + if err := s.Set(nil, []byte("VAL")); !errors.Is(err, ErrEmptyKey) { + t.Errorf("Set nil key: expected ErrEmptyKey, got %v", err) + } + if err := s.Set([]byte{}, []byte("VAL")); !errors.Is(err, ErrEmptyKey) { + t.Errorf("Set empty key: expected ErrEmptyKey, got %v", err) + } + if _, err := s.Get(nil); !errors.Is(err, ErrEmptyKey) { + t.Errorf("Get nil key: expected ErrEmptyKey, got %v", err) + } + }) + + t.Run("Iterate respects prefix", func(t *testing.T) { + // Setup mixed keys + keys := [][]byte{ + []byte("a:1"), []byte("a:2"), []byte("b:1"), + } + for _, k := range keys { + s.Set(k, []byte("VAL")) + } + + count := 0 + err := s.Iterate([]byte("a:"), func(k, v []byte) error { + if !bytes.HasPrefix(k, []byte("a:")) { + t.Errorf("iterator visited key without prefix: %s", k) + } + count++ + return nil + }) + if err != nil { + t.Fatalf("Iterate failed: %v", err) + } + if count != 2 { + t.Errorf("expected 2 keys with prefix 'a:', got %d", count) + } + }) + + t.Run("Iterate error propagation", func(t *testing.T) { + s.Set([]byte("err:1"), []byte("VAL")) + customErr := errors.New("stop") + + err := s.Iterate([]byte("err:"), func(k, v []byte) error { + return customErr + }) + + if !errors.Is(err, customErr) { + t.Errorf("expected custom error to be propagated, got %v", err) + } + }) + + t.Run("Immutability via Cloning", func(t *testing.T) { + key := []byte("MUTATE_KEY") + original := []byte("ORIGINAL") + s.Set(key, original) + + got, _ := s.Get(key) + // Mutate the returned slice + got[0] = 'X' + + // Verify stored value is unchanged + secondGot, _ := s.Get(key) + if bytes.Equal(original, got) { + t.Error("mutating Get result affected original byte array (unexpected match)") + } + if !bytes.Equal(original, secondGot) { + t.Error("stored value was mutated through Get result") + } + }) +} + +func TestBadgerStore(t *testing.T) { + store, err := NewBadgerStore(t.TempDir()) + if err != nil { + t.Fatalf("failed to create badger store: %v", err) + } + defer store.Close() + + runStoreSuite(t, store) +} + +func TestMemoryStore(t *testing.T) { + store := newMemoryStore() + defer store.Close() + + runStoreSuite(t, store) +} diff --git a/internal/storage/store.go b/internal/storage/store.go @@ -0,0 +1,57 @@ +// Copyright 2026 Shivakumar (Certichain) +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package storage + +import "errors" + +// Store defines the interface for the blockchain's key-value storage layer. +// It provides basic CRUD operations and prefix-based iteration. +type Store interface { + Get(key []byte) ([]byte, error) + Set(key, value []byte) error + Delete(key []byte) error + Has(key []byte) (bool, error) + Iterate(prefix []byte, fn func(key, value []byte) error) error + Close() error +} + +var ( + ErrNotFound = errors.New("storage: key not found") + ErrEmptyKey = errors.New("storage: empty key") + ErrEmptyValue = errors.New("storage: empty value") + ErrClosed = errors.New("storage: store not initialized or closed") +) + +const ( + PrefixBlock = "block:" + PrefixTransaction = "tx:" + LastHashKey = "chain:last_hash" + PrefixBatch = "batch:" +) + +// BlockKey returns the database key for a block hash by prepending the block prefix. +func BlockKey(hash []byte) []byte { + return append([]byte(PrefixBlock), hash...) +} + +// TxKey returns the database key for a transaction ID by prepending the transaction prefix. +func TxKey(txID []byte) []byte { + return append([]byte(PrefixTransaction), txID...) +} + +// BatchKey returns the database key for a batch ID by prepending the batch prefix. +func BatchKey(batchID string) []byte { + return append([]byte(PrefixBatch), []byte(batchID)...) +}