-
Notifications
You must be signed in to change notification settings - Fork 19
/
e2e_test.go
394 lines (348 loc) · 16 KB
/
e2e_test.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
package test
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net/http"
"os"
"path"
"sync"
"time"
"github.com/hyperledger/fabric-admin-sdk/internal/configtxgen/genesisconfig"
"github.com/hyperledger/fabric-admin-sdk/pkg/chaincode"
"github.com/hyperledger/fabric-admin-sdk/pkg/channel"
"github.com/hyperledger/fabric-admin-sdk/pkg/discovery"
"github.com/hyperledger/fabric-admin-sdk/pkg/identity"
"github.com/hyperledger/fabric-admin-sdk/pkg/network"
"github.com/hyperledger/fabric-gateway/pkg/client"
gatewaypb "github.com/hyperledger/fabric-protos-go-apiv2/gateway"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"google.golang.org/grpc/status"
)
const (
org1PeerAddress = "localhost:7051"
org2PeerAddress = "localhost:9051"
channelName = "mychannel"
org1MspID = "Org1MSP"
org2MspID = "Org2MSP"
)
func runParallel[T any](args []T, f func(T)) {
var wg sync.WaitGroup
for _, arg := range args {
wg.Add(1)
go func(target T) {
defer GinkgoRecover()
defer wg.Done()
f(target)
}(arg)
}
wg.Wait()
}
func printGrpcError(err error) {
if err == nil {
return
}
fmt.Printf("Received error type %T: %s\n", err, err)
var endorseErr *client.EndorseError
var submitErr *client.SubmitError
var commitStatusErr *client.CommitStatusError
var commitErr *client.CommitError
if errors.As(err, &endorseErr) {
fmt.Printf("Endorse error for transaction %s with gRPC status %v: %s\n", endorseErr.TransactionID, status.Code(err), endorseErr)
} else if errors.As(err, &submitErr) {
fmt.Printf("Submit error for transaction %s with gRPC status %v: %s\n", submitErr.TransactionID, status.Code(err), submitErr)
} else if errors.As(err, &commitStatusErr) {
if errors.Is(err, context.DeadlineExceeded) {
fmt.Printf("Timeout waiting for transaction %s commit status: %s", commitStatusErr.TransactionID, commitStatusErr)
} else {
fmt.Printf("Error obtaining commit status for transaction %s with gRPC status %v: %s\n", commitStatusErr.TransactionID, status.Code(commitStatusErr), commitStatusErr)
}
} else if errors.As(err, &commitErr) {
fmt.Printf("Transaction %s failed to commit with status %d: %s\n", commitErr.TransactionID, int32(commitErr.Code), commitErr)
}
statusErr := status.Convert(err)
details := statusErr.Details()
if len(details) > 0 {
fmt.Println("Error Details:")
for _, detail := range details {
switch detail := detail.(type) {
case *gatewaypb.ErrorDetail:
fmt.Printf("- address: %s, mspId: %s, message: %s\n", detail.Address, detail.MspId, detail.Message)
}
}
}
}
var _ = Describe("e2e", func() {
Context("the e2e test with test network", func() {
It("should work", func(specCtx SpecContext) {
_, err := os.Stat("../fabric-samples/test-network")
if err != nil {
Skip("skip for unit test")
}
TLSCACert := "../fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt"
PrivKeyPath := "../fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/keystore/priv_sk"
SignCert := "../fabric-samples/test-network/organizations/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp/signcerts/Admin@org1.example.com-cert.pem"
peer1 := network.Node{
Addr: org1PeerAddress,
TLSCACert: TLSCACert,
}
err = peer1.LoadConfig()
Expect(err).NotTo(HaveOccurred())
peer1Connection, err := network.DialConnection(peer1)
Expect(err).NotTo(HaveOccurred())
cert, err := identity.ReadCertificate(SignCert)
Expect(err).NotTo(HaveOccurred())
priv, err := identity.ReadPrivateKey(PrivKeyPath)
Expect(err).NotTo(HaveOccurred())
org1MSP, err := identity.NewPrivateKeySigningIdentity(org1MspID, cert, priv)
Expect(err).NotTo(HaveOccurred())
TLSCACert = "../fabric-samples/test-network/organizations/peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt"
PrivKeyPath = "../fabric-samples/test-network/organizations/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/keystore/priv_sk"
SignCert = "../fabric-samples/test-network/organizations/peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp/signcerts/Admin@org2.example.com-cert.pem"
peer2 := network.Node{
Addr: org2PeerAddress,
TLSCACert: TLSCACert,
}
err = peer2.LoadConfig()
Expect(err).NotTo(HaveOccurred())
peer2Connection, err := network.DialConnection(peer2)
Expect(err).NotTo(HaveOccurred())
cert2, err := identity.ReadCertificate(SignCert)
Expect(err).NotTo(HaveOccurred())
priv2, err := identity.ReadPrivateKey(PrivKeyPath)
Expect(err).NotTo(HaveOccurred())
org2MSP, err := identity.NewPrivateKeySigningIdentity(org2MspID, cert2, priv2)
Expect(err).NotTo(HaveOccurred())
//genesis block
createChannel, ok := os.LookupEnv("CREATE_CHANNEL")
if createChannel == "create_channel" && ok {
var profile *genesisconfig.Profile
var err error
profile, err = genesisconfig.Load("ChannelUsingRaft", "./")
Expect(err).NotTo(HaveOccurred())
Expect(profile).ToNot(BeNil())
Expect(profile.Orderer.BatchSize.MaxMessageCount).To(Equal(uint32(10)))
IsBFT, check := os.LookupEnv("CONSENSUS")
if IsBFT == "BFT" && check {
profile, err = genesisconfig.Load("ChannelUsingBFT", "./bft")
Expect(err).NotTo(HaveOccurred())
Expect(profile).ToNot(BeNil())
Expect(profile.Orderer.BatchSize.MaxMessageCount).To(Equal(uint32(10)))
}
block, err := ConfigTxGen(profile, channelName)
Expect(err).NotTo(HaveOccurred())
Expect(block).ToNot(BeNil())
//create channel
var caFile, clientCert, clientKey, osnURL string
osnURL = "https://localhost:7053"
caFile = "../fabric-samples/test-network/organizations/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem"
clientCert = "../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.crt"
clientKey = "../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer.example.com/tls/server.key"
caCertPool := x509.NewCertPool()
caFilePEM, err := os.ReadFile(caFile)
caCertPool.AppendCertsFromPEM(caFilePEM)
Expect(err).NotTo(HaveOccurred())
tlsClientCert, err := tls.LoadX509KeyPair(clientCert, clientKey)
Expect(err).NotTo(HaveOccurred())
resp, err := channel.CreateChannel(osnURL, block, caCertPool, tlsClientCert)
Expect(err).NotTo(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
if IsBFT == "BFT" && check {
osnURLs := []string{"https://localhost:7055", "https://localhost:7057", "https://localhost:7059"}
clientCerts := []string{
"../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.crt",
"../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.crt",
"../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.crt",
}
clientKeys := []string{
"../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer2.example.com/tls/server.key",
"../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer3.example.com/tls/server.key",
"../fabric-samples/test-network/organizations/ordererOrganizations/example.com/orderers/orderer4.example.com/tls/server.key",
}
for i := 0; i < 3; i++ {
osnURL = osnURLs[i]
caFile = "../fabric-samples/test-network/organizations/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem"
clientCert = clientCerts[i]
clientKey = clientKeys[i]
caCertPool := x509.NewCertPool()
caFilePEM, err := os.ReadFile(caFile)
caCertPool.AppendCertsFromPEM(caFilePEM)
Expect(err).NotTo(HaveOccurred())
tlsClientCert, err := tls.LoadX509KeyPair(clientCert, clientKey)
Expect(err).NotTo(HaveOccurred())
resp, err := channel.CreateChannel(osnURL, block, caCertPool, tlsClientCert)
Expect(err).NotTo(HaveOccurred())
Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
}
}
//osnURL
order := network.Node{
Addr: "localhost:7050",
TLSCACert: clientCert,
}
err = order.LoadConfig()
Expect(err).NotTo(HaveOccurred())
ordererConnection, err := network.DialConnection(order)
Expect(err).NotTo(HaveOccurred())
ctx, cancel := context.WithTimeout(specCtx, 2*time.Minute)
defer cancel()
ordererBlock, err := channel.GetConfigBlockFromOrderer(ctx, ordererConnection, org1MSP, channelName, tlsClientCert)
Expect(err).NotTo(HaveOccurred())
Expect(ordererBlock).NotTo(BeNil())
//join peer1
err = channel.JoinChannel(specCtx, peer1Connection, org1MSP, block)
Expect(err).NotTo(HaveOccurred())
//join peer2
err = channel.JoinChannel(specCtx, peer2Connection, org2MSP, block)
Expect(err).NotTo(HaveOccurred())
}
// check peer join channel
peerChannelInfo, err := channel.ListChannelOnPeer(specCtx, peer1Connection, org1MSP)
Expect(err).NotTo(HaveOccurred())
Expect(peerChannelInfo[0].ChannelId).To(Equal(channelName))
// package chaincode as CCAAS
dummyConnection := chaincode.Connection{
Address: "{{.peername}}_basic:9999",
DialTimeout: "10s",
TLSRequired: false,
}
dummyMeta := chaincode.Metadata{
Type: "ccaas",
Label: "basic_1.0",
}
packageFileName := "basic-asset.tar.gz"
err = chaincode.PackageCCAAS(dummyConnection, dummyMeta, tmpDir, packageFileName)
Expect(err).NotTo(HaveOccurred())
packageFilePath := path.Join(tmpDir, packageFileName)
packageReader, err := os.Open(packageFilePath)
Expect(err).NotTo(HaveOccurred(), "open chaincode package file")
chaincodePackage, err := io.ReadAll(packageReader)
Expect(err).NotTo(HaveOccurred(), "read chaincode package")
packageID, err := chaincode.PackageID(bytes.NewReader(chaincodePackage))
Expect(err).NotTo(HaveOccurred(), "get chaincode package ID")
fmt.Println(packageID)
networkPeers := []*chaincode.Peer{
chaincode.NewPeer(peer1Connection, org1MSP),
chaincode.NewPeer(peer2Connection, org2MSP),
}
org1Gateway := chaincode.NewGateway(peer1Connection, org1MSP)
org2Gateway := chaincode.NewGateway(peer2Connection, org2MSP)
allOrgGateways := []*chaincode.Gateway{org1Gateway, org2Gateway}
// Install chaincode on each peer
runParallel(networkPeers, func(peer *chaincode.Peer) {
ctx, cancel := context.WithTimeout(specCtx, 2*time.Minute)
defer cancel()
result, err := peer.Install(ctx, bytes.NewReader(chaincodePackage))
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "chaincode install")
Expect(result.GetPackageId()).To(Equal(packageID), "install chaincode package ID")
Expect(result.GetLabel()).To(Equal(dummyMeta.Label), "install chaincode label")
})
// Query installed chaincode on each peer
runParallel(networkPeers, func(peer *chaincode.Peer) {
ctx, cancel := context.WithTimeout(specCtx, 30*time.Second)
defer cancel()
result, err := peer.QueryInstalled(ctx)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "query installed chaincode")
installedChaincodes := result.GetInstalledChaincodes()
Expect(installedChaincodes).To(HaveLen(1), "number of installed chaincodes")
Expect(installedChaincodes[0].GetPackageId()).To(Equal(packageID), "installed chaincode package ID")
Expect(installedChaincodes[0].GetLabel()).To(Equal(dummyMeta.Label), "installed chaincode label")
})
// Get installed chaincode package from each peer
runParallel(networkPeers, func(peer *chaincode.Peer) {
ctx, cancel := context.WithTimeout(specCtx, 30*time.Second)
defer cancel()
result, err := peer.GetInstalled(ctx, packageID)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "get installed chaincode package")
Expect(result).NotTo(BeEmpty())
})
time.Sleep(time.Duration(20) * time.Second)
PolicyStr := "AND ('Org1MSP.peer','Org2MSP.peer')"
applicationPolicy, err := chaincode.NewApplicationPolicy(PolicyStr, "")
Expect(err).NotTo(HaveOccurred())
chaincodeDef := &chaincode.Definition{
ChannelName: channelName,
PackageID: "",
Name: "basic",
Version: "1.0",
EndorsementPlugin: "",
ValidationPlugin: "",
Sequence: 1,
ApplicationPolicy: applicationPolicy,
InitRequired: false,
Collections: nil,
}
Expect(err).NotTo(HaveOccurred())
// Approve chaincode for each org
runParallel(allOrgGateways, func(gateway *chaincode.Gateway) {
ctx, cancel := context.WithTimeout(specCtx, 30*time.Second)
defer cancel()
err := gateway.Approve(ctx, chaincodeDef)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "approve chaincode for org %s", gateway.ClientIdentity().MspID())
})
// Query approved chaincode for each org
runParallel(allOrgGateways, func(gateway *chaincode.Gateway) {
ctx, cancel := context.WithTimeout(specCtx, 30*time.Second)
defer cancel()
result, err := gateway.QueryApproved(ctx, channelName, chaincodeDef.Name, chaincodeDef.Sequence)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "query approved chaincode for org %s", gateway.ClientIdentity().MspID())
Expect(result.GetVersion()).To(Equal(chaincodeDef.Version))
})
// Check chaincode commit readiness
readinessCtx, readinessCancel := context.WithTimeout(specCtx, 30*time.Second)
defer readinessCancel()
readinessResult, err := org1Gateway.CheckCommitReadiness(readinessCtx, chaincodeDef)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "check commit readiness")
Expect(readinessResult.GetApprovals()[org1MspID]).To(BeTrue())
Expect(readinessResult.GetApprovals()[org2MspID]).To(BeTrue())
time.Sleep(time.Duration(20) * time.Second)
// Commit chaincode
commitCtx, commitCancel := context.WithTimeout(specCtx, 30*time.Second)
defer commitCancel()
err = org1Gateway.Commit(commitCtx, chaincodeDef)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "commit chaincode")
// Query all committed chaincode
committedCtx, committedCancel := context.WithTimeout(specCtx, 30*time.Second)
defer committedCancel()
committedResult, err := org1Gateway.QueryCommitted(committedCtx, channelName)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "query all committed chaincodes")
committedChaincodes := committedResult.GetChaincodeDefinitions()
Expect(committedChaincodes).To(HaveLen(1), "number of committed chaincodes")
Expect(committedChaincodes[0].GetName()).To(Equal("basic"), "committed chaincode name")
Expect(committedChaincodes[0].GetSequence()).To(Equal(int64(1)), "committed chaincode sequence")
// Query named committed chaincode
committedWithNameCtx, committedWithNameCancel := context.WithTimeout(specCtx, 30*time.Second)
defer committedWithNameCancel()
committedWithNameResult, err := org1Gateway.QueryCommittedWithName(committedWithNameCtx, channelName, chaincodeDef.Name)
printGrpcError(err)
Expect(err).NotTo(HaveOccurred(), "query committed chaincode with name")
Expect(readinessResult.GetApprovals()[org1MspID]).To(BeTrue())
Expect(readinessResult.GetApprovals()[org2MspID]).To(BeTrue())
Expect(committedWithNameResult.GetSequence()).To(Equal(chaincodeDef.Sequence), "committed chaincode sequence")
f, _ := os.Create("PackageID")
_, err = io.WriteString(f, packageID)
Expect(err).NotTo(HaveOccurred())
// check discovery as query peer membership
discoveryPeer := discovery.NewPeer(peer1Connection, org1MSP)
peerMembershipCtx, cancel := context.WithTimeout(specCtx, 30*time.Second)
defer cancel()
peerMembershipResult, err := discoveryPeer.PeerMembershipQuery(peerMembershipCtx, channelName, nil)
Expect(err).NotTo(HaveOccurred())
Expect(peerMembershipResult.GetPeersByOrg()[org1MspID].GetPeers()).To(HaveLen(1))
Expect(peerMembershipResult.GetPeersByOrg()[org2MspID].GetPeers()).To(HaveLen(1))
})
})
})