commit 6fcd69369a4a467e071c3ee297c81a3a1b902412
parent 6ccda1ac21cff250560afa00a8d1da53059ceba3
Author: Shivakumar <[email protected]>
Date: Tue, 16 Jun 2026 03:35:33 +0530
test(blockchain): add tests to blockchain
Signed-off-by: Shivakumar <[email protected]>
Diffstat:
2 files changed, 801 insertions(+), 0 deletions(-)
diff --git a/internal/blockchain/blockchain_test.go b/internal/blockchain/blockchain_test.go
@@ -0,0 +1,641 @@
+// 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 blockchain
+
+import (
+ "bytes"
+ "errors"
+ "slices"
+ "sync"
+ "testing"
+ "time"
+
+ "certichain/internal/crypto"
+ "certichain/internal/storage"
+)
+
+// Genesis Unit-tests
+
+func TestNew(t *testing.T) {
+ t.Parallel()
+
+ t.Run("Initialization", func(t *testing.T) {
+ t.Parallel()
+
+ fixedTime := time.Date(2010, 11, 6, 0, 0, 0, 0, time.UTC).Unix()
+
+ tests := []struct {
+ name string
+ opts []Option
+ validate func(*testing.T, *Blockchain)
+ }{
+ {
+ name: "CreateGenesis",
+ opts: nil,
+ validate: func(
+ t *testing.T,
+ bc *Blockchain,
+ ) {
+ count := 0
+ for b, err := range bc.Blocks() {
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b.Header.Height != 0 || !b.Header.PrevHash.IsZero() {
+ t.Error("invalid genesis block structure")
+ }
+ count++
+ }
+ if count != 1 {
+ t.Errorf("expected 1 block, got %d", count)
+ }
+ },
+ },
+ {
+ name: "WithCustomTime",
+ opts: []Option{
+ WithGenesisTime(fixedTime),
+ },
+ validate: func(
+ t *testing.T,
+ bc *Blockchain,
+ ) {
+ g, err := bc.GetBlockByHeight(0)
+ if err != nil {
+ t.Fatalf("GetBlockByHeight(0) unexpected error: %v", err)
+ }
+ if g.Header.TimeStamp != fixedTime {
+ t.Errorf("time mismatch: want %d, got %d", fixedTime, g.Header.TimeStamp)
+ }
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ bc := mustNewMemoryChain(t, tt.opts...)
+ tt.validate(t, bc)
+ })
+ }
+ })
+
+ t.Run("GenesisIsDeterministic", func(t *testing.T) {
+ t.Parallel()
+
+ timestamp := time.Date(2010, 11, 6, 0, 0, 0, 0, time.UTC).Unix()
+ h1 := mustNewMemoryChain(t, WithGenesisTime(timestamp)).LastHash()
+ h2 := mustNewMemoryChain(t, WithGenesisTime(timestamp)).LastHash()
+
+ if !bytes.Equal(h1, h2) {
+ t.Error("hash mismatch for identical timestamp")
+ }
+ })
+}
+
+func TestNew_ExistingChain(t *testing.T) {
+ t.Parallel()
+
+ store := storage.NewMemoryStore()
+ t.Cleanup(func() { store.Close() })
+
+ tip := func() []byte {
+ bc := mustNewChain(t, store)
+ mustAddBlock(t, bc, mustTx(t))
+ return bc.LastHash()
+ }()
+
+ bc := mustNewChain(t, store)
+ if bc.Height() != 1 {
+ t.Errorf("height: want 1, got %d", bc.Height())
+ }
+ if !bytes.Equal(bc.LastHash(), tip) {
+ t.Error("lastHash mismatch after resumption")
+ }
+}
+
+// AddBlock Unit-tests
+
+func TestAddBlock_Validation(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ txs txList
+ wantError error
+ }{
+ {
+ name: "NilTransactionSlice",
+ txs: nil,
+ wantError: ErrNilTransactions,
+ },
+ {
+ name: "EmptyTransactionSlice",
+ txs: txList{},
+ wantError: ErrEmptyBlock,
+ },
+ {
+ name: "NilTransactionEntry",
+ txs: txList{mustTx(t), nil},
+ wantError: ErrNilTransactionEntry,
+ },
+ {
+ name: "UnsignedTransaction",
+ txs: txList{mustTx(t, WithUnsigned())},
+ wantError: ErrUnsignedTx,
+ },
+ {
+ name: "InvalidTransaction",
+ txs: txList{mustTx(t, WithTxID([]byte("INVALID_LENGTH")))},
+ wantError: ErrInvalidTxID,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+
+ initialHash := bc.LastHash()
+ initialHeight := bc.Height()
+
+ _, err := bc.AddBlock(tt.txs)
+
+ if !errors.Is(err, tt.wantError) {
+ t.Fatalf("expected error: %v,\nGot: %v", tt.wantError, err)
+ }
+
+ if bc.Height() != initialHeight || !bytes.Equal(bc.LastHash(), initialHash) {
+ t.Error("Security Invariant Violated: state modified on validation failure")
+ }
+ })
+ }
+}
+
+func TestAddBlock_Properties(t *testing.T) {
+ t.Parallel()
+ bc := mustNewMemoryChain(t)
+
+ t.Run("ChainLinkageAndHeight", func(t *testing.T) {
+ t.Parallel()
+ for i := 1; i < 5; i++ {
+ prevHash := bc.LastHash()
+ block := mustAddBlock(t, bc)
+
+ if !bytes.Equal(block.Header.PrevHash[:], prevHash) {
+ t.Errorf("linkage is broken at block %d", i)
+ }
+
+ if bc.Height() != uint64(i) {
+ t.Errorf("height mismatch: want %d, got %d", i, bc.Height())
+ }
+
+ if !bytes.Equal(bc.LastHash(), block.Hash[:]) {
+ t.Error("LastHash not updated to block hash")
+ }
+ }
+ })
+}
+
+func TestAddBlock_PersistenceIsolation(t *testing.T) {
+ t.Parallel()
+
+ // Setup spy store
+ spy := &spyStore{Store: storage.NewMemoryStore()}
+ bc := mustNewChain(t, spy)
+
+ // Baseline count: 3 (Block, HeightIndex, LastHash)
+ baseline := spy.setCallCount()
+
+ // Add invalid block
+ unsignedTx := mustTx(t, WithUnsigned())
+ _, err := bc.AddBlock(txList{unsignedTx})
+
+ if !errors.Is(err, ErrUnsignedTx) {
+ t.Fatalf("expected ErrUnsignedTx, got %v", err)
+ }
+
+ if current := spy.setCallCount(); current != baseline {
+ t.Errorf("Security Breach: validation failure wrote to storage! %d unexpected calls",
+ current-baseline,
+ )
+ }
+}
+
+// GetBlock Unit-tests
+
+func TestGetBlock(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+ block := mustAddBlock(t, bc)
+
+ nonExistantHash := make([]byte, crypto.HashSize)
+ copy(nonExistantHash, []byte("NON_EXISTANT_HASH"))
+
+ tests := []struct {
+ name string
+ hash []byte
+ wantErr error
+ }{
+ {
+ name: "Found",
+ hash: block.Hash[:],
+ wantErr: nil,
+ },
+ {
+ name: "NotFound",
+ hash: nonExistantHash,
+ wantErr: storage.ErrNotFound,
+ },
+ {
+ name: "EmptyHash",
+ hash: []byte{},
+ wantErr: ErrInvalidHash,
+ },
+ {
+ name: "NilHash",
+ hash: nil,
+ wantErr: ErrInvalidHash,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ got, err := bc.GetBlock(tt.hash)
+
+ if !errors.Is(err, tt.wantErr) {
+ t.Fatalf("expected error: %v, got %v", tt.wantErr, err)
+ }
+
+ if tt.wantErr == nil {
+ // Check Hash
+ if !bytes.Equal(got.Hash[:], block.Hash[:]) {
+ t.Errorf("block hash mismatch: want %x, got %x",
+ block.Hash,
+ got.Hash,
+ )
+ }
+ // Check height and timestamp
+ if got.Header.Height != block.Header.Height {
+ t.Errorf("block height mismatch: want %d, got %d",
+ block.Header.Height,
+ got.Header.Height,
+ )
+ }
+ if got.Header.TimeStamp != block.Header.TimeStamp {
+ t.Errorf("block timestamp mismatch: want %d, got %d",
+ block.Header.TimeStamp,
+ got.Header.TimeStamp,
+ )
+ }
+ }
+ })
+ }
+}
+
+// GetBlockByHeight Unit-tests
+
+func TestGetBlockByHeight(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+ blocks := []*Block{}
+
+ genesis, err := bc.GetBlockByHeight(0)
+ if err != nil {
+ t.Fatalf("failed to GetBlockByHeight(0): %v", err)
+ }
+ blocks = append(blocks, genesis)
+
+ // Add two more blocks
+ blocks = append(blocks, mustAddBlock(t, bc))
+ blocks = append(blocks, mustAddBlock(t, bc))
+
+ t.Run("ValidHeight", func(t *testing.T) {
+ t.Parallel()
+ for i, want := range blocks {
+ got, err := bc.GetBlockByHeight(uint64(i))
+ if err != nil {
+ t.Fatalf("failed to get block at height %d: %v", i, err)
+ }
+ if !bytes.Equal(got.Hash[:], want.Hash[:]) {
+ t.Errorf("height %d: hash mismatch", i)
+ }
+ }
+ })
+
+ t.Run("HeightOutOfBound", func(t *testing.T) {
+ t.Parallel()
+ // current height: 2, so 3 should fail
+ _, err := bc.GetBlockByHeight(3)
+ if !errors.Is(err, storage.ErrNotFound) {
+ t.Errorf("expected ErrNotFound for height 3, got %v", err)
+ }
+ _, err = bc.GetBlockByHeight(1337)
+ if !errors.Is(err, storage.ErrNotFound) {
+ t.Errorf("expected ErrNotFound for height 1337, got %v", err)
+ }
+ })
+}
+
+// GetTransaction Unit-tests
+
+func TestGetTransaction(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+
+ // Create a block with multiple transactions
+ tx1 := mustTx(t)
+ tx2 := mustTx(t)
+ tx3 := mustTx(t)
+
+ mustAddBlock(t, bc, tx1, tx2, tx3)
+
+ t.Run("Found", func(t *testing.T) {
+ t.Parallel()
+ got, err := bc.GetTransaction(tx2.TxID)
+ if err != nil {
+ t.Fatalf("failed to get transaction: %v", err)
+ }
+
+ // Verify the fields
+ if !bytes.Equal(got.TxID, tx2.TxID) {
+ t.Errorf("TxID mismatch: want %x, got %x", tx2.TxID, got.TxID)
+ }
+ if got.IssuerDID != tx2.IssuerDID {
+ t.Errorf("IssuerDID mismatch: want %s, got %s", tx2.IssuerDID, got.IssuerDID)
+ }
+ if !bytes.Equal(got.MerkleRoot, tx2.MerkleRoot) {
+ t.Errorf("MerkleRoot mismatch: want %x, got %x", tx2.MerkleRoot, got.MerkleRoot)
+ }
+ })
+
+ t.Run("ValidationAndMissing", func(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ txID []byte
+ wantErr error
+ }{
+ {
+ name: "NotFound",
+ txID: make([]byte, crypto.HashSize),
+ wantErr: storage.ErrNotFound,
+ },
+ {
+ name: "EmptyID",
+ txID: []byte{},
+ wantErr: ErrInvalidTxID,
+ },
+ {
+ name: "NilID",
+ txID: nil,
+ wantErr: ErrInvalidTxID,
+ },
+ {
+ name: "InvalidTxLength",
+ txID: []byte("INVALID_LENGTH"),
+ wantErr: ErrInvalidTxID,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ t.Parallel()
+
+ _, err := bc.GetTransaction(tt.txID)
+ if !errors.Is(err, tt.wantErr) {
+ t.Errorf("expected error %v, got %v", tt.wantErr, err)
+ }
+ })
+ }
+ })
+}
+
+// Iterator Unit-tests
+
+func TestIterator(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+ const count = 5
+
+ genesis, err := bc.GetBlockByHeight(0)
+ if err != nil {
+ t.Fatalf("failed to set genesis: %v", err)
+ }
+
+ expected := []*Block{genesis}
+
+ for range count {
+ expected = append(expected, mustAddBlock(t, bc))
+ }
+
+ // Reverse the slice for backward iteration verification
+ slices.Reverse(expected)
+
+ t.Run("CompleteBackwardSequence", func(t *testing.T) {
+ t.Parallel()
+ it := bc.Iterator()
+
+ for i, want := range expected {
+ if !it.HasNext() {
+ t.Fatalf("expected HasNext to be true at index %d", i)
+ }
+
+ got, err := it.Next()
+ if err != nil {
+ t.Fatalf("failed at index %d: %v", i, err)
+ }
+
+ // Verify fields
+ if !bytes.Equal(got.Hash[:], want.Hash[:]) {
+ t.Errorf("block %d: hash mismatch", i)
+ }
+ if got.Header.Height != want.Header.Height {
+ t.Errorf("block %d: height mismatch", i)
+ }
+ }
+
+ if it.HasNext() {
+ t.Error("HasNext should be false after genesis")
+ }
+
+ lastBlock, err := it.Next()
+ if lastBlock != nil || err != nil {
+ t.Error("Next() after exhaustion must return (nil, nil)")
+ }
+ })
+
+ t.Run("RangeProtocolEarlyStop", func(t *testing.T) {
+ t.Parallel()
+ count := 0
+
+ for _, err := range bc.Blocks() {
+ if err != nil {
+ t.Fatal(err)
+ }
+ count++
+ if count == 2 {
+ break
+ }
+ }
+ if count != 2 {
+ t.Error("range loop did not follow early break")
+ }
+ })
+}
+
+// Blocks traversal Unit-tests
+
+func TestBlocks(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+ const blocksCount = 5
+
+ for range blocksCount {
+ mustAddBlock(t, bc, mustTx(t))
+ }
+
+ t.Run("FullTraversal", func(t *testing.T) {
+ t.Parallel()
+
+ count := 0
+ expectedHeight := bc.Height()
+ for block, err := range bc.Blocks() {
+ if err != nil {
+ t.Fatalf("range error: %v", err)
+ }
+
+ if block.Header.Height != expectedHeight {
+ t.Errorf("height mismatch: expected height %d, got %d",
+ expectedHeight,
+ block.Header.Height,
+ )
+ }
+ expectedHeight--
+ count++
+ }
+
+ if count != blocksCount+1 { // add the genesis block also
+ t.Errorf("expected to iterate over %d blocks, got %d", blocksCount+1, count)
+ }
+ })
+
+ t.Run("EarlyTermination", func(t *testing.T) {
+ t.Parallel()
+
+ count := 0
+
+ for _, err := range bc.Blocks() {
+ if err != nil {
+ t.Fatalf("range error: %v", err)
+ }
+
+ count++
+ if count == 2 {
+ break
+ }
+ }
+
+ if count != 2 {
+ t.Errorf("expected to stop at 2, but count went up to %d", count)
+ }
+ })
+}
+
+// Blockchain concurrent reads with go routines
+
+func TestBlockchain_ConcurrentReads(t *testing.T) {
+ t.Parallel()
+
+ bc := mustNewMemoryChain(t)
+
+ const (
+ numReaders = 10
+ numIterators = 5
+ blocksToAdd = 50
+ readFrequency = 100
+ )
+
+ var wg sync.WaitGroup
+ wg.Add(numReaders + numIterators + 1) // add +1 for writer
+
+ // Writer
+ // Constantly add blocks
+ go func() {
+ defer wg.Done()
+ for i := range blocksToAdd {
+ _, err := bc.AddBlock(txList{mustTx(t)})
+ if err != nil {
+ t.Errorf("Writer failed at block %d: %v", i, err)
+ return
+ }
+ time.Sleep(1 * time.Millisecond) // to allow readers to catch specific state
+ }
+ }()
+
+ // Readers
+ // Constantly verify the current height and last block
+ for i := range numReaders {
+ go func(id int) {
+ defer wg.Done()
+ for range readFrequency {
+ h := bc.Height()
+ lastHash := bc.LastHash()
+
+ // Check consistency: Height
+ block, err := bc.GetBlockByHeight(h)
+ if err != nil && !errors.Is(err, storage.ErrNotFound) {
+ t.Errorf("Reader %d: GetBlockByHeight(%d) failed: %v", id, h, err)
+ }
+
+ // Verify block
+ if block != nil && !bytes.Equal(block.Hash[:], lastHash) {
+ // The writer may have appended a block between our
+ // Height() and LastHash() calls. This is a race in the
+ // test execution timeline, not a bug in the synchronization.
+ }
+ }
+ }(i)
+ }
+
+ // Iterators
+ // Verify that backward traversal is stable during writes
+ for i := range numIterators {
+ go func(id int) {
+ defer wg.Done()
+ count := 0
+ for _, err := range bc.Blocks() {
+ if err != nil {
+ t.Errorf("Iterators %d failed: %v", id, err)
+ return
+ }
+ count++
+ if count > 10 {
+ break
+ }
+ }
+ }(i)
+ }
+
+ wg.Wait()
+}
diff --git a/internal/blockchain/helpers_test.go b/internal/blockchain/helpers_test.go
@@ -0,0 +1,160 @@
+// 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 blockchain
+
+import (
+ "sync"
+ "testing"
+
+ "certichain/internal/crypto"
+ "certichain/internal/storage"
+ "certichain/internal/transaction"
+)
+
+type txConfig struct {
+ signed bool
+ root crypto.Hash
+ customID []byte
+}
+
+type TxOption func(*txConfig)
+
+func WithUnsigned() TxOption { return func(c *txConfig) { c.signed = false } }
+func WithTxID(id []byte) TxOption { return func(c *txConfig) { c.customID = id } }
+
+// txList is a syntactic sugar type for test readability.
+type txList []*transaction.Transaction
+
+func mustTx(t *testing.T, opts ...TxOption) *transaction.Transaction {
+ t.Helper()
+
+ cfg := &txConfig{
+ signed: true,
+ root: mustMerkleRoot(t),
+ }
+ for _, opt := range opts {
+ opt(cfg)
+ }
+
+ pub, priv, err := crypto.GenerateKeyPair()
+ if err != nil {
+ t.Fatalf("failed to generate keypair: %v", err)
+ }
+
+ did, err := crypto.NewDID(pub)
+ if err != nil {
+ t.Fatalf("failed to generate did: %v", err)
+ }
+
+ tx, err := transaction.New(did, cfg.root[:])
+ if err != nil {
+ t.Fatalf("failed to generate transaction: %v", err)
+ }
+
+ if cfg.customID != nil {
+ tx.TxID = cfg.customID
+ }
+
+ if cfg.signed {
+ if err := tx.Sign(priv); err != nil {
+ t.Fatalf("failed to sign transaction: %v", err)
+ }
+ }
+
+ return tx
+}
+
+// mustNewChain creates a new Blockchain instance.
+func mustNewChain(t *testing.T, store storage.Store, opts ...Option) *Blockchain {
+ t.Helper()
+
+ bc, err := New(store, opts...)
+ if err != nil {
+ t.Fatalf("New() unexpected error: %v", err)
+ }
+ t.Cleanup(func() { bc.Close() })
+
+ return bc
+}
+
+// mustNewMemoryChain creates a new Blockchain instance backed by an in-memory store.
+func mustNewMemoryChain(t *testing.T, opts ...Option) *Blockchain {
+ t.Helper()
+ return mustNewChain(t, storage.NewMemoryStore(), opts...)
+}
+
+// mustAddBlock appends a new block to the chain.
+func mustAddBlock(t *testing.T, bc *Blockchain, txs ...*transaction.Transaction) *Block {
+ t.Helper()
+
+ if len(txs) == 0 {
+ txs = []*transaction.Transaction{mustTx(t)}
+ }
+
+ block, err := bc.AddBlock(txs)
+ if err != nil {
+ t.Fatalf("mustAddBlock failed: %v", err)
+ }
+
+ return block
+}
+
+// mustMerkleRoot returns a dummy merkle root hash.
+func mustMerkleRoot(t *testing.T) crypto.Hash {
+ t.Helper()
+ return crypto.HashBytes([]byte("TEST_MERKLE_ROOT"))
+}
+
+// spyStore wraps a real Store and counts calls to Set via its batches.
+// It uses struct embedding to automatically delegate all other interface methods to the underlying Store.
+type spyStore struct {
+ storage.Store
+ mu sync.Mutex
+ setCalls int
+}
+
+// NewBatch intercepts the batch creation to wrap it in a spyBatch.
+func (s *spyStore) NewBatch() (storage.Batch, error) {
+ batch, err := s.Store.NewBatch()
+ if err != nil {
+ return nil, err
+ }
+
+ return &spyBatch{
+ Batch: batch,
+ spy: s,
+ }, nil
+}
+
+// setCallCount returns the total number of times Set has been called across all generated batches.
+func (s *spyStore) setCallCount() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.setCalls
+}
+
+// spyBatch wraps a storage.Batch to intercept and count Set operations.
+type spyBatch struct {
+ storage.Batch
+ spy *spyStore
+}
+
+// Set stages a key-value pair and increments the parent spyStore's counter.
+func (b *spyBatch) Set(key, value []byte) error {
+ b.spy.mu.Lock()
+ b.spy.setCalls++
+ b.spy.mu.Unlock()
+ return b.Batch.Set(key, value)
+}