github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/app/rpc/types/addrlock.go (about)

     1  package types
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/ethereum/go-ethereum/common"
     7  )
     8  
     9  // AddrLocker is a mutex structure used to avoid querying outdated account data
    10  type AddrLocker struct {
    11  	mu    sync.Mutex
    12  	locks map[common.Address]*sync.Mutex
    13  }
    14  
    15  // lock returns the lock of the given address.
    16  func (l *AddrLocker) lock(address common.Address) *sync.Mutex {
    17  	l.mu.Lock()
    18  	defer l.mu.Unlock()
    19  	if l.locks == nil {
    20  		l.locks = make(map[common.Address]*sync.Mutex)
    21  	}
    22  	if _, ok := l.locks[address]; !ok {
    23  		l.locks[address] = new(sync.Mutex)
    24  	}
    25  	return l.locks[address]
    26  }
    27  
    28  // LockAddr locks an account's mutex. This is used to prevent another tx getting the
    29  // same nonce until the lock is released. The mutex prevents the (an identical nonce) from
    30  // being read again during the time that the first transaction is being signed.
    31  func (l *AddrLocker) LockAddr(address common.Address) {
    32  	l.lock(address).Lock()
    33  }
    34  
    35  // UnlockAddr unlocks the mutex of the given account.
    36  func (l *AddrLocker) UnlockAddr(address common.Address) {
    37  	l.lock(address).Unlock()
    38  }