github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/store/mainchain/validation/nonce_cache.go (about)

     1  package validation
     2  
     3  import (
     4  	"github.com/sixexorg/magnetic-ring/common"
     5  	"github.com/sixexorg/magnetic-ring/core/mainchain/types"
     6  )
     7  
     8  var (
     9  	AccountNonceInstance *AccountNonceCache
    10  	autoNonce            map[types.TransactionType]struct{}
    11  )
    12  
    13  func init() {
    14  	autoNonce = make(map[types.TransactionType]struct{})
    15  	autoNonce[types.RaiseUT] = struct{}{}
    16  }
    17  
    18  func AutoNonceContains(typ types.TransactionType) bool {
    19  	_, ok := autoNonce[typ]
    20  	return ok
    21  }
    22  
    23  type AccountNonceCache struct {
    24  	accountNonce map[common.Address]uint64
    25  	height       uint64
    26  	nonceFunc    GetNonceFunc
    27  }
    28  type GetNonceFunc func(height uint64, account common.Address) uint64
    29  
    30  func (this *AccountNonceCache) GetAccountNonce(account common.Address) uint64 {
    31  	if this.accountNonce[account] != 0 {
    32  		return this.accountNonce[account]
    33  	}
    34  	return this.nonceFunc(this.height, account)
    35  }
    36  
    37  func (this *AccountNonceCache) reset(height uint64) {
    38  	this.accountNonce = make(map[common.Address]uint64)
    39  	this.height = height
    40  }
    41  func NewAccountNonceCache(f GetNonceFunc) {
    42  	AccountNonceInstance = &AccountNonceCache{
    43  		nonceFunc: f,
    44  	}
    45  }
    46  func (this *AccountNonceCache) SetNonce(account common.Address, nonce uint64) {
    47  	this.accountNonce[account] = nonce
    48  }
    49  
    50  func (this *AccountNonceCache) nonceSub(account common.Address) {
    51  	this.accountNonce[account]--
    52  }