certichain

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

helpers_test.go (3915B)


      1 // Copyright 2026 Shivakumar (Certichain)
      2 //
      3 // Licensed under the Apache License, Version 2.0 (the "License");
      4 // you may not use this file except in compliance with the License.
      5 // You may obtain a copy of the License at
      6 //
      7 //     http://www.apache.org/licenses/LICENSE-2.0
      8 //
      9 // Unless required by applicable law or agreed to in writing, software
     10 // distributed under the License is distributed on an "AS IS" BASIS,
     11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 // See the License for the specific language governing permissions and
     13 // limitations under the License.
     14 
     15 package blockchain
     16 
     17 import (
     18 	"sync"
     19 	"testing"
     20 
     21 	"certichain/internal/crypto"
     22 	"certichain/internal/storage"
     23 	"certichain/internal/transaction"
     24 )
     25 
     26 type txConfig struct {
     27 	signed   bool
     28 	root     crypto.Hash
     29 	customID []byte
     30 }
     31 
     32 type TxOption func(*txConfig)
     33 
     34 func WithUnsigned() TxOption      { return func(c *txConfig) { c.signed = false } }
     35 func WithTxID(id []byte) TxOption { return func(c *txConfig) { c.customID = id } }
     36 
     37 // txList is a syntactic sugar type for test readability.
     38 type txList []*transaction.Transaction
     39 
     40 func mustTx(t *testing.T, opts ...TxOption) *transaction.Transaction {
     41 	t.Helper()
     42 
     43 	cfg := &txConfig{
     44 		signed: true,
     45 		root:   mustMerkleRoot(t),
     46 	}
     47 	for _, opt := range opts {
     48 		opt(cfg)
     49 	}
     50 
     51 	pub, priv, err := crypto.GenerateKeyPair()
     52 	if err != nil {
     53 		t.Fatalf("failed to generate keypair: %v", err)
     54 	}
     55 
     56 	did, err := crypto.NewDID(pub)
     57 	if err != nil {
     58 		t.Fatalf("failed to generate did: %v", err)
     59 	}
     60 
     61 	tx, err := transaction.New(did, cfg.root[:])
     62 	if err != nil {
     63 		t.Fatalf("failed to generate transaction: %v", err)
     64 	}
     65 
     66 	if cfg.customID != nil {
     67 		tx.TxID = cfg.customID
     68 	}
     69 
     70 	if cfg.signed {
     71 		if err := tx.Sign(priv); err != nil {
     72 			t.Fatalf("failed to sign transaction: %v", err)
     73 		}
     74 	}
     75 
     76 	return tx
     77 }
     78 
     79 // mustNewChain creates a new Blockchain instance.
     80 func mustNewChain(t *testing.T, store storage.Store, opts ...Option) *Blockchain {
     81 	t.Helper()
     82 
     83 	bc, err := New(store, opts...)
     84 	if err != nil {
     85 		t.Fatalf("New() unexpected error: %v", err)
     86 	}
     87 	t.Cleanup(func() { bc.Close() })
     88 
     89 	return bc
     90 }
     91 
     92 // mustNewMemoryChain creates a new Blockchain instance backed by an in-memory store.
     93 func mustNewMemoryChain(t *testing.T, opts ...Option) *Blockchain {
     94 	t.Helper()
     95 	return mustNewChain(t, storage.NewMemoryStore(), opts...)
     96 }
     97 
     98 // mustAddBlock appends a new block to the chain.
     99 func mustAddBlock(t *testing.T, bc *Blockchain, txs ...*transaction.Transaction) *Block {
    100 	t.Helper()
    101 
    102 	if len(txs) == 0 {
    103 		txs = []*transaction.Transaction{mustTx(t)}
    104 	}
    105 
    106 	block, err := bc.AddBlock(txs)
    107 	if err != nil {
    108 		t.Fatalf("mustAddBlock failed: %v", err)
    109 	}
    110 
    111 	return block
    112 }
    113 
    114 // mustMerkleRoot returns a dummy merkle root hash.
    115 func mustMerkleRoot(t *testing.T) crypto.Hash {
    116 	t.Helper()
    117 	return crypto.HashBytes([]byte("TEST_MERKLE_ROOT"))
    118 }
    119 
    120 // spyStore wraps a real Store and counts calls to Set via its batches.
    121 // It uses struct embedding to automatically delegate all other interface methods to the underlying Store.
    122 type spyStore struct {
    123 	storage.Store
    124 	mu       sync.Mutex
    125 	setCalls int
    126 }
    127 
    128 // NewBatch intercepts the batch creation to wrap it in a spyBatch.
    129 func (s *spyStore) NewBatch() (storage.Batch, error) {
    130 	batch, err := s.Store.NewBatch()
    131 	if err != nil {
    132 		return nil, err
    133 	}
    134 
    135 	return &spyBatch{
    136 		Batch: batch,
    137 		spy:   s,
    138 	}, nil
    139 }
    140 
    141 // setCallCount returns the total number of times Set has been called across all generated batches.
    142 func (s *spyStore) setCallCount() int {
    143 	s.mu.Lock()
    144 	defer s.mu.Unlock()
    145 	return s.setCalls
    146 }
    147 
    148 // spyBatch wraps a storage.Batch to intercept and count Set operations.
    149 type spyBatch struct {
    150 	storage.Batch
    151 	spy *spyStore
    152 }
    153 
    154 // Set stages a key-value pair and increments the parent spyStore's counter.
    155 func (b *spyBatch) Set(key, value []byte) error {
    156 	b.spy.mu.Lock()
    157 	b.spy.setCalls++
    158 	b.spy.mu.Unlock()
    159 	return b.Batch.Set(key, value)
    160 }