forked from hyperledger/fabric-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mockendorserserver.go
380 lines (328 loc) · 10.8 KB
/
mockendorserserver.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
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package channel
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"fmt"
"net"
"sync"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/bccsp/utils"
"github.com/hyperledger/fabric-sdk-go/internal/github.com/hyperledger/fabric/protos/discovery"
"github.com/hyperledger/fabric-sdk-go/pkg/common/providers/fab"
discmocks "github.com/hyperledger/fabric-sdk-go/pkg/fab/discovery/mocks"
eventmocks "github.com/hyperledger/fabric-sdk-go/pkg/fab/events/mocks"
"github.com/hyperledger/fabric-sdk-go/pkg/util/test"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/rwsetutil"
cb "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/common"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/ledger/rwset/kvrwset"
"github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/msp"
pb "github.com/hyperledger/fabric-sdk-go/third_party/github.com/hyperledger/fabric/protos/peer"
"github.com/pkg/errors"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// MockEndorserServer mock endorser server to process endorsement proposals
type MockEndorserServer struct {
ProposalError error
Creds credentials.TransportCredentials
mockPeer *MockPeer
srv *grpc.Server
wg sync.WaitGroup
AddkvWrite bool
DeliveriesListener chan *cb.Block
FilteredDelListener chan *pb.FilteredBlock
}
// ProcessProposal mock implementation that returns success (through mockPeer) if error is not set
// error if it is
func (m *MockEndorserServer) ProcessProposal(context context.Context,
proposal *pb.SignedProposal) (*pb.ProposalResponse, error) {
fcn, err := m.getFuncNameFromProposal(proposal)
if err != nil {
return nil, errors.Wrap(err, "Error getting function name from mockPeer")
}
if m.ProposalError == nil {
tp, err := m.GetMockPeer().ProcessTransactionProposal(fab.TransactionProposal{}, fcn)
if err != nil {
return &pb.ProposalResponse{Response: &pb.Response{
Status: 500,
Message: err.Error(),
}}, err
}
return tp.ProposalResponse, nil
}
return &pb.ProposalResponse{Response: &pb.Response{
Status: 500,
Message: m.ProposalError.Error(),
}}, m.ProposalError
}
func (m *MockEndorserServer) getFuncNameFromProposal(proposal *pb.SignedProposal) ([]byte, error) {
pr := &pb.Proposal{}
err := proto.Unmarshal(proposal.GetProposalBytes(), pr)
if err != nil {
return nil, err
}
cpp := &pb.ChaincodeProposalPayload{}
err = proto.Unmarshal(pr.Payload, cpp)
if err != nil {
return nil, err
}
cic := &pb.ChaincodeInvocationSpec{}
err = proto.Unmarshal(cpp.Input, cic)
if err != nil {
return nil, err
}
return cic.ChaincodeSpec.Input.Args[0], nil
}
// Start the mock endorser server
func (m *MockEndorserServer) Start(address string, filteredChannel chan *pb.FilteredBlock) string {
if m.srv != nil {
panic("MockEndorserServer already started")
}
// pass in TLS creds if present
if m.Creds != nil {
m.srv = grpc.NewServer(grpc.Creds(m.Creds))
} else {
m.srv = grpc.NewServer()
}
// set the filtered block channel used by the mock delivery server
m.FilteredDelListener = filteredChannel
m.registerDiscoveryAndDeliveryServers(address)
lis, err := net.Listen("tcp", address)
if err != nil {
panic(fmt.Sprintf("Error starting EndorserServer %s", err))
}
addr := lis.Addr().String()
test.Logf("Starting MockEndorserServer [%s]", addr)
pb.RegisterEndorserServer(m.srv, m)
m.wg.Add(1)
go func() {
defer m.wg.Done()
if err := m.srv.Serve(lis); err != nil {
test.Logf("StartEndorserServer failed [%s]", err)
}
}()
return addr
}
// Stop the mock broadcast server and wait for completion.
func (m *MockEndorserServer) Stop() {
if m.srv == nil {
panic("MockEndorserServer not started")
}
m.srv.Stop()
m.wg.Wait()
m.srv = nil
}
// GetMockPeer will return the mock endorser's mock peer in a thread safe way
func (m *MockEndorserServer) GetMockPeer() *MockPeer {
var v = func() *MockPeer {
m.wg.Add(1)
defer m.wg.Done()
return m.mockPeer
}
return v()
}
// SetMockPeer will write the mock endorser's mock peer in a thread safe way
func (m *MockEndorserServer) SetMockPeer(mPeer *MockPeer) {
func(p *MockPeer) {
m.wg.Add(1)
defer m.wg.Done()
m.mockPeer = p
}(mPeer)
}
func (m *MockEndorserServer) registerDiscoveryAndDeliveryServers(peerAddress string) {
//register DiscoverService and DeliveryService
discoverServer := discmocks.NewServer(
discmocks.WithLocalPeers(
&discmocks.MockDiscoveryPeerEndpoint{
MSPID: "Org1MSP",
Endpoint: peerAddress,
LedgerHeight: 26,
},
),
discmocks.WithPeers(
&discmocks.MockDiscoveryPeerEndpoint{
MSPID: "Org1MSP",
Endpoint: peerAddress,
LedgerHeight: 26,
},
),
)
discovery.RegisterDiscoveryServer(m.srv, discoverServer)
deliverServer := eventmocks.NewMockDeliverServerWithFilteredDeliveries(m.FilteredDelListener)
pb.RegisterDeliverServer(m.srv, deliverServer)
}
// MockPeer is a mock fabricsdk.Peer
type MockPeer struct {
RWLock *sync.RWMutex
Error error
MockName string
MockURL string
MockRoles []string
MockCert *pem.Block
Payload map[string][]byte
ResponseMessage string
MockMSP string
Status int32
KVWrite bool
ProcessProposalCalls int
Endorser []byte
}
// NewMockPeer creates basic mock peer
func NewMockPeer(name string, url string) *MockPeer {
mp := &MockPeer{MockName: name, MockURL: url, Status: 200, RWLock: &sync.RWMutex{}}
return mp
}
// Name returns the mock peer's mock name
func (p MockPeer) Name() string {
return p.MockName
}
// SetName sets the mock peer's mock name
func (p *MockPeer) SetName(name string) {
p.MockName = name
}
// MSPID gets the Peer mspID.
func (p *MockPeer) MSPID() string {
return p.MockMSP
}
// SetMSPID sets the Peer mspID.
func (p *MockPeer) SetMSPID(mspID string) {
p.MockMSP = mspID
}
// Roles returns the mock peer's mock roles
func (p *MockPeer) Roles() []string {
return p.MockRoles
}
// SetRoles sets the mock peer's mock roles
func (p *MockPeer) SetRoles(roles []string) {
p.MockRoles = roles
}
// EnrollmentCertificate returns the mock peer's mock enrollment certificate
func (p *MockPeer) EnrollmentCertificate() *pem.Block {
return p.MockCert
}
// SetEnrollmentCertificate sets the mock peer's mock enrollment certificate
func (p *MockPeer) SetEnrollmentCertificate(pem *pem.Block) {
p.MockCert = pem
}
// URL returns the mock peer's mock URL
func (p *MockPeer) URL() string {
return p.MockURL
}
// ProcessTransactionProposal does not send anything anywhere but returns an empty mock ProposalResponse
func (p *MockPeer) ProcessTransactionProposal(tp fab.TransactionProposal, funcName []byte) (*fab.TransactionProposalResponse, error) {
if p.RWLock != nil {
p.RWLock.Lock()
defer p.RWLock.Unlock()
}
p.ProcessProposalCalls++
if p.Endorser == nil {
// We serialize identities by prepending the MSPID and appending the ASN.1 DER content of the cert
sID := &msp.SerializedIdentity{Mspid: "Org1MSP", IdBytes: []byte(CertPem)}
endorser, err := proto.Marshal(sID)
if err != nil {
return nil, err
}
p.Endorser = endorser
}
block, _ := pem.Decode(KeyPem)
lowLevelKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, errors.Wrap(err, "Error received while parsing EC Key")
}
proposalResponsePayload, err := p.createProposalResponsePayload()
if err != nil {
return nil, errors.Wrap(err, "Error received while creating proposal response")
}
sigma, err := SignECDSA(lowLevelKey, append(proposalResponsePayload, p.Endorser...))
if err != nil {
return nil, errors.Wrap(err, "Error received while signing proposal for endorser with EC key")
}
payload, ok := p.Payload[string(funcName)]
if !ok {
payload, ok = p.Payload[string("default")]
if !ok {
fmt.Printf("payload for func(%s) not found\n", funcName)
}
}
return &fab.TransactionProposalResponse{
Endorser: p.MockURL,
Status: p.Status,
ProposalResponse: &pb.ProposalResponse{Response: &pb.Response{
Message: p.ResponseMessage, Status: p.Status, Payload: payload}, Payload: proposalResponsePayload,
Endorsement: &pb.Endorsement{Endorser: p.Endorser, Signature: sigma}},
}, p.Error
}
func (p *MockPeer) createProposalResponsePayload() ([]byte, error) {
prp := &pb.ProposalResponsePayload{}
ccAction := &pb.ChaincodeAction{}
txRwSet := &rwsetutil.TxRwSet{}
var kvWrite []*kvrwset.KVWrite
if p.KVWrite {
kvWrite = []*kvrwset.KVWrite{{Key: "key2", IsDelete: false, Value: []byte("value2")}}
}
txRwSet.NsRwSets = []*rwsetutil.NsRwSet{
{NameSpace: "ns1", KvRwSet: &kvrwset.KVRWSet{
Reads: []*kvrwset.KVRead{{Key: "key1", Version: &kvrwset.Version{BlockNum: 1, TxNum: 1}}},
Writes: kvWrite,
}}}
txRWSetBytes, err := txRwSet.ToProtoBytes()
if err != nil {
return nil, err
}
ccAction.Results = txRWSetBytes
ccActionBytes, err := proto.Marshal(ccAction)
if err != nil {
return nil, err
}
prp.Extension = ccActionBytes
prpBytes, err := proto.Marshal(prp)
if err != nil {
return nil, err
}
return prpBytes, nil
}
// SignECDSA sign with ec key
func SignECDSA(k *ecdsa.PrivateKey, digest []byte) (signature []byte, err error) {
hash := sha256.New()
_, err = hash.Write(digest)
if err != nil {
return nil, err
}
r, s, err := ecdsa.Sign(rand.Reader, k, hash.Sum(nil))
if err != nil {
return nil, err
}
s, _, err = utils.ToLowS(&k.PublicKey, s)
if err != nil {
return nil, err
}
return utils.MarshalECDSASignature(r, s)
}
// CertPem certificate
var CertPem = `-----BEGIN CERTIFICATE-----
MIICCjCCAbGgAwIBAgIQOcq9Om9VwUe9hGN0TTGw1DAKBggqhkjOPQQDAjBYMQsw
CQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEWMBQGA1UEBxMNU2FuIEZy
YW5jaXNjbzENMAsGA1UEChMET3JnMTENMAsGA1UEAxMET3JnMTAeFw0xNzA1MDgw
OTMwMzRaFw0yNzA1MDYwOTMwMzRaMGUxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpD
YWxpZm9ybmlhMRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRUwEwYDVQQKEwxPcmcx
LXNlcnZlcjExEjAQBgNVBAMTCWxvY2FsaG9zdDBZMBMGByqGSM49AgEGCCqGSM49
AwEHA0IABAm+2CZhbmsnA+HKQynXKz7fVZvvwlv/DdNg3Mdg7lIcP2z0b07/eAZ5
0chdJNcjNAd/QAj/mmGG4dObeo4oTKGjUDBOMA4GA1UdDwEB/wQEAwIFoDAdBgNV
HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDAYDVR0TAQH/BAIwADAPBgNVHSME
CDAGgAQBAgMEMAoGCCqGSM49BAMCA0cAMEQCIG55RvN4Boa0WS9UcIb/tI2YrAT8
EZd/oNnZYlbxxyvdAiB6sU9xAn4oYIW9xtrrOISv3YRg8rkCEATsagQfH8SiLg==
-----END CERTIFICATE-----`
// KeyPem ec private key
var KeyPem = []byte(`-----BEGIN EC PRIVATE KEY-----
MHcCAQEEICfXQtVmdQAlp/l9umWJqCXNTDurmciDNmGHPpxHwUK/oAoGCCqGSM49
AwEHoUQDQgAECb7YJmFuaycD4cpDKdcrPt9Vm+/CW/8N02Dcx2DuUhw/bPRvTv94
BnnRyF0k1yM0B39ACP+aYYbh05t6jihMoQ==
-----END EC PRIVATE KEY-----`)