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