/
ssv_onboard.go
230 lines (198 loc) · 7.56 KB
/
ssv_onboard.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
package task
import (
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
ssv_network "github.com/stafiprotocol/eth-ssv-client/bindings/SsvNetwork"
ssv_network_views "github.com/stafiprotocol/eth-ssv-client/bindings/SsvNetworkViews"
"github.com/stafiprotocol/eth-ssv-client/pkg/crypto/bls"
"github.com/stafiprotocol/eth-ssv-client/pkg/keyshare"
"github.com/stafiprotocol/eth-ssv-client/pkg/utils"
)
var migrageWaitBlock = uint64(32 * 3)
// onboard validator if:
// 0 staked on stafi and uninitial not onboard
// OR
// 1 staked on stafi and active and not onboard
func (task *Task) checkAndOnboardOnSSV() error {
if !task.offchainStateIsLatest() {
return nil
}
for i := 0; i < task.nextKeyIndex; i++ {
val, exist := task.validatorsByKeyIndex[i]
if !exist {
return fmt.Errorf("validator at index %d not exist", i)
}
if !((val.statusOnStafi == valStatusStaked && (val.statusOnSsv == valStatusUnInitiated || val.statusOnSsv == valStatusRemovedOnSsv) && val.statusOnBeacon == valStatusUnInitiated) || //not init
(val.statusOnStafi == valStatusStaked && (val.statusOnSsv == valStatusUnInitiated || val.statusOnSsv == valStatusRemovedOnSsv) && val.statusOnBeacon == valStatusActiveOnBeacon)) { //not migrate
logrus.Debugf("val: %s not match onboard will skip", hex.EncodeToString(val.privateKey.PublicKey().Marshal()))
continue
}
// check status on ssv
onboard, err := task.ssvNetworkViewsContract.GetValidator(nil, task.ssvKeyPair.CommonAddress(), val.privateKey.PublicKey().Marshal())
if err != nil {
// remove when new SSVViews contract is deployed
if strings.Contains(err.Error(), "execution reverted") {
onboard = false
} else {
return errors.Wrap(err, "ssvNetworkViewsContract.GetValidator failed")
}
}
if onboard {
return fmt.Errorf("validator %s at index %d is onboard on ssv", val.privateKey.PublicKey().SerializeToHexStr(), val.keyIndex)
}
// check removed block
latestBlock, err := task.eth1Client.BlockNumber(context.Background())
if err != nil {
return err
}
if val.removedFromSsvOnBlock+migrageWaitBlock > latestBlock {
logrus.Debugf("val: %s will wait block %d to onboard", hex.EncodeToString(val.privateKey.PublicKey().Marshal()), val.removedFromSsvOnBlock+migrageWaitBlock-latestBlock)
continue
}
cluster, err := task.selectClusterForRegister()
if err != nil {
return errors.Wrap(err, "selectClusterForRegister failed")
}
// encrypt share
clusterOperators := make([]*keyshare.Operator, 0)
for _, id := range cluster.operatorIds {
operator, exist := task.targetOperators[id]
if !exist {
return fmt.Errorf("operator %d not exist in target operators", id)
}
clusterOperators = append(clusterOperators, operator)
}
encryptShares, err := keyshare.EncryptShares(val.privateKey.Marshal(), clusterOperators)
if err != nil {
return err
}
logrus.Debug("start build onboard payload")
// build payload
shares := make([]byte, 0)
pubkeys := make([]byte, 0)
_, needDepositAmount, err := task.calClusterNeedDepositAmount(cluster)
if err != nil {
return errors.Wrap(err, "task.calClusterNeedDepositAmount failed")
}
for i := range clusterOperators {
shareBts, err := base64.StdEncoding.DecodeString(encryptShares[i].EncryptedKey)
if err != nil {
return errors.Wrap(err, "EncryptedKey decode failed")
}
shares = append(shares, shareBts...)
pubkeyBts, err := hexutil.Decode(encryptShares[i].PublicKey)
if err != nil {
return errors.Wrap(err, "publickey decode failed")
}
pubkeys = append(pubkeys, pubkeyBts...)
}
// sign with val private key
data := fmt.Sprintf("%s:%d", task.ssvKeyPair.Address(), task.latestRegistrationNonce)
hash := crypto.Keccak256([]byte(data))
valPrivateKey, err := bls.PrivateKeyFromBytes(val.privateKey.Marshal())
if err != nil {
return err
}
sigs := valPrivateKey.Sign(hash).Marshal()
// build shareData
shareData := append(sigs, pubkeys...)
shareData = append(shareData, shares...)
// check cluster state
isLiquidated, err := task.ssvNetworkViewsContract.IsLiquidated(nil, task.ssvKeyPair.CommonAddress(),
cluster.operatorIds, ssv_network_views.ISSVNetworkCoreCluster(*cluster.latestCluster))
if err != nil {
if strings.Contains(err.Error(), "execution reverted") {
isLiquidated = false
} else {
return errors.Wrap(err, "ssvNetworkViewsContract.IsLiquidated failed")
}
}
if isLiquidated {
logrus.WithFields(logrus.Fields{
"operators": cluster.operatorIds,
}).Warn("cluster is liquidated")
return nil
}
// check balance
ssvAccountBalance, err := task.ssvTokenContract.BalanceOf(nil, task.ssvKeyPair.CommonAddress())
if err != nil {
return err
}
if ssvAccountBalance.Cmp(needDepositAmount) < 0 {
utils.ShutdownRequestChannel <- struct{}{}
return fmt.Errorf("ssv balance not enough, will shutdown. balance: %s, need: %s", ssvAccountBalance.String(), needDepositAmount.String())
}
// check ssv allowance
allowance, err := task.ssvTokenContract.Allowance(nil, task.ssvKeyPair.CommonAddress(), task.ssvNetworkContractAddress)
if err != nil {
return err
}
if allowance.Cmp(needDepositAmount) < 0 {
err = task.connectionOfSsvAccount.LockAndUpdateTxOpts()
if err != nil {
return fmt.Errorf("LockAndUpdateTxOpts err: %s", err)
}
approveAmount := new(big.Int).Mul(needDepositAmount, big.NewInt(10))
approveTx, err := task.ssvTokenContract.Approve(task.connectionOfSsvAccount.TxOpts(), task.ssvNetworkContractAddress, approveAmount)
if err != nil {
task.connectionOfSsvAccount.UnlockTxOpts()
return err
}
task.connectionOfSsvAccount.UnlockTxOpts()
logrus.WithFields(logrus.Fields{
"txHash": approveTx.Hash(),
"approveAmount": approveAmount.String(),
}).Info("approve-tx")
err = task.waitTxOk(approveTx.Hash())
if err != nil {
return err
}
}
// send register tx
err = task.connectionOfSsvAccount.LockAndUpdateTxOpts()
if err != nil {
return fmt.Errorf("LockAndUpdateTxOpts err: %s", err)
}
registerTx, err := task.ssvNetworkContract.RegisterValidator(task.connectionOfSsvAccount.TxOpts(),
val.privateKey.PublicKey().Marshal(), cluster.operatorIds, shareData, needDepositAmount, ssv_network.ISSVNetworkCoreCluster(*cluster.latestCluster))
if err != nil {
task.connectionOfSsvAccount.UnlockTxOpts()
return errors.Wrap(err, "ssvNetworkContract.RegisterValidator failed")
}
task.connectionOfSsvAccount.UnlockTxOpts()
logrus.WithFields(logrus.Fields{
"txHash": registerTx.Hash(),
"registerNonce": task.latestRegistrationNonce,
"operaterIds": cluster.operatorIds,
"pubkey": hex.EncodeToString(val.privateKey.PublicKey().Marshal()),
"ssvDepositAmount": needDepositAmount.String(),
}).Info("onboard-tx")
err = task.waitTxOk(registerTx.Hash())
if err != nil {
return err
}
// check validator status on ssv api
active, err := task.ssvNetworkViewsContract.GetValidator(nil, task.connectionOfSsvAccount.Keypair().CommonAddress(), val.privateKey.PublicKey().Marshal())
if err != nil {
logrus.Errorf("ssvNetworkViewsContract.GetValidator err: %s, will shutdown.", err.Error())
utils.ShutdownRequestChannel <- struct{}{}
return err
}
if !active {
logrus.Errorf("val: %s is inactive, will shutdown.", hex.EncodeToString(val.privateKey.PublicKey().Marshal()))
utils.ShutdownRequestChannel <- struct{}{}
return nil
}
// onboard one validator per cycle
break
}
return nil
}