-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathservice.go
101 lines (81 loc) · 2.31 KB
/
service.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package async_nonce
import (
"context"
"os"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/code-payments/code-server/pkg/code/data/nonce"
"github.com/code-payments/code-server/pkg/code/async"
code_data "github.com/code-payments/code-server/pkg/code/data"
)
var (
ErrInvalidNonceAccountSize = errors.New("invalid nonce account size")
ErrInvalidNonceLimitExceeded = errors.New("nonce account limit exceeded")
ErrNoAvailableKeys = errors.New("no available keys in the vault")
)
const (
nonceBatchSize = 100
noncePoolSizeDefault = 10 // Reserve is calculated as size * 2
nonceKeyPrefixDefault = "non"
nonceKeyPrefixEnv = "NONCE_PUBKEY_PREFIX"
noncePoolSizeEnv = "NONCE_POOL_SIZE"
)
type service struct {
log *logrus.Entry
data code_data.Provider
rent uint64
prefix string
size int
}
func New(data code_data.Provider) async.Service {
return &service{
log: logrus.StandardLogger().WithField("service", "nonce"),
data: data,
prefix: nonceKeyPrefixDefault,
size: noncePoolSizeDefault,
}
}
func (p *service) Start(ctx context.Context, interval time.Duration) error {
// Look for user defined prefix value
prefix := os.Getenv(nonceKeyPrefixEnv)
if len(prefix) > 0 {
p.prefix = prefix
}
// Look for user defined pool size value
sizeStr := os.Getenv(noncePoolSizeEnv)
if len(sizeStr) > 0 {
size, err := strconv.Atoi(sizeStr)
if err != nil {
return errors.Wrap(err, "invalid nonce pool size")
}
p.size = size
}
// Generate vault keys until we have at least 10 in reserve to use for the pool
go p.generateKeys(ctx)
// Watch the size of the nonce pool and create accounts if necessary
go p.generateNonceAccounts(ctx)
// Setup workers to watch for nonce state changes on the Solana side
for _, item := range []nonce.State{
nonce.StateUnknown,
nonce.StateReleased,
} {
go func(state nonce.State) {
err := p.worker(ctx, state, interval)
if err != nil && err != context.Canceled {
p.log.WithError(err).Warnf("nonce processing loop terminated unexpectedly for state %d", state)
}
}(item)
}
go func() {
err := p.metricsGaugeWorker(ctx)
if err != nil && err != context.Canceled {
p.log.WithError(err).Warn("nonce metrics gauge loop terminated unexpectedly")
}
}()
select {
case <-ctx.Done():
return ctx.Err()
}
}