certichain

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

blockchain_test.go (14688B)


      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 	"bytes"
     19 	"errors"
     20 	"slices"
     21 	"sync"
     22 	"testing"
     23 	"time"
     24 
     25 	"certichain/internal/crypto"
     26 	"certichain/internal/storage"
     27 )
     28 
     29 // Genesis Unit-tests
     30 
     31 func TestNew(t *testing.T) {
     32 	t.Parallel()
     33 
     34 	t.Run("Initialization", func(t *testing.T) {
     35 		t.Parallel()
     36 
     37 		fixedTime := time.Date(2010, 11, 6, 0, 0, 0, 0, time.UTC).Unix()
     38 
     39 		tests := []struct {
     40 			name     string
     41 			opts     []Option
     42 			validate func(*testing.T, *Blockchain)
     43 		}{
     44 			{
     45 				name: "CreateGenesis",
     46 				opts: nil,
     47 				validate: func(
     48 					t *testing.T,
     49 					bc *Blockchain,
     50 				) {
     51 					count := 0
     52 					for b, err := range bc.Blocks() {
     53 						if err != nil {
     54 							t.Fatal(err)
     55 						}
     56 						if b.Header.Height != 0 || !b.Header.PrevHash.IsZero() {
     57 							t.Error("invalid genesis block structure")
     58 						}
     59 						count++
     60 					}
     61 					if count != 1 {
     62 						t.Errorf("expected 1 block, got %d", count)
     63 					}
     64 				},
     65 			},
     66 			{
     67 				name: "WithCustomTime",
     68 				opts: []Option{
     69 					WithGenesisTime(fixedTime),
     70 				},
     71 				validate: func(
     72 					t *testing.T,
     73 					bc *Blockchain,
     74 				) {
     75 					g, err := bc.GetBlockByHeight(0)
     76 					if err != nil {
     77 						t.Fatalf("GetBlockByHeight(0) unexpected error: %v", err)
     78 					}
     79 					if g.Header.TimeStamp != fixedTime {
     80 						t.Errorf("time mismatch: want %d, got %d", fixedTime, g.Header.TimeStamp)
     81 					}
     82 				},
     83 			},
     84 		}
     85 
     86 		for _, tt := range tests {
     87 			t.Run(tt.name, func(t *testing.T) {
     88 				bc := mustNewMemoryChain(t, tt.opts...)
     89 				tt.validate(t, bc)
     90 			})
     91 		}
     92 	})
     93 
     94 	t.Run("GenesisIsDeterministic", func(t *testing.T) {
     95 		t.Parallel()
     96 
     97 		timestamp := time.Date(2010, 11, 6, 0, 0, 0, 0, time.UTC).Unix()
     98 		h1 := mustNewMemoryChain(t, WithGenesisTime(timestamp)).LastHash()
     99 		h2 := mustNewMemoryChain(t, WithGenesisTime(timestamp)).LastHash()
    100 
    101 		if !bytes.Equal(h1, h2) {
    102 			t.Error("hash mismatch for identical timestamp")
    103 		}
    104 	})
    105 }
    106 
    107 func TestNew_ExistingChain(t *testing.T) {
    108 	t.Parallel()
    109 
    110 	store := storage.NewMemoryStore()
    111 	t.Cleanup(func() { store.Close() })
    112 
    113 	tip := func() []byte {
    114 		bc := mustNewChain(t, store)
    115 		mustAddBlock(t, bc, mustTx(t))
    116 		return bc.LastHash()
    117 	}()
    118 
    119 	bc := mustNewChain(t, store)
    120 	if bc.Height() != 1 {
    121 		t.Errorf("height: want 1, got %d", bc.Height())
    122 	}
    123 	if !bytes.Equal(bc.LastHash(), tip) {
    124 		t.Error("lastHash mismatch after resumption")
    125 	}
    126 }
    127 
    128 // AddBlock Unit-tests
    129 
    130 func TestAddBlock_Validation(t *testing.T) {
    131 	t.Parallel()
    132 
    133 	tests := []struct {
    134 		name      string
    135 		txs       txList
    136 		wantError error
    137 	}{
    138 		{
    139 			name:      "NilTransactionSlice",
    140 			txs:       nil,
    141 			wantError: ErrNilTransactions,
    142 		},
    143 		{
    144 			name:      "EmptyTransactionSlice",
    145 			txs:       txList{},
    146 			wantError: ErrEmptyBlock,
    147 		},
    148 		{
    149 			name:      "NilTransactionEntry",
    150 			txs:       txList{mustTx(t), nil},
    151 			wantError: ErrNilTransactionEntry,
    152 		},
    153 		{
    154 			name:      "UnsignedTransaction",
    155 			txs:       txList{mustTx(t, WithUnsigned())},
    156 			wantError: ErrUnsignedTx,
    157 		},
    158 		{
    159 			name:      "InvalidTransaction",
    160 			txs:       txList{mustTx(t, WithTxID([]byte("INVALID_LENGTH")))},
    161 			wantError: ErrInvalidTxID,
    162 		},
    163 	}
    164 
    165 	for _, tt := range tests {
    166 		t.Run(tt.name, func(t *testing.T) {
    167 			t.Parallel()
    168 
    169 			bc := mustNewMemoryChain(t)
    170 
    171 			initialHash := bc.LastHash()
    172 			initialHeight := bc.Height()
    173 
    174 			_, err := bc.AddBlock(tt.txs)
    175 
    176 			if !errors.Is(err, tt.wantError) {
    177 				t.Fatalf("expected error: %v,\nGot: %v", tt.wantError, err)
    178 			}
    179 
    180 			if bc.Height() != initialHeight || !bytes.Equal(bc.LastHash(), initialHash) {
    181 				t.Error("Security Invariant Violated: state modified on validation failure")
    182 			}
    183 		})
    184 	}
    185 }
    186 
    187 func TestAddBlock_Properties(t *testing.T) {
    188 	t.Parallel()
    189 	bc := mustNewMemoryChain(t)
    190 
    191 	t.Run("ChainLinkageAndHeight", func(t *testing.T) {
    192 		t.Parallel()
    193 		for i := 1; i < 5; i++ {
    194 			prevHash := bc.LastHash()
    195 			block := mustAddBlock(t, bc)
    196 
    197 			if !bytes.Equal(block.Header.PrevHash[:], prevHash) {
    198 				t.Errorf("linkage is broken at block %d", i)
    199 			}
    200 
    201 			if bc.Height() != uint64(i) {
    202 				t.Errorf("height mismatch: want %d, got %d", i, bc.Height())
    203 			}
    204 
    205 			if !bytes.Equal(bc.LastHash(), block.Hash[:]) {
    206 				t.Error("LastHash not updated to block hash")
    207 			}
    208 		}
    209 	})
    210 }
    211 
    212 func TestAddBlock_PersistenceIsolation(t *testing.T) {
    213 	t.Parallel()
    214 
    215 	// Setup spy store
    216 	spy := &spyStore{Store: storage.NewMemoryStore()}
    217 	bc := mustNewChain(t, spy)
    218 
    219 	// Baseline count: 3 (Block, HeightIndex, LastHash)
    220 	baseline := spy.setCallCount()
    221 
    222 	// Add invalid block
    223 	unsignedTx := mustTx(t, WithUnsigned())
    224 	_, err := bc.AddBlock(txList{unsignedTx})
    225 
    226 	if !errors.Is(err, ErrUnsignedTx) {
    227 		t.Fatalf("expected ErrUnsignedTx, got %v", err)
    228 	}
    229 
    230 	if current := spy.setCallCount(); current != baseline {
    231 		t.Errorf("Security Breach: validation failure wrote to storage! %d unexpected calls",
    232 			current-baseline,
    233 		)
    234 	}
    235 }
    236 
    237 // GetBlock Unit-tests
    238 
    239 func TestGetBlock(t *testing.T) {
    240 	t.Parallel()
    241 
    242 	bc := mustNewMemoryChain(t)
    243 	block := mustAddBlock(t, bc)
    244 
    245 	nonExistantHash := make([]byte, crypto.HashSize)
    246 	copy(nonExistantHash, []byte("NON_EXISTANT_HASH"))
    247 
    248 	tests := []struct {
    249 		name    string
    250 		hash    []byte
    251 		wantErr error
    252 	}{
    253 		{
    254 			name:    "Found",
    255 			hash:    block.Hash[:],
    256 			wantErr: nil,
    257 		},
    258 		{
    259 			name:    "NotFound",
    260 			hash:    nonExistantHash,
    261 			wantErr: storage.ErrNotFound,
    262 		},
    263 		{
    264 			name:    "EmptyHash",
    265 			hash:    []byte{},
    266 			wantErr: ErrInvalidHash,
    267 		},
    268 		{
    269 			name:    "NilHash",
    270 			hash:    nil,
    271 			wantErr: ErrInvalidHash,
    272 		},
    273 	}
    274 
    275 	for _, tt := range tests {
    276 		t.Run(tt.name, func(t *testing.T) {
    277 			t.Parallel()
    278 
    279 			got, err := bc.GetBlock(tt.hash)
    280 
    281 			if !errors.Is(err, tt.wantErr) {
    282 				t.Fatalf("expected error: %v, got %v", tt.wantErr, err)
    283 			}
    284 
    285 			if tt.wantErr == nil {
    286 				// Check Hash
    287 				if !bytes.Equal(got.Hash[:], block.Hash[:]) {
    288 					t.Errorf("block hash mismatch: want %x, got %x",
    289 						block.Hash,
    290 						got.Hash,
    291 					)
    292 				}
    293 				// Check height and timestamp
    294 				if got.Header.Height != block.Header.Height {
    295 					t.Errorf("block height mismatch: want %d, got %d",
    296 						block.Header.Height,
    297 						got.Header.Height,
    298 					)
    299 				}
    300 				if got.Header.TimeStamp != block.Header.TimeStamp {
    301 					t.Errorf("block timestamp mismatch: want %d, got %d",
    302 						block.Header.TimeStamp,
    303 						got.Header.TimeStamp,
    304 					)
    305 				}
    306 			}
    307 		})
    308 	}
    309 }
    310 
    311 // GetBlockByHeight Unit-tests
    312 
    313 func TestGetBlockByHeight(t *testing.T) {
    314 	t.Parallel()
    315 
    316 	bc := mustNewMemoryChain(t)
    317 	blocks := []*Block{}
    318 
    319 	genesis, err := bc.GetBlockByHeight(0)
    320 	if err != nil {
    321 		t.Fatalf("failed to GetBlockByHeight(0): %v", err)
    322 	}
    323 	blocks = append(blocks, genesis)
    324 
    325 	// Add two more blocks
    326 	blocks = append(blocks, mustAddBlock(t, bc))
    327 	blocks = append(blocks, mustAddBlock(t, bc))
    328 
    329 	t.Run("ValidHeight", func(t *testing.T) {
    330 		t.Parallel()
    331 		for i, want := range blocks {
    332 			got, err := bc.GetBlockByHeight(uint64(i))
    333 			if err != nil {
    334 				t.Fatalf("failed to get block at height %d: %v", i, err)
    335 			}
    336 			if !bytes.Equal(got.Hash[:], want.Hash[:]) {
    337 				t.Errorf("height %d: hash mismatch", i)
    338 			}
    339 		}
    340 	})
    341 
    342 	t.Run("HeightOutOfBound", func(t *testing.T) {
    343 		t.Parallel()
    344 		// current height: 2, so 3 should fail
    345 		_, err := bc.GetBlockByHeight(3)
    346 		if !errors.Is(err, storage.ErrNotFound) {
    347 			t.Errorf("expected ErrNotFound for height 3, got %v", err)
    348 		}
    349 		_, err = bc.GetBlockByHeight(1337)
    350 		if !errors.Is(err, storage.ErrNotFound) {
    351 			t.Errorf("expected ErrNotFound for height 1337, got %v", err)
    352 		}
    353 	})
    354 }
    355 
    356 // GetBlockByTxID Unit-tests
    357 
    358 func TestGetBlockByTxID(t *testing.T) {
    359 	t.Parallel()
    360 
    361 	bc := mustNewMemoryChain(t)
    362 	tx := mustTx(t)
    363 
    364 	mustAddBlock(t, bc, tx)
    365 
    366 	tests := []struct {
    367 		name    string
    368 		txID    []byte
    369 		wantErr error
    370 	}{
    371 		{
    372 			name:    "Ideal Case",
    373 			txID:    tx.TxID,
    374 			wantErr: nil,
    375 		},
    376 		{
    377 			name:    "nil Case",
    378 			txID:    nil,
    379 			wantErr: ErrInvalidTxID,
    380 		},
    381 		{
    382 			name:    "Unanchored TxID",
    383 			txID:    mustTx(t).TxID,
    384 			wantErr: storage.ErrNotFound,
    385 		},
    386 		{
    387 			name:    "malformed TxID",
    388 			txID:    make([]byte, 42),
    389 			wantErr: ErrInvalidTxID,
    390 		},
    391 	}
    392 
    393 	for _, tt := range tests {
    394 		t.Run(tt.name, func(t *testing.T) {
    395 			t.Parallel()
    396 
    397 			if _, err := bc.GetBlockByTxID(tt.txID); !errors.Is(err, tt.wantErr) {
    398 				t.Fatalf("Unexpected Error: want = %v, got = %v", err, tt.wantErr)
    399 			}
    400 		})
    401 	}
    402 }
    403 
    404 // GetTransaction Unit-tests
    405 
    406 func TestGetTransaction(t *testing.T) {
    407 	t.Parallel()
    408 
    409 	bc := mustNewMemoryChain(t)
    410 
    411 	// Create a block with multiple transactions
    412 	tx1 := mustTx(t)
    413 	tx2 := mustTx(t)
    414 	tx3 := mustTx(t)
    415 
    416 	mustAddBlock(t, bc, tx1, tx2, tx3)
    417 
    418 	t.Run("Found", func(t *testing.T) {
    419 		t.Parallel()
    420 		got, err := bc.GetTransaction(tx2.TxID)
    421 		if err != nil {
    422 			t.Fatalf("failed to get transaction: %v", err)
    423 		}
    424 
    425 		// Verify the fields
    426 		if !bytes.Equal(got.TxID, tx2.TxID) {
    427 			t.Errorf("TxID mismatch: want %x, got %x", tx2.TxID, got.TxID)
    428 		}
    429 		if got.IssuerDID != tx2.IssuerDID {
    430 			t.Errorf("IssuerDID mismatch: want %s, got %s", tx2.IssuerDID, got.IssuerDID)
    431 		}
    432 		if !bytes.Equal(got.MerkleRoot, tx2.MerkleRoot) {
    433 			t.Errorf("MerkleRoot mismatch: want %x, got %x", tx2.MerkleRoot, got.MerkleRoot)
    434 		}
    435 	})
    436 
    437 	t.Run("ValidationAndMissing", func(t *testing.T) {
    438 		t.Parallel()
    439 
    440 		tests := []struct {
    441 			name    string
    442 			txID    []byte
    443 			wantErr error
    444 		}{
    445 			{
    446 				name:    "NotFound",
    447 				txID:    make([]byte, crypto.HashSize),
    448 				wantErr: storage.ErrNotFound,
    449 			},
    450 			{
    451 				name:    "EmptyID",
    452 				txID:    []byte{},
    453 				wantErr: ErrInvalidTxID,
    454 			},
    455 			{
    456 				name:    "NilID",
    457 				txID:    nil,
    458 				wantErr: ErrInvalidTxID,
    459 			},
    460 			{
    461 				name:    "InvalidTxLength",
    462 				txID:    []byte("INVALID_LENGTH"),
    463 				wantErr: ErrInvalidTxID,
    464 			},
    465 		}
    466 
    467 		for _, tt := range tests {
    468 			t.Run(tt.name, func(t *testing.T) {
    469 				t.Parallel()
    470 
    471 				_, err := bc.GetTransaction(tt.txID)
    472 				if !errors.Is(err, tt.wantErr) {
    473 					t.Errorf("expected error %v, got %v", tt.wantErr, err)
    474 				}
    475 			})
    476 		}
    477 	})
    478 }
    479 
    480 // Iterator Unit-tests
    481 
    482 func TestIterator(t *testing.T) {
    483 	t.Parallel()
    484 
    485 	bc := mustNewMemoryChain(t)
    486 	const count = 5
    487 
    488 	genesis, err := bc.GetBlockByHeight(0)
    489 	if err != nil {
    490 		t.Fatalf("failed to set genesis: %v", err)
    491 	}
    492 
    493 	expected := []*Block{genesis}
    494 
    495 	for range count {
    496 		expected = append(expected, mustAddBlock(t, bc))
    497 	}
    498 
    499 	// Reverse the slice for backward iteration verification
    500 	slices.Reverse(expected)
    501 
    502 	t.Run("CompleteBackwardSequence", func(t *testing.T) {
    503 		t.Parallel()
    504 		it := bc.Iterator()
    505 
    506 		for i, want := range expected {
    507 			if !it.HasNext() {
    508 				t.Fatalf("expected HasNext to be true at index %d", i)
    509 			}
    510 
    511 			got, err := it.Next()
    512 			if err != nil {
    513 				t.Fatalf("failed at index %d: %v", i, err)
    514 			}
    515 
    516 			// Verify fields
    517 			if !bytes.Equal(got.Hash[:], want.Hash[:]) {
    518 				t.Errorf("block %d: hash mismatch", i)
    519 			}
    520 			if got.Header.Height != want.Header.Height {
    521 				t.Errorf("block %d: height mismatch", i)
    522 			}
    523 		}
    524 
    525 		if it.HasNext() {
    526 			t.Error("HasNext should be false after genesis")
    527 		}
    528 
    529 		lastBlock, err := it.Next()
    530 		if lastBlock != nil || err != nil {
    531 			t.Error("Next() after exhaustion must return (nil, nil)")
    532 		}
    533 	})
    534 
    535 	t.Run("RangeProtocolEarlyStop", func(t *testing.T) {
    536 		t.Parallel()
    537 		count := 0
    538 
    539 		for _, err := range bc.Blocks() {
    540 			if err != nil {
    541 				t.Fatal(err)
    542 			}
    543 			count++
    544 			if count == 2 {
    545 				break
    546 			}
    547 		}
    548 		if count != 2 {
    549 			t.Error("range loop did not follow early break")
    550 		}
    551 	})
    552 }
    553 
    554 // Blocks traversal Unit-tests
    555 
    556 func TestBlocks(t *testing.T) {
    557 	t.Parallel()
    558 
    559 	bc := mustNewMemoryChain(t)
    560 	const blocksCount = 5
    561 
    562 	for range blocksCount {
    563 		mustAddBlock(t, bc, mustTx(t))
    564 	}
    565 
    566 	t.Run("FullTraversal", func(t *testing.T) {
    567 		t.Parallel()
    568 
    569 		count := 0
    570 		expectedHeight := bc.Height()
    571 		for block, err := range bc.Blocks() {
    572 			if err != nil {
    573 				t.Fatalf("range error: %v", err)
    574 			}
    575 
    576 			if block.Header.Height != expectedHeight {
    577 				t.Errorf("height mismatch: expected height %d, got %d",
    578 					expectedHeight,
    579 					block.Header.Height,
    580 				)
    581 			}
    582 			expectedHeight--
    583 			count++
    584 		}
    585 
    586 		if count != blocksCount+1 { // add the genesis block also
    587 			t.Errorf("expected to iterate over %d blocks, got %d", blocksCount+1, count)
    588 		}
    589 	})
    590 
    591 	t.Run("EarlyTermination", func(t *testing.T) {
    592 		t.Parallel()
    593 
    594 		count := 0
    595 
    596 		for _, err := range bc.Blocks() {
    597 			if err != nil {
    598 				t.Fatalf("range error: %v", err)
    599 			}
    600 
    601 			count++
    602 			if count == 2 {
    603 				break
    604 			}
    605 		}
    606 
    607 		if count != 2 {
    608 			t.Errorf("expected to stop at 2, but count went up to %d", count)
    609 		}
    610 	})
    611 }
    612 
    613 // Blockchain concurrent reads with go routines
    614 
    615 func TestBlockchain_ConcurrentReads(t *testing.T) {
    616 	t.Parallel()
    617 
    618 	bc := mustNewMemoryChain(t)
    619 
    620 	const (
    621 		numReaders    = 10
    622 		numIterators  = 5
    623 		blocksToAdd   = 50
    624 		readFrequency = 100
    625 	)
    626 
    627 	var wg sync.WaitGroup
    628 	wg.Add(numReaders + numIterators + 1) // add +1 for writer
    629 
    630 	// Writer
    631 	// Constantly add blocks
    632 	go func() {
    633 		defer wg.Done()
    634 		for i := range blocksToAdd {
    635 			_, err := bc.AddBlock(txList{mustTx(t)})
    636 			if err != nil {
    637 				t.Errorf("Writer failed at block %d: %v", i, err)
    638 				return
    639 			}
    640 			time.Sleep(1 * time.Millisecond) // to allow readers to catch specific state
    641 		}
    642 	}()
    643 
    644 	// Readers
    645 	// Constantly verify the current height and last block
    646 	for i := range numReaders {
    647 		go func(id int) {
    648 			defer wg.Done()
    649 			for range readFrequency {
    650 				h := bc.Height()
    651 				lastHash := bc.LastHash()
    652 
    653 				// Check consistency: Height
    654 				block, err := bc.GetBlockByHeight(h)
    655 				if err != nil && !errors.Is(err, storage.ErrNotFound) {
    656 					t.Errorf("Reader %d: GetBlockByHeight(%d) failed: %v", id, h, err)
    657 				}
    658 
    659 				// Verify block
    660 				if block != nil && !bytes.Equal(block.Hash[:], lastHash) {
    661 					// The writer may have appended a block between our
    662 					// Height() and LastHash() calls. This is a race in the
    663 					// test execution timeline, not a bug in the synchronization.
    664 				}
    665 			}
    666 		}(i)
    667 	}
    668 
    669 	// Iterators
    670 	// Verify that backward traversal is stable during writes
    671 	for i := range numIterators {
    672 		go func(id int) {
    673 			defer wg.Done()
    674 			count := 0
    675 			for _, err := range bc.Blocks() {
    676 				if err != nil {
    677 					t.Errorf("Iterators %d failed: %v", id, err)
    678 					return
    679 				}
    680 				count++
    681 				if count > 10 {
    682 					break
    683 				}
    684 			}
    685 		}(i)
    686 	}
    687 
    688 	wg.Wait()
    689 }