-
Notifications
You must be signed in to change notification settings - Fork 19
/
topology_eth_key_rotate.go
317 lines (258 loc) · 9.48 KB
/
topology_eth_key_rotate.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package validators
import (
"context"
"encoding/hex"
"errors"
"fmt"
"sort"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/nodewallets/eth/clef"
"code.vegaprotocol.io/vega/logging"
commandspb "code.vegaprotocol.io/vega/protos/vega/commands/v1"
"github.com/ethereum/go-ethereum/crypto"
)
var (
ErrCurrentEthAddressDoesNotMatch = errors.New("current Ethereum address does not match")
ErrCannotRotateToSameKey = errors.New("new Ethereum address cannot be the same as the previous Ethereum address")
ErrNodeHasUnresolvedRotation = errors.New("ethereum keys from a previous rotation have not been resolved on the multisig control contract")
)
type PendingEthereumKeyRotation struct {
NodeID string
NewAddress string
OldAddress string
SubmitterAddress string
}
type pendingEthereumKeyRotationMapping map[uint64][]PendingEthereumKeyRotation
func (pm pendingEthereumKeyRotationMapping) add(height uint64, rotation PendingEthereumKeyRotation) {
if _, ok := pm[height]; !ok {
pm[height] = []PendingEthereumKeyRotation{}
}
pm[height] = append(pm[height], rotation)
}
func (pm pendingEthereumKeyRotationMapping) get(height uint64) []PendingEthereumKeyRotation {
rotations, ok := pm[height]
if !ok {
return []PendingEthereumKeyRotation{}
}
sort.Slice(rotations, func(i, j int) bool { return rotations[i].NodeID < rotations[j].NodeID })
return rotations
}
func (t *Topology) hasPendingEthKeyRotation(nodeID string) bool {
for _, rotations := range t.pendingEthKeyRotations {
for _, r := range rotations {
if r.NodeID == nodeID {
return true
}
}
}
return false
}
func (t *Topology) ProcessEthereumKeyRotation(
ctx context.Context,
publicKey string,
kr *commandspb.EthereumKeyRotateSubmission,
verify func(message, signature []byte, hexAddress string) error,
) error {
t.mu.Lock()
defer t.mu.Unlock()
t.log.Debug("Received ethereum key rotation",
logging.String("vega-pub-key", publicKey),
logging.String("newAddress", kr.NewAddress),
logging.Uint64("currentBlockHeight", t.currentBlockHeight),
logging.Uint64("targetBlock", kr.TargetBlock),
)
var node *valState
for _, v := range t.validators {
if v.data.VegaPubKey == publicKey {
node = v
break
}
}
if node == nil {
err := fmt.Errorf("failed to rotate ethereum key for non existing validator %q", publicKey)
t.log.Debug("Failed to add Eth key rotation", logging.Error(err))
return err
}
if err := t.validateRotation(kr, node.data, verify); err != nil {
return err
}
// schedule the key rotation to a future block
t.pendingEthKeyRotations.add(kr.TargetBlock,
PendingEthereumKeyRotation{
NodeID: node.data.ID,
NewAddress: kr.NewAddress,
OldAddress: kr.CurrentAddress,
SubmitterAddress: kr.SubmitterAddress,
})
t.log.Debug("Successfully added Ethereum key rotation to pending key rotations",
logging.String("vega-pub-key", publicKey),
logging.Uint64("currentBlockHeight", t.currentBlockHeight),
logging.Uint64("targetBlock", kr.TargetBlock),
logging.String("newAddress", kr.NewAddress),
)
if node.status != ValidatorStatusTendermint {
return nil
}
toRemove := []NodeIDAddress{{NodeID: node.data.ID, EthAddress: node.data.EthereumAddress}}
t.signatures.PrepareValidatorSignatures(ctx, toRemove, t.epochSeq, false)
if len(kr.SubmitterAddress) != 0 {
// we were given an address that will be submitting the multisig changes, we can emit a remove signature for it right now
t.signatures.EmitValidatorRemovedSignatures(ctx, kr.SubmitterAddress, node.data.ID, t.timeService.GetTimeNow())
}
return nil
}
func (t *Topology) GetPendingEthereumKeyRotation(blockHeight uint64, nodeID string) *PendingEthereumKeyRotation {
t.mu.RLock()
defer t.mu.RUnlock()
rotations, ok := t.pendingEthKeyRotations[blockHeight]
if !ok {
return nil
}
for _, r := range rotations {
if r.NodeID == nodeID {
return &PendingEthereumKeyRotation{
NodeID: r.NodeID,
NewAddress: r.NewAddress,
}
}
}
return nil
}
func (t *Topology) ethereumKeyRotationBeginBlockLocked(ctx context.Context) {
// check any unfinalised key rotations
remove := []string{}
for _, r := range t.unresolvedEthKeyRotations {
if !t.multiSigTopology.IsSigner(r.OldAddress) && t.multiSigTopology.IsSigner(r.NewAddress) {
t.log.Info("ethereum key rotations have been resolved on the multisig contract", logging.String("nodeID", r.NodeID), logging.String("old-address", r.OldAddress))
remove = append(remove, r.NodeID)
}
}
for _, nodeID := range remove {
delete(t.unresolvedEthKeyRotations, nodeID)
}
// key swaps should run in deterministic order
rotations := t.pendingEthKeyRotations.get(t.currentBlockHeight)
if len(rotations) == 0 {
return
}
t.log.Debug("Applying ethereum key-rotations", logging.Uint64("currentBlockHeight", t.currentBlockHeight), logging.Int("n-rotations", len(rotations)))
for _, r := range rotations {
t.log.Debug("Applying Ethereum key rotation",
logging.String("nodeID", r.NodeID),
logging.String("newAddress", r.NewAddress),
)
data, ok := t.validators[r.NodeID]
if !ok {
// this should actually happen if validator was removed due to poor performance
t.log.Error("failed to rotate Ethereum key due to non present validator", logging.String("nodeID", r.NodeID), logging.String("EthereumAddress", r.NewAddress))
continue
}
oldAddress := data.data.EthereumAddress
data.data.EthereumAddress = r.NewAddress
t.validators[r.NodeID] = data
t.broker.Send(events.NewEthereumKeyRotationEvent(
ctx,
r.NodeID,
oldAddress,
r.NewAddress,
t.currentBlockHeight,
))
t.log.Debug("Applied Ethereum key rotation",
logging.String("nodeID", r.NodeID),
logging.String("oldAddress", oldAddress),
logging.String("newAddress", r.NewAddress),
)
if data.status != ValidatorStatusTendermint {
continue
}
toAdd := []NodeIDAddress{{NodeID: r.NodeID, EthAddress: r.NewAddress}}
t.signatures.PrepareValidatorSignatures(ctx, toAdd, t.epochSeq, true)
if len(r.SubmitterAddress) != 0 {
// we were given an address that will be submitting the multisig changes, we can emit signatures for it right now
t.signatures.EmitValidatorAddedSignatures(ctx, r.SubmitterAddress, r.NodeID, t.timeService.GetTimeNow())
}
// add to unfinalised map so we can wait to see the changes on the contract
t.unresolvedEthKeyRotations[data.data.ID] = r
}
delete(t.pendingEthKeyRotations, t.currentBlockHeight)
}
func (t *Topology) validateRotation(kr *commandspb.EthereumKeyRotateSubmission, data ValidatorData, verify func(message, signature []byte, hexAddress string) error) error {
if t.hasPendingEthKeyRotation(data.ID) {
return ErrNodeAlreadyHasPendingKeyRotation
}
if _, ok := t.unresolvedEthKeyRotations[data.ID]; ok {
return ErrNodeHasUnresolvedRotation
}
if t.currentBlockHeight >= kr.TargetBlock {
t.log.Debug("target block height is not above current block height", logging.Uint64("target", kr.TargetBlock), logging.Uint64("current", t.currentBlockHeight))
return ErrTargetBlockHeightMustBeGreaterThanCurrentHeight
}
if data.EthereumAddress != kr.CurrentAddress {
t.log.Debug("current addresses do not match", logging.String("current", data.EthereumAddress), logging.String("submitted", kr.CurrentAddress))
return ErrCurrentEthAddressDoesNotMatch
}
if data.EthereumAddress == kr.NewAddress {
t.log.Debug("trying to rotate to the same key", logging.String("current", data.EthereumAddress), logging.String("new-address", kr.NewAddress))
return ErrCannotRotateToSameKey
}
if err := VerifyEthereumKeyRotation(kr, verify); err != nil {
return err
}
return nil
}
func SignEthereumKeyRotation(
kr *commandspb.EthereumKeyRotateSubmission,
ethSigner Signer,
) error {
buf, err := makeEthKeyRotationSignableMessage(kr)
if err != nil {
return err
}
if ethSigner.Algo() != clef.ClefAlgoType {
buf = crypto.Keccak256(buf)
}
ethereumSignature, err := ethSigner.Sign(buf)
if err != nil {
return err
}
kr.EthereumSignature = &commandspb.Signature{
Value: hex.EncodeToString(ethereumSignature),
Algo: ethSigner.Algo(),
}
return nil
}
func VerifyEthereumKeyRotation(kr *commandspb.EthereumKeyRotateSubmission, verify func(message, signature []byte, hexAddress string) error) error {
buf, err := makeEthKeyRotationSignableMessage(kr)
if err != nil {
return err
}
eths, err := hex.DecodeString(kr.GetEthereumSignature().Value)
if err != nil {
return err
}
if err := verify(buf, eths, kr.NewAddress); err != nil {
return err
}
return nil
}
func makeEthKeyRotationSignableMessage(kr *commandspb.EthereumKeyRotateSubmission) ([]byte, error) {
if len(kr.CurrentAddress) <= 0 || len(kr.NewAddress) <= 0 || kr.TargetBlock == 0 {
return nil, ErrMissingRequiredAnnounceNodeFields
}
msg := kr.CurrentAddress + kr.NewAddress + fmt.Sprintf("%d", kr.TargetBlock)
return []byte(msg), nil
}