certichain

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

commit 5dad82a85873421893b91b54bb9ed3303274c018
parent 10cfa01551aec1d83cc5ea59070f9d87a201aa93
Author: Shivakumar <[email protected]>
Date:   Thu, 30 Jul 2026 23:47:11 +0530

feat(mempool): add mempool and tests

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

Diffstat:
Ainternal/mempool/mempool.go | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Ainternal/mempool/mempool_test.go | 661+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 860 insertions(+), 0 deletions(-)

diff --git a/internal/mempool/mempool.go b/internal/mempool/mempool.go @@ -0,0 +1,199 @@ +// 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 mempool + +import ( + "errors" + "slices" + "sync" + "time" + + "certichain/internal/crypto" + "certichain/internal/transaction" +) + +const ( + DefaultMaxSize = 5_000 // Mempool capacity + DefaultTTL = 24 * time.Hour // transaction lifespan +) + +var ( + ErrDuplicateTx = errors.New("mempool: duplicate transaction ID") + ErrMempoolFull = errors.New("mempool: at capacity") + ErrNilTx = errors.New("mempool: nil transaction") + ErrInvalidTx = errors.New("mempool: invalid transaction") +) + +// Mempool manages unconfirmed transactions before they are mined into a block. +type Mempool struct { + mu sync.RWMutex + txs map[string]*transaction.Transaction + maxSize int + ttl time.Duration +} + +type Option func(*Mempool) + +// WithMaxSize configures the maximum number of transactions the pool can hold. +func WithMaxSize(n int) Option { + return func(mp *Mempool) { + mp.maxSize = n + } +} + +// WithTTL configures the time-to-live before a transaction is pruned. +func WithTTL(d time.Duration) Option { + return func(mp *Mempool) { + mp.ttl = d + } +} + +// New initializes a Mempool with default settings, applying any provided options. +func New(opts ...Option) *Mempool { + mp := &Mempool{ + txs: make(map[string]*transaction.Transaction), + maxSize: DefaultMaxSize, + ttl: DefaultTTL, + } + for _, opt := range opts { + opt(mp) + } + return mp +} + +// Add inserts a transaction into the mempool. +func (mp *Mempool) Add(tx *transaction.Transaction) error { + if tx == nil { + return ErrNilTx + } + if !tx.IsSigned() { + return ErrInvalidTx + } + if len(tx.TxID) != crypto.HashSize { + return ErrInvalidTx + } + + mp.mu.Lock() + defer mp.mu.Unlock() + + id := string(tx.TxID) + if _, exists := mp.txs[id]; exists { + return ErrDuplicateTx + } + + if len(mp.txs) >= mp.maxSize { + return ErrMempoolFull + } + + mp.txs[id] = tx.Clone() + return nil +} + +// sortedTransactions returns all transactions deterministically sorted. +// It assumes the caller holds the appropriate mutex. +func (mp *Mempool) sortedTransactions() []*transaction.Transaction { + if len(mp.txs) == 0 { + return nil + } + + result := make([]*transaction.Transaction, 0, len(mp.txs)) + for _, tx := range mp.txs { + result = append(result, tx) + } + + slices.SortFunc(result, transaction.Compare) + return result +} + +// Pending returns all the transactions deterministically sorted. +func (mp *Mempool) Pending() []*transaction.Transaction { + mp.mu.RLock() + defer mp.mu.RUnlock() + return mp.sortedTransactions() +} + +// Flush removes and returns up to the limit pending transactions, sorted +// deterministically (oldest first). A limit of 0 or less returns all +// pending transactions. +func (mp *Mempool) Flush(limit int) []*transaction.Transaction { + mp.mu.Lock() + defer mp.mu.Unlock() + + allTxs := mp.sortedTransactions() + if len(allTxs) == 0 { + return nil + } + + count := len(allTxs) + if limit > 0 && limit < count { + count = limit + } + result := allTxs[:count] + + for _, tx := range result { + delete(mp.txs, string(tx.TxID)) + } + return result +} + +// Prune deletes transactions older than TTL. +// Returns evicted count. +func (mp *Mempool) Prune() int { + mp.mu.Lock() + defer mp.mu.Unlock() + + evicted := 0 + cutoff := time.Now().Add(-mp.ttl).Unix() + + for id, tx := range mp.txs { + if tx.Timestamp < cutoff { + delete(mp.txs, id) + evicted++ + } + } + return evicted +} + +// Remove deletes specific transactions from the mempool. +func (mp *Mempool) Remove(txIDs [][]byte) { + mp.mu.Lock() + defer mp.mu.Unlock() + + for _, id := range txIDs { + delete(mp.txs, string(id)) + } +} + +// Count returns the current count of transactions. +func (mp *Mempool) Count() int { + mp.mu.RLock() + defer mp.mu.RUnlock() + return len(mp.txs) +} + +// Has reports whether a transaction with given txID is pending. +func (mp *Mempool) Has(txID []byte) bool { + mp.mu.RLock() + defer mp.mu.RUnlock() + _, exists := mp.txs[string(txID)] + return exists +} + +// Clear removes all the pending transactions. +func (mp *Mempool) Clear() { + mp.mu.Lock() + defer mp.mu.Unlock() + mp.txs = make(map[string]*transaction.Transaction) +} diff --git a/internal/mempool/mempool_test.go b/internal/mempool/mempool_test.go @@ -0,0 +1,661 @@ +// 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 mempool + +import ( + "bytes" + "errors" + "math/rand" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "certichain/internal/crypto" + "certichain/internal/transaction" +) + +// Options to add to mustTx helper function +func withUnsigned() func(*transaction.Transaction) { + return func(tx *transaction.Transaction) { tx.Signature = nil } +} +func withTimestamp(unix int64) func(*transaction.Transaction) { + return func(tx *transaction.Transaction) { tx.Timestamp = unix } +} +func withTxID(id []byte) func(*transaction.Transaction) { + return func(tx *transaction.Transaction) { tx.TxID = id } +} + +// mustTx creates a new transaction. +func mustTx( + t *testing.T, + opts ...func(*transaction.Transaction), +) *transaction.Transaction { + t.Helper() + + pub, priv, err := crypto.GenerateKeyPair() + if err != nil { + t.Fatal(err) + } + did, err := crypto.NewDID(pub) + if err != nil { + t.Fatal(err) + } + + root := mustMerkleRoot(t) + tx, err := transaction.New(did, root[:]) + if err != nil { + t.Fatal(err) + } + if err := tx.Sign(priv); err != nil { + t.Fatalf("failed to sign: %v", err) + } + + for _, opt := range opts { + opt(tx) + } + + return tx +} + +// mustAdd adds a transaction to the mempool +func mustAdd( + t *testing.T, + mp *Mempool, + tx *transaction.Transaction, +) { + t.Helper() + + if err := mp.Add(tx); err != nil { + t.Fatal(err) + } +} + +// mustMerkleRoot returns a merkle root. +func mustMerkleRoot( + t *testing.T, +) crypto.Hash { + t.Helper() + return crypto.HashBytes([]byte("TEST_MERKLE_ROOT")) +} + +func TestAdd_Validation(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + tx *transaction.Transaction + wantError error + }{ + { + "nil transaction", + nil, + ErrNilTx, + }, + { + "unsigned transaction", + mustTx(t, withUnsigned()), + ErrInvalidTx, + }, + { + "TxID too short", + mustTx(t, withTxID([]byte("INVALID"))), + ErrInvalidTx, + }, + { + "TxID too long", + mustTx(t, withTxID(make([]byte, 42))), + ErrInvalidTx, + }, + { + "Valid signed Tx", + mustTx(t), + nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + mp := New() + err := mp.Add(tt.tx) + + if !errors.Is(err, tt.wantError) { + t.Fatalf("Unexpected Error: want = %v, got = %v", + tt.wantError, + err, + ) + } + }) + } +} + +func TestAdd_Duplicates(t *testing.T) { + t.Parallel() + + // Test adding the same transaction twice + mp := New() + tx := mustTx(t) + + mustAdd(t, mp, tx) + if err := mp.Add(tx); !errors.Is(err, ErrDuplicateTx) { + t.Fatalf("Unexpected Error: want = %v, got = %v", + ErrDuplicateTx, err) + } + + // Test with same TxID, and different merkleroot + tx1 := tx.Clone() + tx1.MerkleRoot = []byte("VALID_DUP") + + if err := mp.Add(tx1); !errors.Is(err, ErrDuplicateTx) { + t.Fatalf("Unexpected Error: want = %v, got = %v", + ErrDuplicateTx, err) + } +} + +func TestAdd_CapacityAndOrdering(t *testing.T) { + t.Parallel() + + mp := New(WithMaxSize(2)) + + mustAdd(t, mp, mustTx(t)) + mustAdd(t, mp, mustTx(t)) + + if err := mp.Add(mustTx(t)); !errors.Is(err, ErrMempoolFull) { + t.Fatalf("Unexpected Error: want = %v, got = %v", + ErrMempoolFull, err) + } + + // Check ordering of error + // ErrDuplicateTx must win over ErrMempoolFull + mp1 := New(WithMaxSize(1)) + tx := mustTx(t) + + mustAdd(t, mp1, tx) + if err := mp1.Add(tx); !errors.Is(err, ErrDuplicateTx) { + t.Fatalf("Unexpected Error: want = %v, got = %v", + ErrDuplicateTx, err) + } +} + +// This below test I don't think is entirely correct +func TestAdd_DefensiveCopy(t *testing.T) { + t.Parallel() + + mp := New() + tx := mustTx(t) + + originalRoot := bytes.Clone(tx.MerkleRoot) + originalSign := bytes.Clone(tx.Signature) + originalNonce := bytes.Clone(tx.Nonce) + + mustAdd(t, mp, tx) + + tx.MerkleRoot[0] = 0xff // Tampering with the data, after add + + pending := mp.Pending() + if !bytes.Equal(pending[0].MerkleRoot, originalRoot) { + t.Error("mempool leaked external mutation") + } + + tx.Signature = []byte("SIGNED_LOL") + if !bytes.Equal(pending[0].Signature, originalSign) { + t.Error("mempool leaked external mutation") + } + + tx.Nonce = []byte("TRULY_RANDOM_NONCE") + if !bytes.Equal(pending[0].Nonce, originalNonce) { + t.Error("mempool leadked external mutation") + } +} + +func TestPending_Determinism(t *testing.T) { + t.Parallel() + + // checking the ordering of timestamps + // i.e. checking if the function sorts + mp := New() + + tx1 := mustTx(t, withTimestamp(300)) + tx2 := mustTx(t, withTimestamp(100)) + tx3 := mustTx(t, withTimestamp(200)) + + txs := []*transaction.Transaction{tx1, tx2, tx3} + + for _, tx := range txs { + mustAdd(t, mp, tx) + } + + pending := mp.Pending() + if !slices.IsSortedFunc(pending, transaction.Compare) { + t.Error("mempool is unsorted") + } + + // Testing how tiebreakers will work + mp2 := New() + + txA := mustTx(t, withTimestamp(500), withTxID(bytes.Repeat([]byte{0x01}, 32))) + txB := mustTx(t, withTimestamp(500), withTxID(bytes.Repeat([]byte{0x00}, 32))) + txs = []*transaction.Transaction{txA, txB} + + for _, tx := range txs { + mustAdd(t, mp2, tx) + } + + pending = mp2.Pending() + if !bytes.Equal(pending[0].TxID, txB.TxID) { + t.Errorf( + "tiebreak failed: want TxB (smaller) first, got TxID = %x", + pending[0].TxID, + ) + } + + // Stability under repetition + for range 50 { + mp3 := New() + + txA := mustTx( + t, + withTimestamp(500), + withTxID(bytes.Repeat([]byte{0x01}, 32)), + ) + txB := mustTx( + t, + withTimestamp(500), + withTxID(bytes.Repeat([]byte{0x00}, 32)), + ) + + txs = []*transaction.Transaction{txA, txB} + + for _, tx := range txs { + mustAdd(t, mp3, tx) + } + + pending = mp3.Pending() + if !bytes.Equal(pending[0].TxID, txB.TxID) { + t.Errorf( + "tiebreak failed: want TxB (smaller) first, got TxID = %x", + pending[0].TxID, + ) + } + } +} + +func TestPending_ReadOnly(t *testing.T) { + t.Parallel() + + mp := New() + mustAdd(t, mp, mustTx(t)) + + // Call pending consecutively twice + pending := mp.Pending() + pending1 := mp.Pending() + + if mp.Count() != 1 { + t.Error("Error: No. of transactions changed") + } + if pending[0] != pending1[0] { + t.Error("Error: pending structs not equal") + } +} + +func TestFlush_Behavior(t *testing.T) { + t.Parallel() + + mp := New() + + // Flush empty + if got := mp.Flush(0); len(got) != 0 { + t.Errorf("Flush Error: want empty, got %d", len(got)) + } + if got := mp.Flush(5); len(got) != 0 { + t.Errorf("Flush Error: want empty, got %d", len(got)) + } + + // Check Flush returns sorted? + wantTxs := make([]*transaction.Transaction, 0, 5) + for range 5 { + tx := mustTx(t) + wantTxs = append(wantTxs, tx) + mustAdd(t, mp, tx) + } + slices.SortFunc(wantTxs, transaction.Compare) + + gotTxs := mp.Flush(0) + + if !slices.EqualFunc(gotTxs, wantTxs, (*transaction.Transaction).Equal) { + t.Error("Flush Error: expected transaction from flush is not sorted") + } + + // Partial Limit + wantTxs = make([]*transaction.Transaction, 0, 5) + for range 5 { + tx := mustTx(t) + wantTxs = append(wantTxs, tx) + mustAdd(t, mp, tx) + } + slices.SortFunc(wantTxs, transaction.Compare) + + gotTxs = mp.Flush(2) + + if mp.Count() != 3 { + t.Errorf("Flush Error: expeced count = 3, got = %d", mp.Count()) + } + + // Check the mempool with Has method + for _, tx := range gotTxs { + if mp.Has(tx.TxID) { + t.Error("Flush Error: flushed transaction still in mempool") + } + } + for _, tx := range wantTxs[2:] { + if !mp.Has(tx.TxID) { + t.Error("FLush Error: missing transaction from mempool after Flush") + } + } + + // Limit exceeds count + gotTxs = mp.Flush(10) + if len(gotTxs) != 3 { + t.Errorf("Flush Error: expected = 3, got = %d", len(gotTxs)) + } + if mp.Count() != 0 { + t.Errorf("Flush Error: mempool not empty, got = %d", mp.Count()) + } + + // Negative limit + for range 5 { + mustAdd(t, mp, mustTx(t)) + } + mp.Flush(-1) + + if mp.Count() != 0 { + t.Errorf("Flush Error: mempool not empty, got = %d", mp.Count()) + } +} + +func TestFlush_Atomicity(t *testing.T) { + t.Parallel() + + mp := New() + + // Adding consecutively + var wg sync.WaitGroup + const addedCount = 50 + + txs := make([]*transaction.Transaction, addedCount) + for i := range txs { + txs[i] = mustTx(t) + } + + for _, tx := range txs { + wg.Go(func() { + if err := mp.Add(tx); err != nil { + t.Errorf("Unexpected Add Error: %v", err) + } + }) + } + wg.Wait() + + flushed := mp.Flush(0) + remaining := mp.Count() + + if len(flushed)+remaining != addedCount { + t.Errorf("Flush Error: transaction missing or duplicated: want = %d, flushed = %d, remaining = %d", + addedCount, + len(flushed), + remaining) + } + + // Concurectly running Add and Flush in parallel + var ( + flushedMu sync.Mutex + allFlushed []*transaction.Transaction + ) + + for range 200 { + wg.Go(func() { + mustAdd(t, mp, mustTx(t)) + }) + } + + for range 20 { + wg.Go(func() { + time.Sleep(time.Millisecond) + batch := mp.Flush(0) + flushedMu.Lock() + allFlushed = append(allFlushed, batch...) + flushedMu.Unlock() + }) + } + + wg.Wait() + + allFlushed = append(allFlushed, mp.Flush(0)...) + if len(allFlushed) != 200 { + t.Errorf("Flush Error: expected 200, got %d", len(allFlushed)) + } +} + +func TestPrune(t *testing.T) { + t.Parallel() + + mp := New(WithTTL(time.Hour)) + now := time.Now() + + expired := mustTx(t, withTimestamp(now.Add(-2*time.Hour).Unix())) + fresh := mustTx(t, withTimestamp(now.Unix())) + + mustAdd(t, mp, expired) + mustAdd(t, mp, fresh) + + evicted := mp.Prune() + + if evicted != 1 { + t.Errorf("Prune Error: evicted count want = 1, got = %d", evicted) + } + if mp.Has(expired.TxID) { + t.Error("Prune Error: mempool has expired transaction") + } + if !mp.Has(fresh.TxID) { + t.Error("Prune Error: missing transaction") + } +} + +func TestRemove(t *testing.T) { + t.Parallel() + + mp := New() + + allTxs := make([]*transaction.Transaction, 0, 3) + for range 3 { + tx := mustTx(t) + allTxs = append(allTxs, tx) + mustAdd(t, mp, tx) + } + slices.SortFunc(allTxs, transaction.Compare) + + mp.Remove([][]byte{allTxs[0].TxID, allTxs[1].TxID}) + + if mp.Count() != 1 { + t.Errorf("Remove Error: mempool count: want 1, got %d", mp.Count()) + } + if !mp.Has(allTxs[2].TxID) { + t.Error("Remove Error: missing transaction") + } + if mp.Has(allTxs[0].TxID) || mp.Has(allTxs[1].TxID) { + t.Error("Remove Error: mempool has removed transaction") + } +} + +func TestHas(t *testing.T) { + t.Parallel() + + mp := New() + tx := mustTx(t) + + if mp.Has(tx.TxID) { + t.Error("Has Error: found transaction in empty mempool") + } + + mustAdd(t, mp, tx) + if !mp.Has(tx.TxID) { + t.Error("Has Error: missing transaction") + } + + mp.Remove([][]byte{tx.TxID}) + if mp.Has(tx.TxID) { + t.Error("Has Error: transaction in mempool after removed") + } +} + +func TestClear(t *testing.T) { + t.Parallel() + + mp := New() + + allTxs := make([]*transaction.Transaction, 0, 3) + for range 3 { + tx := mustTx(t) + allTxs = append(allTxs, tx) + mustAdd(t, mp, tx) + } + slices.SortFunc(allTxs, transaction.Compare) + + mp.Clear() + + if mp.Count() != 0 { + t.Error("Clear Error: Count not 0 after Clear") + } + for _, tx := range allTxs { + if mp.Has(tx.TxID) { + t.Errorf("Clear Error: transaction found in mempool after Clear: %x", + tx.TxID) + } + } + + mp.Clear() // Clear on empty mempool, shouldn't panic +} + +func TestMempool_ConcurrentUniqueAdds(t *testing.T) { + t.Parallel() + + mp := New() + + txs := make([]*transaction.Transaction, 200) + for i := range txs { + txs[i] = mustTx(t) + } + + var wg sync.WaitGroup + for _, tx := range txs { + wg.Go(func() { + if err := mp.Add(tx); err != nil { + t.Errorf("Unexpected Add Error: %v", err) + } + }) + } + wg.Wait() + + if mp.Count() != 200 { + t.Errorf("Mempool Error: mempool count want 200, got %d", + mp.Count()) + } +} + +func TestMempool_ConcurrentDuplicateAdd(t *testing.T) { + t.Parallel() + + mp := New() + tx := mustTx(t) + + var ( + wg sync.WaitGroup + successes atomic.Int32 + duplicates atomic.Int32 + ) + + for range 100 { + wg.Go(func() { + err := mp.Add(tx.Clone()) + + switch { + case err == nil: + successes.Add(1) + case errors.Is(err, ErrDuplicateTx): + duplicates.Add(1) + default: + t.Errorf("Unexpected Error: %v", err) + } + + }) + } + wg.Wait() + + if successes.Load() != 1 { + t.Fatalf("mempool error: successfull adds: want 1, got %d", + successes.Load()) + } + if duplicates.Load() != 99 { + t.Fatalf("mempool error: duplicate adds: want 99, got %d", + duplicates.Load()) + } + if mp.Count() != 1 { + t.Fatalf("mempool error: mempool count: want 1, got %d", + mp.Count()) + } +} + +func TestMempool_ConcurrentMixedOps(t *testing.T) { + t.Parallel() + + mp := New() + + const workers = 8 + const iterations = 100 + + txs := make([]*transaction.Transaction, workers*iterations) + for i := range txs { + txs[i] = mustTx(t) + } + + var wg sync.WaitGroup + for w := range workers { + wg.Go(func() { + for i := range iterations { + tx := txs[w*iterations+i] + switch rand.Intn(6) { + case 0: + if err := mp.Add(tx); err != nil { + t.Error(err) + } + case 1: + _ = mp.Pending() + case 2: + _ = mp.Count() + case 3: + _ = mp.Has(tx.TxID) + case 4: + mp.Remove([][]byte{tx.TxID}) + case 5: + _ = mp.Prune() + } + } + }) + } + wg.Wait() +}