/
priv_validator.go
446 lines (381 loc) · 13.2 KB
/
priv_validator.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//go:generate ../scripts/mockery_generate.sh PrivValidator
package types
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"strconv"
"github.com/hellarcore/hellard-go/btcjson"
sync "github.com/sasha-s/go-deadlock"
"github.com/hellarcore/tenderhellar/crypto"
"github.com/hellarcore/tenderhellar/crypto/bls12381"
tmbytes "github.com/hellarcore/tenderhellar/libs/bytes"
"github.com/hellarcore/tenderhellar/libs/log"
tmproto "github.com/hellarcore/tenderhellar/proto/tendermint/types"
)
// PrivValidatorType defines the implementation types.
type PrivValidatorType uint8
const (
MockSignerClient = PrivValidatorType(0x00) // mock signer
FileSignerClient = PrivValidatorType(0x01) // signer client via file
RetrySignerClient = PrivValidatorType(0x02) // signer client with retry via socket
SignerSocketClient = PrivValidatorType(0x03) // signer client via socket
ErrorMockSignerClient = PrivValidatorType(0x04) // error mock signer
SignerGRPCClient = PrivValidatorType(0x05) // signer client via gRPC
HellarCoreRPCClient = PrivValidatorType(0x06) // signer client via gRPC
)
// PrivValidator defines the functionality of a local Tendermint validator
// that signs votes and proposals, and never double signs.
type PrivValidator interface {
GetPubKey(ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PubKey, error)
UpdatePrivateKey(
ctx context.Context,
privateKey crypto.PrivKey,
quorumHash crypto.QuorumHash,
thresholdPublicKey crypto.PubKey,
height int64,
)
GetProTxHash(context.Context) (crypto.ProTxHash, error)
GetFirstQuorumHash(context.Context) (crypto.QuorumHash, error)
GetPrivateKey(ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PrivKey, error)
GetThresholdPublicKey(ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PubKey, error)
GetHeight(ctx context.Context, quorumHash crypto.QuorumHash) (int64, error)
SignVote(
ctx context.Context, chainID string, quorumType btcjson.LLMQType, quorumHash crypto.QuorumHash,
vote *tmproto.Vote, logger log.Logger) error
SignProposal(
ctx context.Context, chainID string, quorumType btcjson.LLMQType, quorumHash crypto.QuorumHash,
proposal *tmproto.Proposal) (tmbytes.HexBytes, error)
ExtractIntoValidator(ctx context.Context, quorumHash crypto.QuorumHash) *Validator
}
type PrivValidatorsByProTxHash []PrivValidator
func (pvs PrivValidatorsByProTxHash) Len() int {
return len(pvs)
}
func (pvs PrivValidatorsByProTxHash) Less(i, j int) bool {
pvi, err := pvs[i].GetProTxHash(context.Background())
if err != nil {
panic(err)
}
pvj, err := pvs[j].GetProTxHash(context.Background())
if err != nil {
panic(err)
}
return bytes.Compare(pvi, pvj) == -1
}
func (pvs PrivValidatorsByProTxHash) Swap(i, j int) {
pvs[i], pvs[j] = pvs[j], pvs[i]
}
//----------------------------------------
// MockPV
// MockPV implements PrivValidator without any safety or persistence.
// Only use it for testing.
type MockPV struct {
PrivateKeys map[string]crypto.QuorumKeys
// heightString -> quorumHash
UpdateHeights map[string]crypto.QuorumHash
// quorumHash -> heightString
FirstHeightOfQuorums map[string]string
ProTxHash crypto.ProTxHash
mtx sync.RWMutex
breakProposalSigning bool
breakVoteSigning bool
}
// GenKeysForQuorumHash generates the quorum keys for passed quorum hash
func GenKeysForQuorumHash(quorumHash crypto.QuorumHash) func(pv *MockPV) {
return func(pv *MockPV) {
pv.PrivateKeys[quorumHash.String()] = generateQuorumKeys()
}
}
// UseProTxHash sets pro-tx-hash to a private-validator
func UseProTxHash(proTxHash ProTxHash) func(pv *MockPV) {
return func(pv *MockPV) {
pv.ProTxHash = proTxHash
}
}
func generateQuorumKeys() crypto.QuorumKeys {
privKey := bls12381.GenPrivKey()
return crypto.QuorumKeys{
PrivKey: privKey,
PubKey: privKey.PubKey(),
ThresholdPublicKey: privKey.PubKey(),
}
}
func NewMockPV(opts ...func(pv *MockPV)) *MockPV {
pv := &MockPV{
PrivateKeys: make(map[string]crypto.QuorumKeys),
UpdateHeights: make(map[string]crypto.QuorumHash),
FirstHeightOfQuorums: make(map[string]string),
ProTxHash: crypto.RandProTxHash(),
breakProposalSigning: false,
breakVoteSigning: false,
}
for _, opt := range opts {
opt(pv)
}
if len(pv.PrivateKeys) == 0 {
quorumHash := crypto.RandQuorumHash()
pv.PrivateKeys[quorumHash.String()] = generateQuorumKeys()
}
return pv
}
func NewMockPVForQuorum(quorumHash crypto.QuorumHash) *MockPV {
return NewMockPV(GenKeysForQuorumHash(quorumHash))
}
// NewMockPVWithParams allows one to create a MockPV instance, but with finer
// grained control over the operation of the mock validator. This is useful for
// mocking test failures.
func NewMockPVWithParams(
privKey crypto.PrivKey,
proTxHash crypto.ProTxHash,
quorumHash crypto.QuorumHash,
thresholdPublicKey crypto.PubKey,
breakProposalSigning bool,
breakVoteSigning bool,
) *MockPV {
quorumKeys := crypto.QuorumKeys{
PrivKey: privKey,
PubKey: privKey.PubKey(),
ThresholdPublicKey: thresholdPublicKey,
}
privateKeysMap := make(map[string]crypto.QuorumKeys)
privateKeysMap[quorumHash.String()] = quorumKeys
updateHeightsMap := make(map[string]crypto.QuorumHash)
firstHeightOfQuorumsMap := make(map[string]string)
return &MockPV{
PrivateKeys: privateKeysMap,
UpdateHeights: updateHeightsMap,
FirstHeightOfQuorums: firstHeightOfQuorumsMap,
ProTxHash: proTxHash,
breakProposalSigning: breakProposalSigning,
breakVoteSigning: breakVoteSigning,
}
}
// GetPubKey implements PrivValidator.
func (pv *MockPV) GetPubKey(_ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PubKey, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
if keys, ok := pv.PrivateKeys[quorumHash.String()]; ok {
return keys.PubKey, nil
}
return nil, fmt.Errorf("mockPV: no public key for quorum hash %v", quorumHash)
}
// GetProTxHash implements PrivValidator.
func (pv *MockPV) GetProTxHash(_ctx context.Context) (crypto.ProTxHash, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
if len(pv.ProTxHash) != crypto.ProTxHashSize {
return nil, fmt.Errorf("mock proTxHash is invalid size")
}
return pv.ProTxHash, nil
}
func (pv *MockPV) GetFirstQuorumHash(_ctx context.Context) (crypto.QuorumHash, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
for quorumHashString := range pv.PrivateKeys {
return hex.DecodeString(quorumHashString)
}
return nil, nil
}
// GetThresholdPublicKey ...
func (pv *MockPV) GetThresholdPublicKey(_ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PubKey, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
return pv.PrivateKeys[quorumHash.String()].ThresholdPublicKey, nil
}
// GetPrivateKey ...
func (pv *MockPV) GetPrivateKey(_ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PrivKey, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
return pv.PrivateKeys[quorumHash.String()].PrivKey, nil
}
func (pv *MockPV) getPrivateKey(quorumHash crypto.QuorumHash) crypto.PrivKey {
return pv.PrivateKeys[quorumHash.String()].PrivKey
}
// ThresholdPublicKeyForQuorumHash ...
func (pv *MockPV) ThresholdPublicKeyForQuorumHash(_ctx context.Context, quorumHash crypto.QuorumHash) (crypto.PubKey, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
return pv.PrivateKeys[quorumHash.String()].ThresholdPublicKey, nil
}
// GetHeight ...
func (pv *MockPV) GetHeight(_ctx context.Context, quorumHash crypto.QuorumHash) (int64, error) {
pv.mtx.RLock()
defer pv.mtx.RUnlock()
if intString, ok := pv.FirstHeightOfQuorums[quorumHash.String()]; ok {
return strconv.ParseInt(intString, 10, 64)
}
return -1, fmt.Errorf("quorum hash not found for GetHeight %v", quorumHash.String())
}
// SignVote implements PrivValidator.
func (pv *MockPV) SignVote(
_ctx context.Context,
chainID string,
quorumType btcjson.LLMQType,
quorumHash crypto.QuorumHash,
vote *tmproto.Vote,
_logger log.Logger) error {
pv.mtx.Lock()
defer pv.mtx.Unlock()
useChainID := chainID
if pv.breakVoteSigning {
useChainID = "incorrect-chain-id"
}
blockSignID := VoteBlockSignID(useChainID, vote, quorumType, quorumHash)
privKey := pv.getPrivateKey(quorumHash)
blockSignature, err := privKey.SignDigest(blockSignID)
// fmt.Printf("validator %X signing vote of type %d at height %d with key %X blockSignBytes %X stateSignBytes %X\n",
// pv.ProTxHash, vote.Type, vote.Height, pv.PrivKey.PubKey().Bytes(), blockSignBytes, stateSignBytes)
// fmt.Printf("block sign bytes are %X by %X using key %X resulting in sig %X\n", blockSignBytes, pv.ProTxHash,
// pv.PrivKey.PubKey().Bytes(), blockSignature)
if err != nil {
return err
}
vote.BlockSignature = blockSignature
// We only sign vote extensions for precommits
if vote.Type != tmproto.PrecommitType {
if len(vote.VoteExtensions) > 0 {
return errors.New("unexpected vote extension - vote extensions are only allowed in precommits")
}
return nil
}
extensions := VoteExtensionsFromProto(vote.VoteExtensions...)
signItems, err := extensions.SignItems(useChainID, quorumType, quorumHash, vote.Height, vote.Round)
if err != nil {
return err
}
for i, sign := range signItems {
sig, err := privKey.SignDigest(sign.SignHash)
if err != nil {
return err
}
vote.VoteExtensions[i].Signature = sig
}
return nil
}
// SignProposal Implements PrivValidator.
func (pv *MockPV) SignProposal(
_ctx context.Context,
chainID string,
quorumType btcjson.LLMQType,
quorumHash crypto.QuorumHash,
proposal *tmproto.Proposal,
) (tmbytes.HexBytes, error) {
pv.mtx.Lock()
defer pv.mtx.Unlock()
if pv.breakProposalSigning {
chainID = "incorrect-chain-id"
}
signID := ProposalBlockSignID(chainID, proposal, quorumType, quorumHash)
quorumKeys, ok := pv.PrivateKeys[quorumHash.String()]
if !ok {
return signID, fmt.Errorf("file private validator could not sign vote for quorum hash %v", quorumHash)
}
sig, err := quorumKeys.PrivKey.SignDigest(signID)
if err != nil {
return nil, err
}
proposal.Signature = sig
return signID, nil
}
func (pv *MockPV) UpdatePrivateKey(
_ctx context.Context,
privateKey crypto.PrivKey,
quorumHash crypto.QuorumHash,
thresholdPublicKey crypto.PubKey,
height int64,
) {
// fmt.Printf("mockpv node %X setting a new key %X at height %d\n", pv.ProTxHash,
// privateKey.PubKey().Bytes(), height)
pv.mtx.Lock()
defer pv.mtx.Unlock()
pv.PrivateKeys[quorumHash.String()] = crypto.QuorumKeys{
PrivKey: privateKey,
PubKey: privateKey.PubKey(),
ThresholdPublicKey: thresholdPublicKey,
}
pv.UpdateHeights[strconv.Itoa(int(height))] = quorumHash
if _, ok := pv.FirstHeightOfQuorums[quorumHash.String()]; !ok {
pv.FirstHeightOfQuorums[quorumHash.String()] = strconv.Itoa(int(height))
}
}
func (pv *MockPV) ExtractIntoValidator(ctx context.Context, quorumHash crypto.QuorumHash) *Validator {
pubKey, _ := pv.GetPubKey(ctx, quorumHash)
if len(pv.ProTxHash) != crypto.DefaultHashSize {
panic("proTxHash wrong length")
}
return &Validator{
PubKey: pubKey,
VotingPower: DefaultHellarVotingPower,
ProTxHash: pv.ProTxHash,
}
}
// String returns a string representation of the MockPV.
func (pv *MockPV) String() string {
proTxHash, _ := pv.GetProTxHash(context.TODO()) // mockPV will never return an error, ignored here
return fmt.Sprintf("MockPV{%v}", proTxHash)
}
// XXX: Implement.
func (pv *MockPV) DisableChecks() {
// Currently this does nothing,
// as MockPV has no safety checks at all.
}
type ErroringMockPV struct {
MockPV
}
var ErroringMockPVErr = errors.New("erroringMockPV always returns an error")
// GetPubKey Implements PrivValidator.
func (pv *ErroringMockPV) GetPubKey(_ctx context.Context, _quorumHash crypto.QuorumHash) (crypto.PubKey, error) {
return nil, ErroringMockPVErr
}
// SignVote Implements PrivValidator.
func (pv *ErroringMockPV) SignVote(
_ctx context.Context, _chainID string, _quorumType btcjson.LLMQType, _quorumHash crypto.QuorumHash,
_vote *tmproto.Vote, _logger log.Logger) error {
return ErroringMockPVErr
}
// SignProposal Implements PrivValidator.
func (pv *ErroringMockPV) SignProposal(
_ctx context.Context, _chainID string,
_quorumType btcjson.LLMQType,
_quorumHash crypto.QuorumHash,
_proposal *tmproto.Proposal,
) (tmbytes.HexBytes, error) {
return nil, ErroringMockPVErr
}
// NewErroringMockPV returns a MockPV that fails on each signing request. Again, for testing only.
func NewErroringMockPV() *ErroringMockPV {
privKey := bls12381.GenPrivKey()
quorumHash := crypto.RandQuorumHash()
quorumKeys := crypto.QuorumKeys{
PrivKey: privKey,
PubKey: privKey.PubKey(),
ThresholdPublicKey: privKey.PubKey(),
}
privateKeysMap := make(map[string]crypto.QuorumKeys)
privateKeysMap[quorumHash.String()] = quorumKeys
return &ErroringMockPV{
MockPV{
PrivateKeys: privateKeysMap,
UpdateHeights: nil,
FirstHeightOfQuorums: nil,
ProTxHash: crypto.RandProTxHash(),
breakProposalSigning: false,
breakVoteSigning: false,
},
}
}
type MockPrivValidatorsByProTxHash []*MockPV
func (pvs MockPrivValidatorsByProTxHash) Len() int {
return len(pvs)
}
func (pvs MockPrivValidatorsByProTxHash) Less(i, j int) bool {
pvi := pvs[i].ProTxHash
pvj := pvs[j].ProTxHash
return bytes.Compare(pvi, pvj) == -1
}
func (pvs MockPrivValidatorsByProTxHash) Swap(i, j int) {
pvs[i], pvs[j] = pvs[j], pvs[i]
}