certichain

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

mempool.go (4874B)


      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 mempool
     16 
     17 import (
     18 	"errors"
     19 	"slices"
     20 	"sync"
     21 	"time"
     22 
     23 	"certichain/internal/crypto"
     24 	"certichain/internal/transaction"
     25 )
     26 
     27 const (
     28 	DefaultMaxSize = 5_000          // Mempool capacity
     29 	DefaultTTL     = 24 * time.Hour // transaction lifespan
     30 )
     31 
     32 var (
     33 	ErrDuplicateTx = errors.New("mempool: duplicate transaction ID")
     34 	ErrMempoolFull = errors.New("mempool: at capacity")
     35 	ErrNilTx       = errors.New("mempool: nil transaction")
     36 	ErrInvalidTx   = errors.New("mempool: invalid transaction")
     37 )
     38 
     39 // Mempool manages unconfirmed transactions before they are mined into a block.
     40 type Mempool struct {
     41 	mu      sync.RWMutex
     42 	txs     map[string]*transaction.Transaction
     43 	maxSize int
     44 	ttl     time.Duration
     45 }
     46 
     47 type Option func(*Mempool)
     48 
     49 // WithMaxSize configures the maximum number of transactions the pool can hold.
     50 func WithMaxSize(n int) Option {
     51 	return func(mp *Mempool) {
     52 		mp.maxSize = n
     53 	}
     54 }
     55 
     56 // WithTTL configures the time-to-live before a transaction is pruned.
     57 func WithTTL(d time.Duration) Option {
     58 	return func(mp *Mempool) {
     59 		mp.ttl = d
     60 	}
     61 }
     62 
     63 // New initializes a Mempool with default settings, applying any provided options.
     64 func New(opts ...Option) *Mempool {
     65 	mp := &Mempool{
     66 		txs:     make(map[string]*transaction.Transaction),
     67 		maxSize: DefaultMaxSize,
     68 		ttl:     DefaultTTL,
     69 	}
     70 	for _, opt := range opts {
     71 		opt(mp)
     72 	}
     73 	return mp
     74 }
     75 
     76 // Add inserts a transaction into the mempool.
     77 func (mp *Mempool) Add(tx *transaction.Transaction) error {
     78 	if tx == nil {
     79 		return ErrNilTx
     80 	}
     81 	if !tx.IsSigned() {
     82 		return ErrInvalidTx
     83 	}
     84 	if len(tx.TxID) != crypto.HashSize {
     85 		return ErrInvalidTx
     86 	}
     87 
     88 	mp.mu.Lock()
     89 	defer mp.mu.Unlock()
     90 
     91 	id := string(tx.TxID)
     92 	if _, exists := mp.txs[id]; exists {
     93 		return ErrDuplicateTx
     94 	}
     95 
     96 	if len(mp.txs) >= mp.maxSize {
     97 		return ErrMempoolFull
     98 	}
     99 
    100 	mp.txs[id] = tx.Clone()
    101 	return nil
    102 }
    103 
    104 // sortedTransactions returns all transactions deterministically sorted.
    105 // It assumes the caller holds the appropriate mutex.
    106 func (mp *Mempool) sortedTransactions() []*transaction.Transaction {
    107 	if len(mp.txs) == 0 {
    108 		return nil
    109 	}
    110 
    111 	result := make([]*transaction.Transaction, 0, len(mp.txs))
    112 	for _, tx := range mp.txs {
    113 		result = append(result, tx)
    114 	}
    115 
    116 	slices.SortFunc(result, transaction.Compare)
    117 	return result
    118 }
    119 
    120 // Get checks if the transaction exists in the mempool and returns it.
    121 func (mp *Mempool) Get(txID []byte) *transaction.Transaction {
    122 	mp.mu.Lock()
    123 	defer mp.mu.Unlock()
    124 	if tx, exists := mp.txs[string(txID)]; exists {
    125 		return tx.Clone()
    126 	}
    127 	return nil
    128 }
    129 
    130 // Pending returns all the transactions deterministically sorted.
    131 func (mp *Mempool) Pending() []*transaction.Transaction {
    132 	mp.mu.RLock()
    133 	defer mp.mu.RUnlock()
    134 	return mp.sortedTransactions()
    135 }
    136 
    137 // Flush removes and returns up to the limit pending transactions, sorted
    138 // deterministically (oldest first). A limit of 0 or less returns all
    139 // pending transactions.
    140 func (mp *Mempool) Flush(limit int) []*transaction.Transaction {
    141 	mp.mu.Lock()
    142 	defer mp.mu.Unlock()
    143 
    144 	allTxs := mp.sortedTransactions()
    145 	if len(allTxs) == 0 {
    146 		return nil
    147 	}
    148 
    149 	count := len(allTxs)
    150 	if limit > 0 && limit < count {
    151 		count = limit
    152 	}
    153 	result := allTxs[:count]
    154 
    155 	for _, tx := range result {
    156 		delete(mp.txs, string(tx.TxID))
    157 	}
    158 	return result
    159 }
    160 
    161 // Prune deletes transactions older than TTL.
    162 // Returns evicted count.
    163 func (mp *Mempool) Prune() int {
    164 	mp.mu.Lock()
    165 	defer mp.mu.Unlock()
    166 
    167 	evicted := 0
    168 	cutoff := time.Now().Add(-mp.ttl).Unix()
    169 
    170 	for id, tx := range mp.txs {
    171 		if tx.Timestamp < cutoff {
    172 			delete(mp.txs, id)
    173 			evicted++
    174 		}
    175 	}
    176 	return evicted
    177 }
    178 
    179 // Remove deletes specific transactions from the mempool.
    180 func (mp *Mempool) Remove(txIDs [][]byte) {
    181 	mp.mu.Lock()
    182 	defer mp.mu.Unlock()
    183 
    184 	for _, id := range txIDs {
    185 		delete(mp.txs, string(id))
    186 	}
    187 }
    188 
    189 // Count returns the current count of transactions.
    190 func (mp *Mempool) Count() int {
    191 	mp.mu.RLock()
    192 	defer mp.mu.RUnlock()
    193 	return len(mp.txs)
    194 }
    195 
    196 // Has reports whether a transaction with given txID is pending.
    197 func (mp *Mempool) Has(txID []byte) bool {
    198 	mp.mu.RLock()
    199 	defer mp.mu.RUnlock()
    200 	_, exists := mp.txs[string(txID)]
    201 	return exists
    202 }
    203 
    204 // Clear removes all the pending transactions.
    205 func (mp *Mempool) Clear() {
    206 	mp.mu.Lock()
    207 	defer mp.mu.Unlock()
    208 	mp.txs = make(map[string]*transaction.Transaction)
    209 }