-
Notifications
You must be signed in to change notification settings - Fork 210
/
handler.go
463 lines (439 loc) · 14.2 KB
/
handler.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
package malfeasance
import (
"context"
"errors"
"fmt"
"slices"
"time"
"github.com/spacemeshos/post/shared"
"github.com/spacemeshos/post/verifying"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/datastore"
"github.com/spacemeshos/go-spacemesh/events"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/malfeasance/wire"
"github.com/spacemeshos/go-spacemesh/p2p"
"github.com/spacemeshos/go-spacemesh/p2p/pubsub"
"github.com/spacemeshos/go-spacemesh/signing"
"github.com/spacemeshos/go-spacemesh/sql"
"github.com/spacemeshos/go-spacemesh/sql/atxs"
"github.com/spacemeshos/go-spacemesh/sql/identities"
)
var (
ErrKnownProof = errors.New("known proof")
errMalformedData = fmt.Errorf("%w: malformed data", pubsub.ErrValidationReject)
errWrongHash = fmt.Errorf("%w: incorrect hash", pubsub.ErrValidationReject)
errInvalidProof = fmt.Errorf("%w: invalid proof", pubsub.ErrValidationReject)
)
// Handler processes MalfeasanceProof from gossip and, if deems it valid, propagates it to peers.
type Handler struct {
logger log.Log
cdb *datastore.CachedDB
self p2p.Peer
nodeIDs []types.NodeID
edVerifier SigVerifier
tortoise tortoise
postVerifier postVerifier
}
func NewHandler(
cdb *datastore.CachedDB,
lg log.Log,
self p2p.Peer,
nodeID []types.NodeID,
edVerifier SigVerifier,
tortoise tortoise,
postVerifier postVerifier,
) *Handler {
return &Handler{
logger: lg,
cdb: cdb,
self: self,
nodeIDs: nodeID,
edVerifier: edVerifier,
tortoise: tortoise,
postVerifier: postVerifier,
}
}
func (h *Handler) reportMalfeasance(smesher types.NodeID, mp *wire.MalfeasanceProof) {
h.tortoise.OnMalfeasance(smesher)
events.ReportMalfeasance(smesher, mp)
if slices.Contains(h.nodeIDs, smesher) {
events.EmitOwnMalfeasanceProof(smesher, mp)
}
}
// HandleSyncedMalfeasanceProof is the sync validator for MalfeasanceProof.
func (h *Handler) HandleSyncedMalfeasanceProof(
ctx context.Context,
expHash types.Hash32,
_ p2p.Peer,
data []byte,
) error {
var p wire.MalfeasanceProof
if err := codec.Decode(data, &p); err != nil {
numMalformed.Inc()
h.logger.With().Error("malformed message (sync)", log.Context(ctx), log.Err(err))
return errMalformedData
}
nodeID, err := h.validateAndSave(ctx, &wire.MalfeasanceGossip{MalfeasanceProof: p})
if err == nil && types.Hash32(nodeID) != expHash {
return fmt.Errorf(
"%w: malfeasance proof want %s, got %s",
errWrongHash,
expHash.ShortString(),
nodeID.ShortString(),
)
}
return err
}
// HandleMalfeasanceProof is the gossip receiver for MalfeasanceGossip.
func (h *Handler) HandleMalfeasanceProof(ctx context.Context, peer p2p.Peer, data []byte) error {
var p wire.MalfeasanceGossip
if err := codec.Decode(data, &p); err != nil {
numMalformed.Inc()
h.logger.With().Error("malformed message", log.Context(ctx), log.Err(err))
return errMalformedData
}
if peer == h.self {
id, err := Validate(ctx, h.logger, h.cdb, h.edVerifier, h.postVerifier, &p)
if err != nil {
return err
}
h.reportMalfeasance(id, &p.MalfeasanceProof)
// node saves malfeasance proof eagerly/atomically with the malicious data.
// it has validated the proof before saving to db.
updateMetrics(p.Proof)
return nil
}
_, err := h.validateAndSave(ctx, &p)
return err
}
func (h *Handler) validateAndSave(ctx context.Context, p *wire.MalfeasanceGossip) (types.NodeID, error) {
if p.Eligibility != nil {
return types.EmptyNodeID, fmt.Errorf(
"%w: eligibility field was deprecated with hare3",
pubsub.ErrValidationReject,
)
}
nodeID, err := Validate(ctx, h.logger, h.cdb, h.edVerifier, h.postVerifier, p)
if err != nil {
return types.EmptyNodeID, err
}
if err := h.cdb.WithTx(ctx, func(dbtx *sql.Tx) error {
malicious, err := identities.IsMalicious(dbtx, nodeID)
if err != nil {
return fmt.Errorf("check known malicious: %w", err)
} else if malicious {
h.logger.WithContext(ctx).With().Debug("known malicious identity", log.Stringer("smesher", nodeID))
return ErrKnownProof
}
encoded, err := codec.Encode(&p.MalfeasanceProof)
if err != nil {
h.logger.With().Panic("failed to encode MalfeasanceProof", log.Err(err))
}
if err := identities.SetMalicious(dbtx, nodeID, encoded, time.Now()); err != nil {
return fmt.Errorf("add malfeasance proof: %w", err)
}
return nil
}); err != nil {
if !errors.Is(err, ErrKnownProof) {
h.logger.WithContext(ctx).With().Error("failed to save MalfeasanceProof",
log.Stringer("smesher", nodeID),
log.Inline(p),
log.Err(err),
)
}
return types.EmptyNodeID, err
}
h.reportMalfeasance(nodeID, &p.MalfeasanceProof)
h.cdb.CacheMalfeasanceProof(nodeID, &p.MalfeasanceProof)
updateMetrics(p.Proof)
h.logger.WithContext(ctx).With().Info("new malfeasance proof",
log.Stringer("smesher", nodeID),
log.Inline(p),
)
return nodeID, nil
}
func Validate(
ctx context.Context,
logger log.Log,
cdb *datastore.CachedDB,
edVerifier SigVerifier,
postVerifier postVerifier,
p *wire.MalfeasanceGossip,
) (types.NodeID, error) {
var (
nodeID types.NodeID
err error
)
switch p.Proof.Type {
case wire.HareEquivocation:
nodeID, err = validateHareEquivocation(ctx, logger, cdb, edVerifier, &p.MalfeasanceProof)
case wire.MultipleATXs:
nodeID, err = validateMultipleATXs(ctx, logger, cdb, edVerifier, &p.MalfeasanceProof)
case wire.MultipleBallots:
nodeID, err = validateMultipleBallots(ctx, logger, cdb, edVerifier, &p.MalfeasanceProof)
case wire.InvalidPostIndex:
proof := p.MalfeasanceProof.Proof.Data.(*wire.InvalidPostIndexProof) // guaranteed to work by scale func
nodeID, err = validateInvalidPostIndex(ctx, logger, cdb, edVerifier, postVerifier, proof)
case wire.InvalidPrevATX:
proof := p.MalfeasanceProof.Proof.Data.(*wire.InvalidPrevATXProof) // guaranteed to work by scale func
nodeID, err = validateInvalidPrevATX(ctx, cdb, edVerifier, proof)
default:
return nodeID, fmt.Errorf("%w: unknown malfeasance type", errInvalidProof)
}
switch {
case err == nil:
return nodeID, nil
case errors.Is(err, ErrKnownProof):
return nodeID, err
}
logger.WithContext(ctx).With().Warning("malfeasance proof failed validation", log.Inline(p), log.Err(err))
return nodeID, fmt.Errorf("%w: %v", errInvalidProof, err)
}
func updateMetrics(tp wire.Proof) {
switch tp.Type {
case wire.HareEquivocation:
numProofsHare.Inc()
case wire.MultipleATXs:
numProofsATX.Inc()
case wire.MultipleBallots:
numProofsBallot.Inc()
case wire.InvalidPostIndex:
numProofsPostIndex.Inc()
case wire.InvalidPrevATX:
numProofsPrevATX.Inc()
}
}
func hasPublishedAtxs(db sql.Executor, nodeID types.NodeID) error {
_, err := atxs.GetLastIDByNodeID(db, nodeID)
if err != nil {
if errors.Is(err, sql.ErrNotFound) {
return errors.New("identity does not exist")
}
return err
}
return nil
}
func validateHareEquivocation(
ctx context.Context,
logger log.Log,
db sql.Executor,
edVerifier SigVerifier,
proof *wire.MalfeasanceProof,
) (types.NodeID, error) {
if proof.Proof.Type != wire.HareEquivocation {
return types.EmptyNodeID, fmt.Errorf(
"wrong malfeasance type. want %v, got %v",
wire.HareEquivocation,
proof.Proof.Type,
)
}
var (
firstNid types.NodeID
firstMsg wire.HareProofMsg
)
hp, ok := proof.Proof.Data.(*wire.HareProof)
if !ok {
return types.EmptyNodeID, errors.New("wrong message type for hare equivocation")
}
for _, msg := range hp.Messages {
if !edVerifier.Verify(signing.HARE, msg.SmesherID, msg.SignedBytes(), msg.Signature) {
return types.EmptyNodeID, errors.New("invalid signature")
}
if firstNid == types.EmptyNodeID {
if err := hasPublishedAtxs(db, msg.SmesherID); err != nil {
return types.EmptyNodeID, fmt.Errorf("check identity in hare malfeasance %v: %w", msg.SmesherID, err)
}
firstNid = msg.SmesherID
firstMsg = msg
} else if msg.SmesherID == firstNid {
if msg.InnerMsg.Layer == firstMsg.InnerMsg.Layer &&
msg.InnerMsg.Round == firstMsg.InnerMsg.Round &&
msg.InnerMsg.MsgHash != firstMsg.InnerMsg.MsgHash {
return msg.SmesherID, nil
}
}
}
logger.With().Warning("received invalid hare malfeasance proof",
log.Context(ctx),
log.Stringer("first_smesher", hp.Messages[0].SmesherID),
log.Object("first_proof", &hp.Messages[0].InnerMsg),
log.Stringer("second_smesher", hp.Messages[1].SmesherID),
log.Object("second_proof", &hp.Messages[1].InnerMsg),
)
numInvalidProofsHare.Inc()
return types.EmptyNodeID, errors.New("invalid hare malfeasance proof")
}
func validateMultipleATXs(
ctx context.Context,
logger log.Log,
db sql.Executor,
edVerifier SigVerifier,
proof *wire.MalfeasanceProof,
) (types.NodeID, error) {
if proof.Proof.Type != wire.MultipleATXs {
return types.EmptyNodeID, fmt.Errorf(
"wrong malfeasance type. want %v, got %v",
wire.MultipleATXs,
proof.Proof.Type,
)
}
var (
firstNid types.NodeID
firstMsg wire.AtxProofMsg
)
ap, ok := proof.Proof.Data.(*wire.AtxProof)
if !ok {
return types.EmptyNodeID, errors.New("wrong message type for multiple ATXs")
}
for _, msg := range ap.Messages {
if !edVerifier.Verify(signing.ATX, msg.SmesherID, msg.SignedBytes(), msg.Signature) {
return types.EmptyNodeID, errors.New("invalid signature")
}
if firstNid == types.EmptyNodeID {
if err := hasPublishedAtxs(db, msg.SmesherID); err != nil {
return types.EmptyNodeID, fmt.Errorf("check identity in atx malfeasance %v: %w", msg.SmesherID, err)
}
firstNid = msg.SmesherID
firstMsg = msg
} else if msg.SmesherID == firstNid {
if msg.InnerMsg.PublishEpoch == firstMsg.InnerMsg.PublishEpoch &&
msg.InnerMsg.MsgHash != firstMsg.InnerMsg.MsgHash {
return msg.SmesherID, nil
}
}
}
logger.With().Warning("received invalid atx malfeasance proof",
log.Context(ctx),
log.Stringer("first_smesher", ap.Messages[0].SmesherID),
log.Object("first_proof", &ap.Messages[0].InnerMsg),
log.Stringer("second_smesher", ap.Messages[1].SmesherID),
log.Object("second_proof", &ap.Messages[1].InnerMsg),
)
numInvalidProofsATX.Inc()
return types.EmptyNodeID, errors.New("invalid atx malfeasance proof")
}
func validateMultipleBallots(
ctx context.Context,
logger log.Log,
db sql.Executor,
edVerifier SigVerifier,
proof *wire.MalfeasanceProof,
) (types.NodeID, error) {
if proof.Proof.Type != wire.MultipleBallots {
return types.EmptyNodeID, fmt.Errorf(
"wrong malfeasance type. want %v, got %v",
wire.MultipleBallots,
proof.Proof.Type,
)
}
var (
firstNid types.NodeID
firstMsg wire.BallotProofMsg
err error
)
bp, ok := proof.Proof.Data.(*wire.BallotProof)
if !ok {
return types.EmptyNodeID, errors.New("wrong message type for multi ballots")
}
for _, msg := range bp.Messages {
if !edVerifier.Verify(signing.BALLOT, msg.SmesherID, msg.SignedBytes(), msg.Signature) {
return types.EmptyNodeID, errors.New("invalid signature")
}
if firstNid == types.EmptyNodeID {
if err = hasPublishedAtxs(db, msg.SmesherID); err != nil {
return types.EmptyNodeID, fmt.Errorf("check identity in ballot malfeasance %v: %w", msg.SmesherID, err)
}
firstNid = msg.SmesherID
firstMsg = msg
} else if msg.SmesherID == firstNid {
if msg.InnerMsg.Layer == firstMsg.InnerMsg.Layer &&
msg.InnerMsg.MsgHash != firstMsg.InnerMsg.MsgHash {
return msg.SmesherID, nil
}
}
}
logger.With().Warning("received invalid ballot malfeasance proof",
log.Context(ctx),
log.Stringer("first_smesher", bp.Messages[0].SmesherID),
log.Object("first_proof", &bp.Messages[0].InnerMsg),
log.Stringer("second_smesher", bp.Messages[1].SmesherID),
log.Object("second_proof", &bp.Messages[1].InnerMsg),
)
numInvalidProofsBallot.Inc()
return types.EmptyNodeID, errors.New("invalid ballot malfeasance proof")
}
func validateInvalidPostIndex(
ctx context.Context,
logger log.Log,
db sql.Executor,
edVerifier SigVerifier,
postVerifier postVerifier,
proof *wire.InvalidPostIndexProof,
) (types.NodeID, error) {
atx := &proof.Atx
if err := hasPublishedAtxs(db, atx.SmesherID); err != nil {
return types.EmptyNodeID, fmt.Errorf("check identity %v in invalid post index: %w", atx.SmesherID, err)
}
if !edVerifier.Verify(signing.ATX, atx.SmesherID, atx.SignedBytes(), atx.Signature) {
return types.EmptyNodeID, errors.New("invalid signature")
}
commitmentAtx := atx.CommitmentATX
if commitmentAtx == nil {
atx, err := atxs.CommitmentATX(db, atx.SmesherID)
if err != nil {
return types.EmptyNodeID, fmt.Errorf("getting commitment ATX: %w", err)
}
commitmentAtx = &atx
}
post := (*shared.Proof)(atx.NIPost.Post)
meta := &shared.ProofMetadata{
NodeId: atx.SmesherID[:],
CommitmentAtxId: commitmentAtx[:],
NumUnits: atx.NumUnits,
Challenge: atx.NIPost.PostMetadata.Challenge,
LabelsPerUnit: atx.NIPost.PostMetadata.LabelsPerUnit,
}
if err := postVerifier.Verify(
ctx,
post,
meta,
verifying.SelectedIndex(int(proof.InvalidIdx)),
); err != nil {
return atx.SmesherID, nil
}
numInvalidProofsPostIndex.Inc()
return types.EmptyNodeID, errors.New("invalid post index malfeasance proof - POST is valid")
}
func validateInvalidPrevATX(
ctx context.Context,
db sql.Executor,
edVerifier SigVerifier,
proof *wire.InvalidPrevATXProof,
) (types.NodeID, error) {
atx1 := proof.Atx1
if err := hasPublishedAtxs(db, atx1.SmesherID); err != nil {
return types.EmptyNodeID, fmt.Errorf("check identity %v in invalid previous ATX: %w", atx1.SmesherID, err)
}
if !edVerifier.Verify(signing.ATX, atx1.SmesherID, atx1.SignedBytes(), atx1.Signature) {
return types.EmptyNodeID, errors.New("atx1: invalid signature")
}
atx2 := proof.Atx2
if atx1.SmesherID != atx2.SmesherID {
numInvalidProofsPrevATX.Inc()
return types.EmptyNodeID, errors.New("invalid old prev ATX malfeasance proof: smesher IDs are different")
}
if !edVerifier.Verify(signing.ATX, atx2.SmesherID, atx2.SignedBytes(), atx2.Signature) {
return types.EmptyNodeID, errors.New("atx2: invalid signature")
}
if atx1.ID() == atx2.ID() {
numInvalidProofsPrevATX.Inc()
return types.EmptyNodeID, errors.New("invalid old prev ATX malfeasance proof: ATX IDs are the same")
}
if atx1.PrevATXID != atx2.PrevATXID {
numInvalidProofsPrevATX.Inc()
return types.EmptyNodeID, errors.New("invalid old prev ATX malfeasance proof: prev ATX IDs are different")
}
return atx1.SmesherID, nil
}