-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
608 lines (538 loc) · 17.4 KB
/
client.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package discovery
import (
"bytes"
"context"
"encoding/json"
"math/rand"
"time"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/protos/discovery"
"github.com/hyperledger/fabric/protos/gossip"
"github.com/hyperledger/fabric/protos/msp"
"github.com/pkg/errors"
)
var (
configTypes = []discovery.QueryType{discovery.ConfigQueryType, discovery.PeerMembershipQueryType, discovery.ChaincodeQueryType, discovery.LocalMembershipQueryType}
)
// Client interacts with the discovery server
type Client struct {
lastRequest []byte
lastSignature []byte
createConnection Dialer
signRequest Signer
}
// NewRequest creates a new request
func NewRequest() *Request {
r := &Request{
invocationChainMapping: make(map[int][]InvocationChain),
queryMapping: make(map[discovery.QueryType]map[string]int),
Request: &discovery.Request{},
}
// pre-populate types
for _, queryType := range configTypes {
r.queryMapping[queryType] = make(map[string]int)
}
return r
}
// Request aggregates several queries inside it
type Request struct {
lastChannel string
lastIndex int
// map from query type to channel to expected index in response
queryMapping map[discovery.QueryType]map[string]int
// map from expected index in response to invocation chains
invocationChainMapping map[int][]InvocationChain
*discovery.Request
}
// AddConfigQuery adds to the request a config query
func (req *Request) AddConfigQuery() *Request {
ch := req.lastChannel
q := &discovery.Query_ConfigQuery{
ConfigQuery: &discovery.ConfigQuery{},
}
req.Queries = append(req.Queries, &discovery.Query{
Channel: ch,
Query: q,
})
req.addQueryMapping(discovery.ConfigQueryType, ch)
return req
}
// AddEndorsersQuery adds to the request a query for given chaincodes
// interests are the chaincode interests that the client wants to query for.
// All interests for a given channel should be supplied in an aggregated slice
func (req *Request) AddEndorsersQuery(interests ...*discovery.ChaincodeInterest) (*Request, error) {
if err := validateInterests(interests...); err != nil {
return nil, err
}
ch := req.lastChannel
q := &discovery.Query_CcQuery{
CcQuery: &discovery.ChaincodeQuery{
Interests: interests,
},
}
req.Queries = append(req.Queries, &discovery.Query{
Channel: ch,
Query: q,
})
var invocationChains []InvocationChain
for _, interest := range interests {
invocationChains = append(invocationChains, interest.Chaincodes)
}
req.addChaincodeQueryMapping(invocationChains)
req.addQueryMapping(discovery.ChaincodeQueryType, ch)
return req, nil
}
// AddLocalPeersQuery adds to the request a local peer query
func (req *Request) AddLocalPeersQuery() *Request {
q := &discovery.Query_LocalPeers{
LocalPeers: &discovery.LocalPeerQuery{},
}
req.Queries = append(req.Queries, &discovery.Query{
Query: q,
})
req.addQueryMapping(discovery.LocalMembershipQueryType, "")
return req
}
// AddPeersQuery adds to the request a peer query
func (req *Request) AddPeersQuery() *Request {
ch := req.lastChannel
q := &discovery.Query_PeerQuery{
PeerQuery: &discovery.PeerMembershipQuery{},
}
req.Queries = append(req.Queries, &discovery.Query{
Channel: ch,
Query: q,
})
req.addQueryMapping(discovery.PeerMembershipQueryType, ch)
return req
}
// OfChannel sets the next queries added to be in the given channel's context
func (req *Request) OfChannel(ch string) *Request {
req.lastChannel = ch
return req
}
func (req *Request) addChaincodeQueryMapping(invocationChains []InvocationChain) {
req.invocationChainMapping[req.lastIndex] = invocationChains
}
func (req *Request) addQueryMapping(queryType discovery.QueryType, key string) {
req.queryMapping[queryType][key] = req.lastIndex
req.lastIndex++
}
// Send sends the request and returns the response, or error on failure
func (c *Client) Send(ctx context.Context, req *Request, auth *discovery.AuthInfo) (Response, error) {
reqToBeSent := *req.Request
reqToBeSent.Authentication = auth
payload, err := proto.Marshal(&reqToBeSent)
if err != nil {
return nil, errors.Wrap(err, "failed marshaling Request to bytes")
}
sig := c.lastSignature
// Only sign the Request if it is different than the previous Request sent.
// Otherwise, use the last signature from the previous send.
// This is not only to save CPU cycles in the Client-side,
// but also for the server side to be able to memoize the signature verification.
// We have the use the previous signature, because many signature schemes are not deterministic.
if !bytes.Equal(c.lastRequest, payload) {
sig, err = c.signRequest(payload)
if err != nil {
return nil, errors.Wrap(err, "failed signing Request")
}
}
// Remember this Request and the corresponding signature, in order to skip signing next time
// and reuse the signature
c.lastRequest = payload
c.lastSignature = sig
conn, err := c.createConnection()
if err != nil {
return nil, errors.Wrap(err, "failed connecting to discovery service")
}
cl := discovery.NewDiscoveryClient(conn)
resp, err := cl.Discover(ctx, &discovery.SignedRequest{
Payload: payload,
Signature: sig,
})
if err != nil {
return nil, errors.Wrap(err, "discovery service refused our Request")
}
if n := len(resp.Results); n != req.lastIndex {
return nil, errors.Errorf("Sent %d queries but received %d responses back", req.lastIndex, n)
}
return req.computeResponse(resp)
}
type resultOrError interface {
}
type response map[key]resultOrError
type localResponse struct {
response
}
func (cr *localResponse) Peers() ([]*Peer, error) {
return parsePeers(discovery.LocalMembershipQueryType, cr.response, "")
}
type channelResponse struct {
response
channel string
}
func (cr *channelResponse) Config() (*discovery.ConfigResult, error) {
res, exists := cr.response[key{
queryType: discovery.ConfigQueryType,
channel: cr.channel,
}]
if !exists {
return nil, ErrNotFound
}
if config, isConfig := res.(*discovery.ConfigResult); isConfig {
return config, nil
}
return nil, res.(error)
}
func parsePeers(queryType discovery.QueryType, r response, channel string) ([]*Peer, error) {
res, exists := r[key{
queryType: queryType,
channel: channel,
}]
if !exists {
return nil, ErrNotFound
}
if peers, isPeers := res.([]*Peer); isPeers {
return peers, nil
}
return nil, res.(error)
}
func (cr *channelResponse) Peers() ([]*Peer, error) {
return parsePeers(discovery.PeerMembershipQueryType, cr.response, cr.channel)
}
func (cr *channelResponse) Endorsers(invocationChain InvocationChain, ps PrioritySelector, ef ExclusionFilter) (Endorsers, error) {
// If we have a key that has no chaincode field,
// it means it's an error returned from the service
if err, exists := cr.response[key{
queryType: discovery.ChaincodeQueryType,
channel: cr.channel,
}]; exists {
return nil, err.(error)
}
// Else, the service returned a response that isn't an error
res, exists := cr.response[key{
queryType: discovery.ChaincodeQueryType,
channel: cr.channel,
invocationChain: invocationChain.String(),
}]
if !exists {
return nil, ErrNotFound
}
desc := res.(*endorsementDescriptor)
rand.Seed(time.Now().Unix())
// We iterate over all layouts to find one that we have enough peers to select
for _, index := range rand.Perm(len(desc.layouts)) {
layout := desc.layouts[index]
endorsers, canLayoutBeSatisfied := selectPeersForLayout(desc.endorsersByGroups, layout, ps, ef)
if canLayoutBeSatisfied {
return endorsers, nil
}
}
return nil, errors.New("no endorsement combination can be satisfied")
}
func selectPeersForLayout(endorsersByGroups map[string][]*Peer, layout map[string]int, ps PrioritySelector, ef ExclusionFilter) (Endorsers, bool) {
var endorsers []*Peer
for grp, count := range layout {
shuffledEndorsers := Endorsers(endorsersByGroups[grp]).Shuffle()
endorsersOfGrp := shuffledEndorsers.Filter(ef).Sort(ps)
// We couldn't select enough peers for this layout because the current group
// requires more peers than we have available to be selected
if len(endorsersOfGrp) < count {
return nil, false
}
endorsersOfGrp = endorsersOfGrp[:count]
endorsers = append(endorsers, endorsersOfGrp...)
}
// The current (randomly chosen) layout can be satisfied, so return it
// instead of checking the next one.
return endorsers, true
}
func (resp response) ForLocal() LocalResponse {
return &localResponse{
response: resp,
}
}
func (resp response) ForChannel(ch string) ChannelResponse {
return &channelResponse{
channel: ch,
response: resp,
}
}
type key struct {
queryType discovery.QueryType
channel string
invocationChain string
}
func (req *Request) computeResponse(r *discovery.Response) (response, error) {
var err error
resp := make(response)
for configType, channel2index := range req.queryMapping {
switch configType {
case discovery.ConfigQueryType:
err = resp.mapConfig(channel2index, r)
case discovery.ChaincodeQueryType:
err = resp.mapEndorsers(channel2index, r, req.queryMapping, req.invocationChainMapping)
case discovery.PeerMembershipQueryType:
err = resp.mapPeerMembership(channel2index, r, discovery.PeerMembershipQueryType)
case discovery.LocalMembershipQueryType:
err = resp.mapPeerMembership(channel2index, r, discovery.LocalMembershipQueryType)
}
if err != nil {
return nil, err
}
}
return resp, err
}
func (resp response) mapConfig(channel2index map[string]int, r *discovery.Response) error {
for ch, index := range channel2index {
config, err := r.ConfigAt(index)
if config == nil && err == nil {
return errors.Errorf("expected QueryResult of either ConfigResult or Error but got %v instead", r.Results[index])
}
key := key{
queryType: discovery.ConfigQueryType,
channel: ch,
}
if err != nil {
resp[key] = errors.New(err.Content)
continue
}
resp[key] = config
}
return nil
}
func (resp response) mapPeerMembership(channel2index map[string]int, r *discovery.Response, qt discovery.QueryType) error {
for ch, index := range channel2index {
membersRes, err := r.MembershipAt(index)
if membersRes == nil && err == nil {
return errors.Errorf("expected QueryResult of either PeerMembershipResult or Error but got %v instead", r.Results[index])
}
key := key{
queryType: qt,
channel: ch,
}
if err != nil {
resp[key] = errors.New(err.Content)
continue
}
peers, err2 := peersForChannel(membersRes, qt)
if err2 != nil {
return errors.Wrap(err2, "failed constructing peer membership out of response")
}
resp[key] = peers
}
return nil
}
func peersForChannel(membersRes *discovery.PeerMembershipResult, qt discovery.QueryType) ([]*Peer, error) {
var peers []*Peer
for org, peersOfCurrentOrg := range membersRes.PeersByOrg {
for _, peer := range peersOfCurrentOrg.Peers {
aliveMsg, err := peer.MembershipInfo.ToGossipMessage()
if err != nil {
return nil, errors.Wrap(err, "failed unmarshaling alive message")
}
var stateInfoMsg *gossip.SignedGossipMessage
if isStateInfoExpected(qt) {
stateInfoMsg, err = peer.StateInfo.ToGossipMessage()
if err != nil {
return nil, errors.Wrap(err, "failed unmarshaling stateInfo message")
}
if err := validateStateInfoMessage(stateInfoMsg); err != nil {
return nil, errors.Wrap(err, "failed validating stateInfo message")
}
}
if err := validateAliveMessage(aliveMsg); err != nil {
return nil, errors.Wrap(err, "failed validating alive message")
}
peers = append(peers, &Peer{
MSPID: org,
Identity: peer.Identity,
AliveMessage: aliveMsg,
StateInfoMessage: stateInfoMsg,
})
}
}
return peers, nil
}
func isStateInfoExpected(qt discovery.QueryType) bool {
return qt != discovery.LocalMembershipQueryType
}
func (resp response) mapEndorsers(
channel2index map[string]int,
r *discovery.Response,
queryMapping map[discovery.QueryType]map[string]int,
chaincodeQueryMapping map[int][]InvocationChain) error {
for ch, index := range channel2index {
ccQueryRes, err := r.EndorsersAt(index)
if ccQueryRes == nil && err == nil {
return errors.Errorf("expected QueryResult of either ChaincodeQueryResult or Error but got %v instead", r.Results[index])
}
if err != nil {
key := key{
queryType: discovery.ChaincodeQueryType,
channel: ch,
}
resp[key] = errors.New(err.Content)
continue
}
if err := resp.mapEndorsersOfChannel(ccQueryRes, ch, chaincodeQueryMapping[index]); err != nil {
return errors.Wrapf(err, "failed assembling endorsers of channel %s", ch)
}
}
return nil
}
func (resp response) mapEndorsersOfChannel(ccRs *discovery.ChaincodeQueryResult, channel string, invocationChain []InvocationChain) error {
if len(ccRs.Content) < len(invocationChain) {
return errors.Errorf("expected %d endorsement descriptors but got only %d", len(invocationChain), len(ccRs.Content))
}
for i, desc := range ccRs.Content {
expectedCCName := invocationChain[i][0].Name
if desc.Chaincode != expectedCCName {
return errors.Errorf("expected chaincode %s but got endorsement descriptor for %s", expectedCCName, desc.Chaincode)
}
key := key{
queryType: discovery.ChaincodeQueryType,
channel: channel,
invocationChain: invocationChain[i].String(),
}
descriptor, err := resp.createEndorsementDescriptor(desc, channel)
if err != nil {
return err
}
resp[key] = descriptor
}
return nil
}
func (resp response) createEndorsementDescriptor(desc *discovery.EndorsementDescriptor, channel string) (*endorsementDescriptor, error) {
descriptor := &endorsementDescriptor{
layouts: []map[string]int{},
endorsersByGroups: make(map[string][]*Peer),
}
for _, l := range desc.Layouts {
currentLayout := make(map[string]int)
descriptor.layouts = append(descriptor.layouts, currentLayout)
for grp, count := range l.QuantitiesByGroup {
if _, exists := desc.EndorsersByGroups[grp]; !exists {
return nil, errors.Errorf("group %s isn't mapped to endorsers, but exists in a layout", grp)
}
currentLayout[grp] = int(count)
}
}
for grp, peers := range desc.EndorsersByGroups {
var endorsers []*Peer
for _, p := range peers.Peers {
peer, err := endorser(p, desc.Chaincode, channel)
if err != nil {
return nil, errors.Wrap(err, "failed creating endorser object")
}
endorsers = append(endorsers, peer)
}
descriptor.endorsersByGroups[grp] = endorsers
}
return descriptor, nil
}
func endorser(peer *discovery.Peer, chaincode, channel string) (*Peer, error) {
if peer.MembershipInfo == nil || peer.StateInfo == nil {
return nil, errors.Errorf("received empty envelope(s) for endorsers for chaincode %s, channel %s", chaincode, channel)
}
aliveMsg, err := peer.MembershipInfo.ToGossipMessage()
if err != nil {
return nil, errors.Wrap(err, "failed unmarshaling gossip envelope to alive message")
}
stateInfMsg, err := peer.StateInfo.ToGossipMessage()
if err != nil {
return nil, errors.Wrap(err, "failed unmarshaling gossip envelope to state info message")
}
if err := validateAliveMessage(aliveMsg); err != nil {
return nil, errors.Wrap(err, "failed validating alive message")
}
if err := validateStateInfoMessage(stateInfMsg); err != nil {
return nil, errors.Wrap(err, "failed validating stateInfo message")
}
sID := &msp.SerializedIdentity{}
if err := proto.Unmarshal(peer.Identity, sID); err != nil {
return nil, errors.Wrap(err, "failed unmarshaling peer's identity")
}
return &Peer{
Identity: peer.Identity,
StateInfoMessage: stateInfMsg,
AliveMessage: aliveMsg,
MSPID: sID.Mspid,
}, nil
}
type endorsementDescriptor struct {
endorsersByGroups map[string][]*Peer
layouts []map[string]int
}
// NewClient creates a new Client instance
func NewClient(createConnection Dialer, s Signer) *Client {
return &Client{
createConnection: createConnection,
signRequest: s,
}
}
func validateAliveMessage(message *gossip.SignedGossipMessage) error {
am := message.GetAliveMsg()
if am == nil {
return errors.New("message isn't an alive message")
}
m := am.Membership
if m == nil {
return errors.New("membership is empty")
}
if am.Timestamp == nil {
return errors.New("timestamp is nil")
}
return nil
}
func validateStateInfoMessage(message *gossip.SignedGossipMessage) error {
si := message.GetStateInfo()
if si == nil {
return errors.New("message isn't a stateInfo message")
}
if si.Timestamp == nil {
return errors.New("timestamp is nil")
}
if si.Properties == nil {
return errors.New("properties is nil")
}
return nil
}
func validateInterests(interests ...*discovery.ChaincodeInterest) error {
if len(interests) == 0 {
return errors.New("no chaincode interests given")
}
for _, interest := range interests {
if interest == nil {
return errors.New("chaincode interest is nil")
}
if err := InvocationChain(interest.Chaincodes).ValidateInvocationChain(); err != nil {
return err
}
}
return nil
}
// InvocationChain aggregates ChaincodeCalls
type InvocationChain []*discovery.ChaincodeCall
// String returns a string representation of this invocation chain
func (ic InvocationChain) String() string {
s, _ := json.Marshal(ic)
return string(s)
}
// ValidateInvocationChain validates the InvocationChain's structure
func (ic InvocationChain) ValidateInvocationChain() error {
if len(ic) == 0 {
return errors.New("invocation chain should not be empty")
}
for _, cc := range ic {
if cc.Name == "" {
return errors.New("chaincode name should not be empty")
}
}
return nil
}