github.com/bitfinexcom/bitfinex-api-go@v0.0.0-20210608095005-9e0b26f200fb/pkg/utils/nonce.go (about) 1 package utils 2 3 import ( 4 "strconv" 5 "sync/atomic" 6 "time" 7 ) 8 9 // v2 types 10 11 type NonceGenerator interface { 12 GetNonce() string 13 } 14 15 type EpochNonceGenerator struct { 16 nonce uint64 17 } 18 19 // GetNonce is a naive nonce producer that takes the current Unix nano epoch 20 // and counts upwards. 21 // This is a naive approach because the nonce bound to the currently used API 22 // key and as such needs to be synchronised with other instances using the same 23 // key in order to avoid race conditions. 24 func (u *EpochNonceGenerator) GetNonce() string { 25 return strconv.FormatUint(atomic.AddUint64(&u.nonce, 1), 10) 26 } 27 28 func NewEpochNonceGenerator() *EpochNonceGenerator { 29 return &EpochNonceGenerator{ 30 nonce: uint64(time.Now().Unix()) * 1000000, 31 } 32 } 33 34 // v1 support 35 36 var nonce uint64 37 38 func init() { 39 nonce = uint64(time.Now().UnixNano()) * 1000000 40 } 41 42 // GetNonce is a naive nonce producer that takes the current Unix nano epoch 43 // and counts upwards. 44 // This is a naive approach because the nonce bound to the currently used API 45 // key and as such needs to be synchronised with other instances using the same 46 // key in order to avoid race conditions. 47 func GetNonce() string { 48 return strconv.FormatUint(atomic.AddUint64(&nonce, 1), 10) 49 }