github.com/sberex/go-sberex@v1.8.2-0.20181113200658-ed96ac38f7d7/internal/ethapi/addrlock.go (about) 1 // This file is part of the go-sberex library. The go-sberex library is 2 // free software: you can redistribute it and/or modify it under the terms 3 // of the GNU Lesser General Public License as published by the Free 4 // Software Foundation, either version 3 of the License, or (at your option) 5 // any later version. 6 // 7 // The go-sberex library is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 10 // General Public License <http://www.gnu.org/licenses/> for more details. 11 12 package ethapi 13 14 import ( 15 "sync" 16 17 "github.com/Sberex/go-sberex/common" 18 ) 19 20 type AddrLocker struct { 21 mu sync.Mutex 22 locks map[common.Address]*sync.Mutex 23 } 24 25 // lock returns the lock of the given address. 26 func (l *AddrLocker) lock(address common.Address) *sync.Mutex { 27 l.mu.Lock() 28 defer l.mu.Unlock() 29 if l.locks == nil { 30 l.locks = make(map[common.Address]*sync.Mutex) 31 } 32 if _, ok := l.locks[address]; !ok { 33 l.locks[address] = new(sync.Mutex) 34 } 35 return l.locks[address] 36 } 37 38 // LockAddr locks an account's mutex. This is used to prevent another tx getting the 39 // same nonce until the lock is released. The mutex prevents the (an identical nonce) from 40 // being read again during the time that the first transaction is being signed. 41 func (l *AddrLocker) LockAddr(address common.Address) { 42 l.lock(address).Lock() 43 } 44 45 // UnlockAddr unlocks the mutex of the given account. 46 func (l *AddrLocker) UnlockAddr(address common.Address) { 47 l.lock(address).Unlock() 48 }