From a8a66494ec35403dd8d73bd74add5cf0d51bf3db Mon Sep 17 00:00:00 2001 From: Pouya Date: Sun, 24 Mar 2024 13:18:43 +0100 Subject: [PATCH] Fix mutex issues --- src/plugins/uniswap/uniswap.go | 56 ++++++++++++++++++++++------------ src/utils/debounce.go | 2 +- 2 files changed, 37 insertions(+), 21 deletions(-) diff --git a/src/plugins/uniswap/uniswap.go b/src/plugins/uniswap/uniswap.go index 7dfa8de7..a8fb1129 100644 --- a/src/plugins/uniswap/uniswap.go +++ b/src/plugins/uniswap/uniswap.go @@ -67,6 +67,39 @@ var crossPrices map[string]big.Int var crossTokens map[string]datasets.TokenKey var lastPrice big.Int +func CheckAndCacheSignature( + reportedValues *xsync.MapOf[bls12381.G1Affine, big.Int], + signature bls12381.G1Affine, signer bls.Signer, + hash bls12381.G1Affine, + totalVoted *big.Int) error { + + signatureMutex.Lock() + defer signatureMutex.Unlock() + + cached, _ := signatureCache.Get(hash) + + packed := bls.Signature{ + Signature: signature, + Signer: signer, + Processed: false, + } + + for _, item := range cached { + if item.Signer.PublicKey == signer.PublicKey { + log.Logger. + With("Address", address.Calculate(signer.PublicKey[:])). + Debug("Duplicated signature") + return fmt.Errorf("duplicated signature") + } + } + + reportedValues.Store(hash, *totalVoted) + cached = append(cached, packed) + signatureCache.Add(hash, cached) + + return nil +} + // TODO: This needs to work with different datasets // TODO: Can we turn this into a library func? func RecordSignature( @@ -146,29 +179,12 @@ func RecordSignature( return isMajority }) - signatureMutex.Lock() - cached, _ := signatureCache.Get(hash) - - packed := bls.Signature{ - Signature: signature, - Signer: signer, - Processed: false, - } + err = CheckAndCacheSignature(&reportedValues, signature, signer, hash, totalVoted) - for _, item := range cached { - if item.Signer.PublicKey == signer.PublicKey { - log.Logger. - With("Address", address.Calculate(signer.PublicKey[:])). - Debug("Duplicated signature") - return - } + if err != nil { + return } - reportedValues.Store(hash, *totalVoted) - cached = append(cached, packed) - signatureCache.Add(hash, cached) - signatureMutex.Unlock() - if isMajority { reportLog := log.Logger. With("Block", info.Asset.Block). diff --git a/src/utils/debounce.go b/src/utils/debounce.go index 334ba025..0ca7d3fa 100644 --- a/src/utils/debounce.go +++ b/src/utils/debounce.go @@ -33,9 +33,9 @@ func Debounce[KeyType comparable, ArgType any]( debounce.Lock() go func() { + defer debounce.Unlock() delete(debounce.timers, key) function(arg) - debounce.Unlock() }() }) }