mempool_test.go (13849B)
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 "bytes" 19 "errors" 20 "math/rand" 21 "slices" 22 "sync" 23 "sync/atomic" 24 "testing" 25 "time" 26 27 "certichain/internal/crypto" 28 "certichain/internal/transaction" 29 ) 30 31 // Options to add to mustTx helper function 32 func withUnsigned() func(*transaction.Transaction) { 33 return func(tx *transaction.Transaction) { tx.Signature = nil } 34 } 35 func withTimestamp(unix int64) func(*transaction.Transaction) { 36 return func(tx *transaction.Transaction) { tx.Timestamp = unix } 37 } 38 func withTxID(id []byte) func(*transaction.Transaction) { 39 return func(tx *transaction.Transaction) { tx.TxID = id } 40 } 41 42 // mustTx creates a new transaction. 43 func mustTx( 44 t *testing.T, 45 opts ...func(*transaction.Transaction), 46 ) *transaction.Transaction { 47 t.Helper() 48 49 pub, priv, err := crypto.GenerateKeyPair() 50 if err != nil { 51 t.Fatal(err) 52 } 53 did, err := crypto.NewDID(pub) 54 if err != nil { 55 t.Fatal(err) 56 } 57 58 root := mustMerkleRoot(t) 59 tx, err := transaction.New(did, root[:]) 60 if err != nil { 61 t.Fatal(err) 62 } 63 if err := tx.Sign(priv); err != nil { 64 t.Fatalf("failed to sign: %v", err) 65 } 66 67 for _, opt := range opts { 68 opt(tx) 69 } 70 71 return tx 72 } 73 74 // mustAdd adds a transaction to the mempool 75 func mustAdd( 76 t *testing.T, 77 mp *Mempool, 78 tx *transaction.Transaction, 79 ) { 80 t.Helper() 81 82 if err := mp.Add(tx); err != nil { 83 t.Fatal(err) 84 } 85 } 86 87 // mustMerkleRoot returns a merkle root. 88 func mustMerkleRoot( 89 t *testing.T, 90 ) crypto.Hash { 91 t.Helper() 92 return crypto.HashBytes([]byte("TEST_MERKLE_ROOT")) 93 } 94 95 func TestAdd_Validation(t *testing.T) { 96 t.Parallel() 97 98 tests := []struct { 99 name string 100 tx *transaction.Transaction 101 wantError error 102 }{ 103 { 104 "nil transaction", 105 nil, 106 ErrNilTx, 107 }, 108 { 109 "unsigned transaction", 110 mustTx(t, withUnsigned()), 111 ErrInvalidTx, 112 }, 113 { 114 "TxID too short", 115 mustTx(t, withTxID([]byte("INVALID"))), 116 ErrInvalidTx, 117 }, 118 { 119 "TxID too long", 120 mustTx(t, withTxID(make([]byte, 42))), 121 ErrInvalidTx, 122 }, 123 { 124 "Valid signed Tx", 125 mustTx(t), 126 nil, 127 }, 128 } 129 130 for _, tt := range tests { 131 t.Run(tt.name, func(t *testing.T) { 132 t.Parallel() 133 134 mp := New() 135 err := mp.Add(tt.tx) 136 137 if !errors.Is(err, tt.wantError) { 138 t.Fatalf("Unexpected Error: want = %v, got = %v", 139 tt.wantError, 140 err, 141 ) 142 } 143 }) 144 } 145 } 146 147 func TestAdd_Duplicates(t *testing.T) { 148 t.Parallel() 149 150 // Test adding the same transaction twice 151 mp := New() 152 tx := mustTx(t) 153 154 mustAdd(t, mp, tx) 155 if err := mp.Add(tx); !errors.Is(err, ErrDuplicateTx) { 156 t.Fatalf("Unexpected Error: want = %v, got = %v", 157 ErrDuplicateTx, err) 158 } 159 160 // Test with same TxID, and different merkleroot 161 tx1 := tx.Clone() 162 tx1.MerkleRoot = []byte("VALID_DUP") 163 164 if err := mp.Add(tx1); !errors.Is(err, ErrDuplicateTx) { 165 t.Fatalf("Unexpected Error: want = %v, got = %v", 166 ErrDuplicateTx, err) 167 } 168 } 169 170 func TestAdd_CapacityAndOrdering(t *testing.T) { 171 t.Parallel() 172 173 mp := New(WithMaxSize(2)) 174 175 mustAdd(t, mp, mustTx(t)) 176 mustAdd(t, mp, mustTx(t)) 177 178 if err := mp.Add(mustTx(t)); !errors.Is(err, ErrMempoolFull) { 179 t.Fatalf("Unexpected Error: want = %v, got = %v", 180 ErrMempoolFull, err) 181 } 182 183 // Check ordering of error 184 // ErrDuplicateTx must win over ErrMempoolFull 185 mp1 := New(WithMaxSize(1)) 186 tx := mustTx(t) 187 188 mustAdd(t, mp1, tx) 189 if err := mp1.Add(tx); !errors.Is(err, ErrDuplicateTx) { 190 t.Fatalf("Unexpected Error: want = %v, got = %v", 191 ErrDuplicateTx, err) 192 } 193 } 194 195 // This below test I don't think is entirely correct 196 func TestAdd_DefensiveCopy(t *testing.T) { 197 t.Parallel() 198 199 mp := New() 200 tx := mustTx(t) 201 202 originalRoot := bytes.Clone(tx.MerkleRoot) 203 originalSign := bytes.Clone(tx.Signature) 204 originalNonce := bytes.Clone(tx.Nonce) 205 206 mustAdd(t, mp, tx) 207 208 tx.MerkleRoot[0] = 0xff // Tampering with the data, after add 209 210 pending := mp.Pending() 211 if !bytes.Equal(pending[0].MerkleRoot, originalRoot) { 212 t.Error("mempool leaked external mutation") 213 } 214 215 tx.Signature = []byte("SIGNED_LOL") 216 if !bytes.Equal(pending[0].Signature, originalSign) { 217 t.Error("mempool leaked external mutation") 218 } 219 220 tx.Nonce = []byte("TRULY_RANDOM_NONCE") 221 if !bytes.Equal(pending[0].Nonce, originalNonce) { 222 t.Error("mempool leadked external mutation") 223 } 224 } 225 226 func TestGet(t *testing.T) { 227 t.Parallel() 228 229 mp := New() 230 tx := mustTx(t) 231 232 if mp.Get(tx.TxID) != nil { 233 t.Error("Get Error: found transaction in empty mempool") 234 } 235 236 mustAdd(t, mp, tx) 237 if mp.Get(tx.TxID) == nil { 238 t.Error("Get Error: missing transaction") 239 } 240 241 mp.Remove([][]byte{tx.TxID}) 242 if mp.Get(tx.TxID) != nil { 243 t.Error("Get Error: transction in mempool after removed") 244 } 245 } 246 247 func TestPending_Determinism(t *testing.T) { 248 t.Parallel() 249 250 // checking the ordering of timestamps 251 // i.e. checking if the function sorts 252 mp := New() 253 254 tx1 := mustTx(t, withTimestamp(300)) 255 tx2 := mustTx(t, withTimestamp(100)) 256 tx3 := mustTx(t, withTimestamp(200)) 257 258 txs := []*transaction.Transaction{tx1, tx2, tx3} 259 260 for _, tx := range txs { 261 mustAdd(t, mp, tx) 262 } 263 264 pending := mp.Pending() 265 if !slices.IsSortedFunc(pending, transaction.Compare) { 266 t.Error("mempool is unsorted") 267 } 268 269 // Testing how tiebreakers will work 270 mp2 := New() 271 272 txA := mustTx(t, withTimestamp(500), withTxID(bytes.Repeat([]byte{0x01}, 32))) 273 txB := mustTx(t, withTimestamp(500), withTxID(bytes.Repeat([]byte{0x00}, 32))) 274 txs = []*transaction.Transaction{txA, txB} 275 276 for _, tx := range txs { 277 mustAdd(t, mp2, tx) 278 } 279 280 pending = mp2.Pending() 281 if !bytes.Equal(pending[0].TxID, txB.TxID) { 282 t.Errorf( 283 "tiebreak failed: want TxB (smaller) first, got TxID = %x", 284 pending[0].TxID, 285 ) 286 } 287 288 // Stability under repetition 289 for range 50 { 290 mp3 := New() 291 292 txA := mustTx( 293 t, 294 withTimestamp(500), 295 withTxID(bytes.Repeat([]byte{0x01}, 32)), 296 ) 297 txB := mustTx( 298 t, 299 withTimestamp(500), 300 withTxID(bytes.Repeat([]byte{0x00}, 32)), 301 ) 302 303 txs = []*transaction.Transaction{txA, txB} 304 305 for _, tx := range txs { 306 mustAdd(t, mp3, tx) 307 } 308 309 pending = mp3.Pending() 310 if !bytes.Equal(pending[0].TxID, txB.TxID) { 311 t.Errorf( 312 "tiebreak failed: want TxB (smaller) first, got TxID = %x", 313 pending[0].TxID, 314 ) 315 } 316 } 317 } 318 319 func TestPending_ReadOnly(t *testing.T) { 320 t.Parallel() 321 322 mp := New() 323 mustAdd(t, mp, mustTx(t)) 324 325 // Call pending consecutively twice 326 pending := mp.Pending() 327 pending1 := mp.Pending() 328 329 if mp.Count() != 1 { 330 t.Error("Error: No. of transactions changed") 331 } 332 if pending[0] != pending1[0] { 333 t.Error("Error: pending structs not equal") 334 } 335 } 336 337 func TestFlush_Behavior(t *testing.T) { 338 t.Parallel() 339 340 mp := New() 341 342 // Flush empty 343 if got := mp.Flush(0); len(got) != 0 { 344 t.Errorf("Flush Error: want empty, got %d", len(got)) 345 } 346 if got := mp.Flush(5); len(got) != 0 { 347 t.Errorf("Flush Error: want empty, got %d", len(got)) 348 } 349 350 // Check Flush returns sorted? 351 wantTxs := make([]*transaction.Transaction, 0, 5) 352 for range 5 { 353 tx := mustTx(t) 354 wantTxs = append(wantTxs, tx) 355 mustAdd(t, mp, tx) 356 } 357 slices.SortFunc(wantTxs, transaction.Compare) 358 359 gotTxs := mp.Flush(0) 360 361 if !slices.EqualFunc(gotTxs, wantTxs, (*transaction.Transaction).Equal) { 362 t.Error("Flush Error: expected transaction from flush is not sorted") 363 } 364 365 // Partial Limit 366 wantTxs = make([]*transaction.Transaction, 0, 5) 367 for range 5 { 368 tx := mustTx(t) 369 wantTxs = append(wantTxs, tx) 370 mustAdd(t, mp, tx) 371 } 372 slices.SortFunc(wantTxs, transaction.Compare) 373 374 gotTxs = mp.Flush(2) 375 376 if mp.Count() != 3 { 377 t.Errorf("Flush Error: expeced count = 3, got = %d", mp.Count()) 378 } 379 380 // Check the mempool with Has method 381 for _, tx := range gotTxs { 382 if mp.Has(tx.TxID) { 383 t.Error("Flush Error: flushed transaction still in mempool") 384 } 385 } 386 for _, tx := range wantTxs[2:] { 387 if !mp.Has(tx.TxID) { 388 t.Error("FLush Error: missing transaction from mempool after Flush") 389 } 390 } 391 392 // Limit exceeds count 393 gotTxs = mp.Flush(10) 394 if len(gotTxs) != 3 { 395 t.Errorf("Flush Error: expected = 3, got = %d", len(gotTxs)) 396 } 397 if mp.Count() != 0 { 398 t.Errorf("Flush Error: mempool not empty, got = %d", mp.Count()) 399 } 400 401 // Negative limit 402 for range 5 { 403 mustAdd(t, mp, mustTx(t)) 404 } 405 mp.Flush(-1) 406 407 if mp.Count() != 0 { 408 t.Errorf("Flush Error: mempool not empty, got = %d", mp.Count()) 409 } 410 } 411 412 func TestFlush_Atomicity(t *testing.T) { 413 t.Parallel() 414 415 mp := New() 416 417 // Adding consecutively 418 var wg sync.WaitGroup 419 const addedCount = 50 420 421 txs := make([]*transaction.Transaction, addedCount) 422 for i := range txs { 423 txs[i] = mustTx(t) 424 } 425 426 for _, tx := range txs { 427 wg.Go(func() { 428 if err := mp.Add(tx); err != nil { 429 t.Errorf("Unexpected Add Error: %v", err) 430 } 431 }) 432 } 433 wg.Wait() 434 435 flushed := mp.Flush(0) 436 remaining := mp.Count() 437 438 if len(flushed)+remaining != addedCount { 439 t.Errorf("Flush Error: transaction missing or duplicated: want = %d, flushed = %d, remaining = %d", 440 addedCount, 441 len(flushed), 442 remaining) 443 } 444 445 // Concurectly running Add and Flush in parallel 446 var ( 447 flushedMu sync.Mutex 448 allFlushed []*transaction.Transaction 449 ) 450 451 for range 200 { 452 wg.Go(func() { 453 mustAdd(t, mp, mustTx(t)) 454 }) 455 } 456 457 for range 20 { 458 wg.Go(func() { 459 time.Sleep(time.Millisecond) 460 batch := mp.Flush(0) 461 flushedMu.Lock() 462 allFlushed = append(allFlushed, batch...) 463 flushedMu.Unlock() 464 }) 465 } 466 467 wg.Wait() 468 469 allFlushed = append(allFlushed, mp.Flush(0)...) 470 if len(allFlushed) != 200 { 471 t.Errorf("Flush Error: expected 200, got %d", len(allFlushed)) 472 } 473 } 474 475 func TestPrune(t *testing.T) { 476 t.Parallel() 477 478 mp := New(WithTTL(time.Hour)) 479 now := time.Now() 480 481 expired := mustTx(t, withTimestamp(now.Add(-2*time.Hour).Unix())) 482 fresh := mustTx(t, withTimestamp(now.Unix())) 483 484 mustAdd(t, mp, expired) 485 mustAdd(t, mp, fresh) 486 487 evicted := mp.Prune() 488 489 if evicted != 1 { 490 t.Errorf("Prune Error: evicted count want = 1, got = %d", evicted) 491 } 492 if mp.Has(expired.TxID) { 493 t.Error("Prune Error: mempool has expired transaction") 494 } 495 if !mp.Has(fresh.TxID) { 496 t.Error("Prune Error: missing transaction") 497 } 498 } 499 500 func TestRemove(t *testing.T) { 501 t.Parallel() 502 503 mp := New() 504 505 allTxs := make([]*transaction.Transaction, 0, 3) 506 for range 3 { 507 tx := mustTx(t) 508 allTxs = append(allTxs, tx) 509 mustAdd(t, mp, tx) 510 } 511 slices.SortFunc(allTxs, transaction.Compare) 512 513 mp.Remove([][]byte{allTxs[0].TxID, allTxs[1].TxID}) 514 515 if mp.Count() != 1 { 516 t.Errorf("Remove Error: mempool count: want 1, got %d", mp.Count()) 517 } 518 if !mp.Has(allTxs[2].TxID) { 519 t.Error("Remove Error: missing transaction") 520 } 521 if mp.Has(allTxs[0].TxID) || mp.Has(allTxs[1].TxID) { 522 t.Error("Remove Error: mempool has removed transaction") 523 } 524 } 525 526 func TestHas(t *testing.T) { 527 t.Parallel() 528 529 mp := New() 530 tx := mustTx(t) 531 532 if mp.Has(tx.TxID) { 533 t.Error("Has Error: found transaction in empty mempool") 534 } 535 536 mustAdd(t, mp, tx) 537 if !mp.Has(tx.TxID) { 538 t.Error("Has Error: missing transaction") 539 } 540 541 mp.Remove([][]byte{tx.TxID}) 542 if mp.Has(tx.TxID) { 543 t.Error("Has Error: transaction in mempool after removed") 544 } 545 } 546 547 func TestClear(t *testing.T) { 548 t.Parallel() 549 550 mp := New() 551 552 allTxs := make([]*transaction.Transaction, 0, 3) 553 for range 3 { 554 tx := mustTx(t) 555 allTxs = append(allTxs, tx) 556 mustAdd(t, mp, tx) 557 } 558 slices.SortFunc(allTxs, transaction.Compare) 559 560 mp.Clear() 561 562 if mp.Count() != 0 { 563 t.Error("Clear Error: Count not 0 after Clear") 564 } 565 for _, tx := range allTxs { 566 if mp.Has(tx.TxID) { 567 t.Errorf("Clear Error: transaction found in mempool after Clear: %x", 568 tx.TxID) 569 } 570 } 571 572 mp.Clear() // Clear on empty mempool, shouldn't panic 573 } 574 575 func TestMempool_ConcurrentUniqueAdds(t *testing.T) { 576 t.Parallel() 577 578 mp := New() 579 580 txs := make([]*transaction.Transaction, 200) 581 for i := range txs { 582 txs[i] = mustTx(t) 583 } 584 585 var wg sync.WaitGroup 586 for _, tx := range txs { 587 wg.Go(func() { 588 if err := mp.Add(tx); err != nil { 589 t.Errorf("Unexpected Add Error: %v", err) 590 } 591 }) 592 } 593 wg.Wait() 594 595 if mp.Count() != 200 { 596 t.Errorf("Mempool Error: mempool count want 200, got %d", 597 mp.Count()) 598 } 599 } 600 601 func TestMempool_ConcurrentDuplicateAdd(t *testing.T) { 602 t.Parallel() 603 604 mp := New() 605 tx := mustTx(t) 606 607 var ( 608 wg sync.WaitGroup 609 successes atomic.Int32 610 duplicates atomic.Int32 611 ) 612 613 for range 100 { 614 wg.Go(func() { 615 err := mp.Add(tx.Clone()) 616 617 switch { 618 case err == nil: 619 successes.Add(1) 620 case errors.Is(err, ErrDuplicateTx): 621 duplicates.Add(1) 622 default: 623 t.Errorf("Unexpected Error: %v", err) 624 } 625 626 }) 627 } 628 wg.Wait() 629 630 if successes.Load() != 1 { 631 t.Fatalf("mempool error: successfull adds: want 1, got %d", 632 successes.Load()) 633 } 634 if duplicates.Load() != 99 { 635 t.Fatalf("mempool error: duplicate adds: want 99, got %d", 636 duplicates.Load()) 637 } 638 if mp.Count() != 1 { 639 t.Fatalf("mempool error: mempool count: want 1, got %d", 640 mp.Count()) 641 } 642 } 643 644 func TestMempool_ConcurrentMixedOps(t *testing.T) { 645 t.Parallel() 646 647 mp := New() 648 649 const workers = 8 650 const iterations = 100 651 652 txs := make([]*transaction.Transaction, workers*iterations) 653 for i := range txs { 654 txs[i] = mustTx(t) 655 } 656 657 var wg sync.WaitGroup 658 for w := range workers { 659 wg.Go(func() { 660 for i := range iterations { 661 tx := txs[w*iterations+i] 662 switch rand.Intn(6) { 663 case 0: 664 if err := mp.Add(tx); err != nil { 665 t.Error(err) 666 } 667 case 1: 668 _ = mp.Pending() 669 case 2: 670 _ = mp.Count() 671 case 3: 672 _ = mp.Has(tx.TxID) 673 case 4: 674 mp.Remove([][]byte{tx.TxID}) 675 case 5: 676 _ = mp.Prune() 677 } 678 } 679 }) 680 } 681 wg.Wait() 682 }