-
Notifications
You must be signed in to change notification settings - Fork 0
/
extensions.go
618 lines (527 loc) · 18.3 KB
/
extensions.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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package gossip
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/common/util"
"github.com/hyperledger/fabric/gossip/api"
"github.com/hyperledger/fabric/gossip/common"
)
// NewGossipMessageComparator creates a MessageReplacingPolicy given a maximum number of blocks to hold
func NewGossipMessageComparator(dataBlockStorageSize int) common.MessageReplacingPolicy {
return (&msgComparator{dataBlockStorageSize: dataBlockStorageSize}).getMsgReplacingPolicy()
}
type msgComparator struct {
dataBlockStorageSize int
}
func (mc *msgComparator) getMsgReplacingPolicy() common.MessageReplacingPolicy {
return func(this interface{}, that interface{}) common.InvalidationResult {
return mc.invalidationPolicy(this, that)
}
}
func (mc *msgComparator) invalidationPolicy(this interface{}, that interface{}) common.InvalidationResult {
thisMsg := this.(*SignedGossipMessage)
thatMsg := that.(*SignedGossipMessage)
if thisMsg.IsAliveMsg() && thatMsg.IsAliveMsg() {
return aliveInvalidationPolicy(thisMsg.GetAliveMsg(), thatMsg.GetAliveMsg())
}
if thisMsg.IsDataMsg() && thatMsg.IsDataMsg() {
return mc.dataInvalidationPolicy(thisMsg.GetDataMsg(), thatMsg.GetDataMsg())
}
if thisMsg.IsStateInfoMsg() && thatMsg.IsStateInfoMsg() {
return mc.stateInvalidationPolicy(thisMsg.GetStateInfo(), thatMsg.GetStateInfo())
}
if thisMsg.IsIdentityMsg() && thatMsg.IsIdentityMsg() {
return mc.identityInvalidationPolicy(thisMsg.GetPeerIdentity(), thatMsg.GetPeerIdentity())
}
if thisMsg.IsLeadershipMsg() && thatMsg.IsLeadershipMsg() {
return leaderInvalidationPolicy(thisMsg.GetLeadershipMsg(), thatMsg.GetLeadershipMsg())
}
return common.MessageNoAction
}
func (mc *msgComparator) stateInvalidationPolicy(thisStateMsg *StateInfo, thatStateMsg *StateInfo) common.InvalidationResult {
if !bytes.Equal(thisStateMsg.PkiId, thatStateMsg.PkiId) {
return common.MessageNoAction
}
return compareTimestamps(thisStateMsg.Timestamp, thatStateMsg.Timestamp)
}
func (mc *msgComparator) identityInvalidationPolicy(thisIdentityMsg *PeerIdentity, thatIdentityMsg *PeerIdentity) common.InvalidationResult {
if bytes.Equal(thisIdentityMsg.PkiId, thatIdentityMsg.PkiId) {
return common.MessageInvalidated
}
return common.MessageNoAction
}
func (mc *msgComparator) dataInvalidationPolicy(thisDataMsg *DataMessage, thatDataMsg *DataMessage) common.InvalidationResult {
if thisDataMsg.Payload.SeqNum == thatDataMsg.Payload.SeqNum {
return common.MessageInvalidated
}
diff := abs(thisDataMsg.Payload.SeqNum, thatDataMsg.Payload.SeqNum)
if diff <= uint64(mc.dataBlockStorageSize) {
return common.MessageNoAction
}
if thisDataMsg.Payload.SeqNum > thatDataMsg.Payload.SeqNum {
return common.MessageInvalidates
}
return common.MessageInvalidated
}
func aliveInvalidationPolicy(thisMsg *AliveMessage, thatMsg *AliveMessage) common.InvalidationResult {
if !bytes.Equal(thisMsg.Membership.PkiId, thatMsg.Membership.PkiId) {
return common.MessageNoAction
}
return compareTimestamps(thisMsg.Timestamp, thatMsg.Timestamp)
}
func leaderInvalidationPolicy(thisMsg *LeadershipMessage, thatMsg *LeadershipMessage) common.InvalidationResult {
if !bytes.Equal(thisMsg.PkiId, thatMsg.PkiId) {
return common.MessageNoAction
}
return compareTimestamps(thisMsg.Timestamp, thatMsg.Timestamp)
}
func compareTimestamps(thisTS *PeerTime, thatTS *PeerTime) common.InvalidationResult {
if thisTS.IncNum == thatTS.IncNum {
if thisTS.SeqNum > thatTS.SeqNum {
return common.MessageInvalidates
}
return common.MessageInvalidated
}
if thisTS.IncNum < thatTS.IncNum {
return common.MessageInvalidated
}
return common.MessageInvalidates
}
// IsAliveMsg returns whether this GossipMessage is an AliveMessage
func (m *GossipMessage) IsAliveMsg() bool {
return m.GetAliveMsg() != nil
}
// IsDataMsg returns whether this GossipMessage is a data message
func (m *GossipMessage) IsDataMsg() bool {
return m.GetDataMsg() != nil
}
// IsStateInfoPullRequestMsg returns whether this GossipMessage is a stateInfoPullRequest
func (m *GossipMessage) IsStateInfoPullRequestMsg() bool {
return m.GetStateInfoPullReq() != nil
}
// IsStateInfoSnapshot returns whether this GossipMessage is a stateInfo snapshot
func (m *GossipMessage) IsStateInfoSnapshot() bool {
return m.GetStateSnapshot() != nil
}
// IsStateInfoMsg returns whether this GossipMessage is a stateInfo message
func (m *GossipMessage) IsStateInfoMsg() bool {
return m.GetStateInfo() != nil
}
// IsPullMsg returns whether this GossipMessage is a message that belongs
// to the pull mechanism
func (m *GossipMessage) IsPullMsg() bool {
return m.GetDataReq() != nil || m.GetDataUpdate() != nil ||
m.GetHello() != nil || m.GetDataDig() != nil
}
// IsRemoteStateMessage returns whether this GossipMessage is related to state synchronization
func (m *GossipMessage) IsRemoteStateMessage() bool {
return m.GetStateRequest() != nil || m.GetStateResponse() != nil
}
// GetPullMsgType returns the phase of the pull mechanism this GossipMessage belongs to
// for example: Hello, Digest, etc.
// If this isn't a pull message, PullMsgType_UNDEFINED is returned.
func (m *GossipMessage) GetPullMsgType() PullMsgType {
if helloMsg := m.GetHello(); helloMsg != nil {
return helloMsg.MsgType
}
if digMsg := m.GetDataDig(); digMsg != nil {
return digMsg.MsgType
}
if reqMsg := m.GetDataReq(); reqMsg != nil {
return reqMsg.MsgType
}
if resMsg := m.GetDataUpdate(); resMsg != nil {
return resMsg.MsgType
}
return PullMsgType_UNDEFINED
}
// IsChannelRestricted returns whether this GossipMessage should be routed
// only in its channel
func (m *GossipMessage) IsChannelRestricted() bool {
return m.Tag == GossipMessage_CHAN_AND_ORG || m.Tag == GossipMessage_CHAN_ONLY || m.Tag == GossipMessage_CHAN_OR_ORG
}
// IsOrgRestricted returns whether this GossipMessage should be routed only
// inside the organization
func (m *GossipMessage) IsOrgRestricted() bool {
return m.Tag == GossipMessage_CHAN_AND_ORG || m.Tag == GossipMessage_ORG_ONLY
}
// IsIdentityMsg returns whether this GossipMessage is an identity message
func (m *GossipMessage) IsIdentityMsg() bool {
return m.GetPeerIdentity() != nil
}
// IsDataReq returns whether this GossipMessage is a data request message
func (m *GossipMessage) IsDataReq() bool {
return m.GetDataReq() != nil
}
// IsPrivateDataMsg returns whether this message is related to private data
func (m *GossipMessage) IsPrivateDataMsg() bool {
return m.GetPrivateReq() != nil || m.GetPrivateRes() != nil || m.GetPrivateData() != nil
}
// IsAck returns whether this GossipMessage is an acknowledgement
func (m *GossipMessage) IsAck() bool {
return m.GetAck() != nil
}
// IsDataUpdate returns whether this GossipMessage is a data update message
func (m *GossipMessage) IsDataUpdate() bool {
return m.GetDataUpdate() != nil
}
// IsHelloMsg returns whether this GossipMessage is a hello message
func (m *GossipMessage) IsHelloMsg() bool {
return m.GetHello() != nil
}
// IsDigestMsg returns whether this GossipMessage is a digest message
func (m *GossipMessage) IsDigestMsg() bool {
return m.GetDataDig() != nil
}
// IsLeadershipMsg returns whether this GossipMessage is a leadership (leader election) message
func (m *GossipMessage) IsLeadershipMsg() bool {
return m.GetLeadershipMsg() != nil
}
// MsgConsumer invokes code given a SignedGossipMessage
type MsgConsumer func(message *SignedGossipMessage)
// IdentifierExtractor extracts from a SignedGossipMessage an identifier
type IdentifierExtractor func(*SignedGossipMessage) string
// IsTagLegal checks the GossipMessage tags and inner type
// and returns an error if the tag doesn't match the type.
func (m *GossipMessage) IsTagLegal() error {
if m.Tag == GossipMessage_UNDEFINED {
return fmt.Errorf("Undefined tag")
}
if m.IsDataMsg() {
if m.Tag != GossipMessage_CHAN_AND_ORG {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_CHAN_AND_ORG)])
}
return nil
}
if m.IsAliveMsg() || m.GetMemReq() != nil || m.GetMemRes() != nil {
if m.Tag != GossipMessage_EMPTY {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_EMPTY)])
}
return nil
}
if m.IsIdentityMsg() {
if m.Tag != GossipMessage_ORG_ONLY {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_ORG_ONLY)])
}
return nil
}
if m.IsPullMsg() {
switch m.GetPullMsgType() {
case PullMsgType_BLOCK_MSG:
if m.Tag != GossipMessage_CHAN_AND_ORG {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_CHAN_AND_ORG)])
}
return nil
case PullMsgType_IDENTITY_MSG:
if m.Tag != GossipMessage_EMPTY {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_EMPTY)])
}
return nil
default:
return fmt.Errorf("Invalid PullMsgType: %s", PullMsgType_name[int32(m.GetPullMsgType())])
}
}
if m.IsStateInfoMsg() || m.IsStateInfoPullRequestMsg() || m.IsStateInfoSnapshot() || m.IsRemoteStateMessage() {
if m.Tag != GossipMessage_CHAN_OR_ORG {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_CHAN_OR_ORG)])
}
return nil
}
if m.IsLeadershipMsg() {
if m.Tag != GossipMessage_CHAN_AND_ORG {
return fmt.Errorf("Tag should be %s", GossipMessage_Tag_name[int32(GossipMessage_CHAN_AND_ORG)])
}
return nil
}
return fmt.Errorf("Unknown message type: %v", m)
}
// Verifier receives a peer identity, a signature and a message
// and returns nil if the signature on the message could be verified
// using the given identity.
type Verifier func(peerIdentity []byte, signature, message []byte) error
// Signer signs a message, and returns (signature, nil)
// on success, and nil and an error on failure.
type Signer func(msg []byte) ([]byte, error)
// ReceivedMessage is a GossipMessage wrapper that
// enables the user to send a message to the origin from which
// the ReceivedMessage was sent from.
// It also allows to know the identity of the sender,
// to obtain the raw bytes the GossipMessage was un-marshaled from,
// and the signature over these raw bytes.
type ReceivedMessage interface {
// Respond sends a GossipMessage to the origin from which this ReceivedMessage was sent from
Respond(msg *GossipMessage)
// GetGossipMessage returns the underlying GossipMessage
GetGossipMessage() *SignedGossipMessage
// GetSourceMessage Returns the Envelope the ReceivedMessage was
// constructed with
GetSourceEnvelope() *Envelope
// GetConnectionInfo returns information about the remote peer
// that sent the message
GetConnectionInfo() *ConnectionInfo
// Ack returns to the sender an acknowledgement for the message
// An ack can receive an error that indicates that the operation related
// to the message has failed
Ack(err error)
}
// ConnectionInfo represents information about
// the remote peer that sent a certain ReceivedMessage
type ConnectionInfo struct {
ID common.PKIidType
Auth *AuthInfo
Identity api.PeerIdentityType
Endpoint string
}
// String returns a string representation of this ConnectionInfo
func (c *ConnectionInfo) String() string {
return fmt.Sprintf("%s %v", c.Endpoint, c.ID)
}
// AuthInfo represents the authentication
// data that was provided by the remote peer
// at the connection time
type AuthInfo struct {
SignedData []byte
Signature []byte
}
// Sign signs a GossipMessage with given Signer.
// Returns an Envelope on success,
// panics on failure.
func (m *SignedGossipMessage) Sign(signer Signer) (*Envelope, error) {
// If we have a secretEnvelope, don't override it.
// Back it up, and restore it later
var secretEnvelope *SecretEnvelope
if m.Envelope != nil {
secretEnvelope = m.Envelope.SecretEnvelope
}
m.Envelope = nil
payload, err := proto.Marshal(m.GossipMessage)
if err != nil {
return nil, err
}
sig, err := signer(payload)
if err != nil {
return nil, err
}
e := &Envelope{
Payload: payload,
Signature: sig,
SecretEnvelope: secretEnvelope,
}
m.Envelope = e
return e, nil
}
// NoopSign creates a SignedGossipMessage with a nil signature
func (m *GossipMessage) NoopSign() (*SignedGossipMessage, error) {
signer := func(msg []byte) ([]byte, error) {
return nil, nil
}
sMsg := &SignedGossipMessage{
GossipMessage: m,
}
_, err := sMsg.Sign(signer)
return sMsg, err
}
// Verify verifies a signed GossipMessage with a given Verifier.
// Returns nil on success, error on failure.
func (m *SignedGossipMessage) Verify(peerIdentity []byte, verify Verifier) error {
if m.Envelope == nil {
return errors.New("Missing envelope")
}
if len(m.Envelope.Payload) == 0 {
return errors.New("Empty payload")
}
if len(m.Envelope.Signature) == 0 {
return errors.New("Empty signature")
}
payloadSigVerificationErr := verify(peerIdentity, m.Envelope.Signature, m.Envelope.Payload)
if payloadSigVerificationErr != nil {
return payloadSigVerificationErr
}
if m.Envelope.SecretEnvelope != nil {
payload := m.Envelope.SecretEnvelope.Payload
sig := m.Envelope.SecretEnvelope.Signature
if len(payload) == 0 {
return errors.New("Empty payload")
}
if len(sig) == 0 {
return errors.New("Empty signature")
}
return verify(peerIdentity, sig, payload)
}
return nil
}
// IsSigned returns whether the message
// has a signature in the envelope.
func (m *SignedGossipMessage) IsSigned() bool {
return m.Envelope != nil && m.Envelope.Payload != nil && m.Envelope.Signature != nil
}
// ToGossipMessage un-marshals a given envelope and creates a
// SignedGossipMessage out of it.
// Returns an error if un-marshaling fails.
func (e *Envelope) ToGossipMessage() (*SignedGossipMessage, error) {
if e == nil {
return nil, errors.New("nil envelope")
}
msg := &GossipMessage{}
err := proto.Unmarshal(e.Payload, msg)
if err != nil {
return nil, fmt.Errorf("Failed unmarshaling GossipMessage from envelope: %v", err)
}
return &SignedGossipMessage{
GossipMessage: msg,
Envelope: e,
}, nil
}
// SignSecret signs the secret payload and creates
// a secret envelope out of it.
func (e *Envelope) SignSecret(signer Signer, secret *Secret) error {
payload, err := proto.Marshal(secret)
if err != nil {
return err
}
sig, err := signer(payload)
if err != nil {
return err
}
e.SecretEnvelope = &SecretEnvelope{
Payload: payload,
Signature: sig,
}
return nil
}
// InternalEndpoint returns the internal endpoint
// in the secret envelope, or an empty string
// if a failure occurs.
func (s *SecretEnvelope) InternalEndpoint() string {
if s == nil {
return ""
}
secret := &Secret{}
if err := proto.Unmarshal(s.Payload, secret); err != nil {
return ""
}
return secret.GetInternalEndpoint()
}
// SignedGossipMessage contains a GossipMessage
// and the Envelope from which it came from
type SignedGossipMessage struct {
*Envelope
*GossipMessage
}
func (p *Payload) toString() string {
return fmt.Sprintf("Block message: {Data: %d bytes, seq: %d}", len(p.Data), p.SeqNum)
}
func (du *DataUpdate) toString() string {
mType := PullMsgType_name[int32(du.MsgType)]
return fmt.Sprintf("Type: %s, items: %d, nonce: %d", mType, len(du.Data), du.Nonce)
}
func (mr *MembershipResponse) toString() string {
return fmt.Sprintf("MembershipResponse with Alive: %d, Dead: %d", len(mr.Alive), len(mr.Dead))
}
func (sis *StateInfoSnapshot) toString() string {
return fmt.Sprintf("StateInfoSnapshot with %d items", len(sis.Elements))
}
// String returns a string representation
// of a SignedGossipMessage
func (m *SignedGossipMessage) String() string {
env := "No envelope"
if m.Envelope != nil {
var secretEnv string
if m.SecretEnvelope != nil {
pl := len(m.SecretEnvelope.Payload)
sl := len(m.SecretEnvelope.Signature)
secretEnv = fmt.Sprintf(" Secret payload: %d bytes, Secret Signature: %d bytes", pl, sl)
}
env = fmt.Sprintf("%d bytes, Signature: %d bytes%s", len(m.Envelope.Payload), len(m.Envelope.Signature), secretEnv)
}
gMsg := "No gossipMessage"
if m.GossipMessage != nil {
var isSimpleMsg bool
if m.GetStateResponse() != nil {
gMsg = fmt.Sprintf("StateResponse with %d items", len(m.GetStateResponse().Payloads))
} else if m.IsDataMsg() && m.GetDataMsg().Payload != nil {
gMsg = m.GetDataMsg().Payload.toString()
} else if m.IsDataUpdate() {
update := m.GetDataUpdate()
gMsg = fmt.Sprintf("DataUpdate: %s", update.toString())
} else if m.GetMemRes() != nil {
gMsg = m.GetMemRes().toString()
} else if m.IsStateInfoSnapshot() {
gMsg = m.GetStateSnapshot().toString()
} else if m.GetPrivateRes() != nil {
gMsg = m.GetPrivateRes().ToString()
} else {
gMsg = m.GossipMessage.String()
isSimpleMsg = true
}
if !isSimpleMsg {
desc := fmt.Sprintf("Channel: %s, nonce: %d, tag: %s", string(m.Channel), m.Nonce, GossipMessage_Tag_name[int32(m.Tag)])
gMsg = fmt.Sprintf("%s %s", desc, gMsg)
}
}
return fmt.Sprintf("GossipMessage: %v, Envelope: %s", gMsg, env)
}
func (dd *DataRequest) FormattedDigests() []string {
if dd.MsgType == PullMsgType_IDENTITY_MSG {
return digestsToHex(dd.Digests)
}
return digestsAsStrings(dd.Digests)
}
func (dd *DataDigest) FormattedDigests() []string {
if dd.MsgType == PullMsgType_IDENTITY_MSG {
return digestsToHex(dd.Digests)
}
return digestsAsStrings(dd.Digests)
}
// Hash returns the SHA256 representation of the PvtDataDigest's bytes
func (dig *PvtDataDigest) Hash() (string, error) {
b, err := proto.Marshal(dig)
if err != nil {
return "", err
}
return hex.EncodeToString(util.ComputeSHA256(b)), nil
}
// ToString returns a string representation of this RemotePvtDataResponse
func (res *RemotePvtDataResponse) ToString() string {
a := make([]string, len(res.Elements))
for i, el := range res.Elements {
a[i] = fmt.Sprintf("%s with %d elements", el.Digest.String(), len(el.Payload))
}
return fmt.Sprintf("%v", a)
}
func digestsAsStrings(digests [][]byte) []string {
a := make([]string, len(digests))
for i, dig := range digests {
a[i] = string(dig)
}
return a
}
func digestsToHex(digests [][]byte) []string {
a := make([]string, len(digests))
for i, dig := range digests {
a[i] = hex.EncodeToString(dig)
}
return a
}
// LedgerHeight returns the ledger height that is specified
// in the StateInfo message
func (msg *StateInfo) LedgerHeight() (uint64, error) {
if msg.Properties != nil {
return msg.Properties.LedgerHeight, nil
}
return 0, errors.New("properties undefined")
}
// Abs returns abs(a-b)
func abs(a, b uint64) uint64 {
if a > b {
return a - b
}
return b - a
}