From cf7e53842a3c694f1c0cccce2d6754ed24031ded Mon Sep 17 00:00:00 2001 From: bitromortac Date: Tue, 21 Jul 2026 09:19:42 +0000 Subject: [PATCH] firewall: optimize CryptoRandIntn with sync.Pool Utilize a sync.Pool for *big.Int instances in CryptoRandIntn to avoid frequent heap allocations. This significantly reduces garbage collection pressure when randomizing timestamps, amounts, and fees inside loops (e.g. iterating over forwarding history responses). --- firewall/privacy_mapper.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/firewall/privacy_mapper.go b/firewall/privacy_mapper.go index 460181a2..d7b7bec9 100644 --- a/firewall/privacy_mapper.go +++ b/firewall/privacy_mapper.go @@ -11,6 +11,7 @@ import ( "math/big" "strconv" "strings" + "sync" "time" "github.com/btcsuite/btcd/chaincfg/chainhash" @@ -1857,13 +1858,26 @@ func hideBool(randIntn func(n int64) (int64, error)) (bool, error) { return random >= 1, nil } +// bigIntPool is a pool of *big.Int values to avoid frequent heap allocations in +// CryptoRandIntn. +var bigIntPool = sync.Pool{ + New: func() any { + return new(big.Int) + }, +} + // CryptoRandIntn generates a random number between [0, n). func CryptoRandIntn(n int64) (int64, error) { if n == 0 { return 0, nil } - randBig, err := rand.Int(rand.Reader, big.NewInt(n)) + nBig := bigIntPool.Get().(*big.Int) + defer bigIntPool.Put(nBig) + + nBig.SetInt64(n) + + randBig, err := rand.Int(rand.Reader, nBig) if err != nil { return 0, err }