/
instantiatechaincode.go
522 lines (482 loc) · 18.2 KB
/
instantiatechaincode.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
package operations
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/hyperledger/fabric-test/tools/operator/connectionprofile"
"github.com/hyperledger/fabric-test/tools/operator/logger"
"github.com/hyperledger/fabric-test/tools/operator/networkclient"
"github.com/hyperledger/fabric-test/tools/operator/paths"
"github.com/hyperledger/fabric-test/tools/operator/testclient/inputStructs"
yaml "gopkg.in/yaml.v2"
)
//InstantiateCCUIObject --
type InstantiateCCUIObject struct {
SDK string `json:"sdk,omitempty"`
TransType string `json:"transType,omitempty"`
TLS string `json:"TLS,omitempty"`
ChainCodeID string `json:"chaincodeID,omitempty"`
ChainCodeVer string `json:"chaincodeVer,omitempty"`
OrgConnProfilePaths []inputStructs.Organization `json:"orgConnProfilePaths,omitempty"`
ChannelOpt ChannelOptions `json:"channelOpt,omitempty"`
DeployOpt InstantiateDeployOptions `json:"deploy,omitempty"`
TimeOutOpt TimeOutOptions `json:"timeoutOpt,omitempty"`
Sequence string `json:"sequence,omitempty"`
TargetPeers []string `json:"targetPeers,omitempty"`
}
//InstantiateDeployOptions --
type InstantiateDeployOptions struct {
Function string `json:"fcn,omitempty"`
Arguments []string `json:"args,omitempty"`
Endorsement *EndorsementPolicy `json:"endorsement,omitempty"`
CollectionsConfigPath string `json:"collectionsConfigPath,omitempty"`
}
//TimeOutOptions --
type TimeOutOptions struct {
PreConfig string `json:"preConfig,omitempty"`
Request string `json:"request,omitempty"`
}
//EndorsementPolicy --
type EndorsementPolicy struct {
Identities []Identity `json:"identities,omitempty"`
Policy map[string][]Policy `json:"policy,omitempty"`
SignaturePolicy string `json:"signaturePolicy,omitempty"`
}
//Policy --
type Policy struct {
SignedBy int `json:"signed-by"`
}
//Identity --
type Identity struct {
Role struct {
Name string `json:"name,omitempty"`
MSPID string `json:"mspId,omitempty"`
} `json:"role,omitempty"`
}
//ConnProfileOptions --
type ConnProfileOptions struct {
Organizations map[string]struct {
MSPID string `yaml:"mspid,omitempty"`
Peers []string `yaml:"peers,omitempty"`
} `yaml:"organizations,omitempty"`
Peers map[string]struct {
URL string `yaml:"url,omitempty"`
MetricsURL string `yaml:"metricsURL,omitempty"`
} `yaml:"peers,omitempty"`
Orderers map[string]struct {
URL string `yaml:"url,omitempty"`
MetricsURL string `yaml:"metricsURL,omitempty"`
}
Channels map[string]struct {
Orderers []string `yaml:"orderers,omitempty"`
Peers []string `yaml:"peers,omitempty"`
}
}
//InstalledCC --
type InstalledCC struct {
CC []struct {
PackageID string `json:"package_id,omitempty"`
Label string `json:"label,omitempty"`
} `json:"installed_chaincodes,omitempty"`
}
//InstantiateCC -- To instantiate/upgrade chaincode with the objects created and to update connection profile
func (i InstantiateCCUIObject) InstantiateCC(config inputStructs.Config, tls, action string) error {
var instantiateCCObjects []InstantiateCCUIObject
configObjects := config.InstantiateCC
var ccConfigObjects []interface{}
if action == "upgrade" {
configObjects = config.UpgradeCC
}
// print action (in bold) and input
fmt.Printf("\033[1m\nAction:%s\nInput:\033[0m\n%s\n", action, spew.Sdump(configObjects))
for index := 0; index < len(configObjects); index++ {
ccObjects, err := i.generateInstantiateCCObjects(configObjects[index], config.Organizations, tls, action)
if err != nil {
return err
}
ccConfigObjects = append(ccConfigObjects, &configObjects[index])
instantiateCCObjects = append(instantiateCCObjects, ccObjects...)
}
err := i.instantiateCC(instantiateCCObjects)
if err != nil {
return err
}
var connProfileObject connectionprofile.ConnProfile
err = connProfileObject.UpdateConnectionProfiles(ccConfigObjects, config.Organizations, action)
if err != nil {
return err
}
return nil
}
//generateInstantiateCCObjects -- To generate chaincode objects for instantiation/upgrade
func (i InstantiateCCUIObject) generateInstantiateCCObjects(ccObject inputStructs.InstantiateCC, organizations []inputStructs.Organization, tls, action string) ([]InstantiateCCUIObject, error) {
var instantiateCCObjects []InstantiateCCUIObject
var err error
if ccObject.ChannelPrefix != "" && ccObject.NumChannels > 0 {
instantiateCCObjects, err = i.createInstantiateCCObjectIfChanPrefix(ccObject, organizations, tls, action)
if err != nil {
return instantiateCCObjects, err
}
return instantiateCCObjects, nil
}
orgNames := strings.Split(ccObject.Organizations, ",")
instantiateCCObjects, err = i.createInstantiateCCObjects(orgNames, ccObject.ChannelName, tls, action, organizations, ccObject)
if err != nil {
return instantiateCCObjects, err
}
return instantiateCCObjects, nil
}
//createInstantiateCCObjects -- To create chaincode objects for instantiation/upgrade per channel
func (i InstantiateCCUIObject) createInstantiateCCObjects(orgNames []string, channelName, tls, action string, orgConnectionProfilePaths []inputStructs.Organization, ccObject inputStructs.InstantiateCC) ([]InstantiateCCUIObject, error) {
var instantiateCCObjects []InstantiateCCUIObject
targetPeers := strings.Split(ccObject.TargetPeers, ",")
i = InstantiateCCUIObject{
SDK: ccObject.SDK,
TransType: action,
TLS: tls,
OrgConnProfilePaths: orgConnectionProfilePaths,
ChainCodeID: ccObject.ChainCodeName,
ChainCodeVer: ccObject.ChainCodeVersion,
TargetPeers: targetPeers,
Sequence: ccObject.Sequence,
ChannelOpt: ChannelOptions{
Name: channelName,
OrgName: orgNames,
},
DeployOpt: InstantiateDeployOptions{
Function: ccObject.CCFcn,
Arguments: strings.Split(ccObject.CCFcnArgs, ","),
},
TimeOutOpt: TimeOutOptions{
PreConfig: ccObject.TimeOutOpt.PreConfig,
Request: ccObject.TimeOutOpt.Request,
},
}
if ccObject.TimeOutOpt.PreConfig == "" {
i.TimeOutOpt = TimeOutOptions{PreConfig: "600000", Request: "600000"}
}
if ccObject.EndorsementPolicy != "" {
if ccObject.SDK != "cli" || strings.Contains(ccObject.EndorsementPolicy, "of") {
endorsementPolicy, err := i.getEndorsementPolicy(orgConnectionProfilePaths, ccObject.EndorsementPolicy)
if err != nil {
logger.ERROR("Failed to get the endorsement policy")
return instantiateCCObjects, err
}
i.DeployOpt.Endorsement = endorsementPolicy
} else {
endorsementPolicy := &EndorsementPolicy{SignaturePolicy: ccObject.EndorsementPolicy}
i.DeployOpt.Endorsement = endorsementPolicy
}
}
if ccObject.CollectionPath != "" {
i.DeployOpt.CollectionsConfigPath = ccObject.CollectionPath
}
instantiateCCObjects = append(instantiateCCObjects, i)
return instantiateCCObjects, nil
}
//createInstantiateCCObjectIfChanPrefix -- To create chaincode objects if channel prefix and number of channels are given
func (i InstantiateCCUIObject) createInstantiateCCObjectIfChanPrefix(ccObject inputStructs.InstantiateCC, organizations []inputStructs.Organization, tls, action string) ([]InstantiateCCUIObject, error) {
var instantiateCCObjects []InstantiateCCUIObject
var channelName string
for j := 0; j < ccObject.NumChannels; j++ {
channelName = fmt.Sprintf("%s%s", ccObject.ChannelPrefix, strconv.Itoa(j))
orgNames := strings.Split(ccObject.Organizations, ",")
ccObjects, err := i.createInstantiateCCObjects(orgNames, channelName, tls, action, organizations, ccObject)
if err != nil {
return instantiateCCObjects, err
}
instantiateCCObjects = append(instantiateCCObjects, ccObjects...)
}
return instantiateCCObjects, nil
}
//getEndorsementPolicy -- To get the endorsement policy
func (i InstantiateCCUIObject) getEndorsementPolicy(organizations []inputStructs.Organization, policy string) (*EndorsementPolicy, error) {
var endorsementPolicy *EndorsementPolicy
var identities []Identity
var policies []Policy
var identity Identity
args := strings.Split(policy, "(")
orgs := args[len(args)-1]
orgs = orgs[:len(orgs)-1]
orgNames := strings.Split(orgs, ",")
for _, orgName := range orgNames {
orgName = strings.TrimSpace(orgName)
connProfilePath := paths.GetConnProfilePath([]string{orgName}, organizations)
connProfConfig, err := ConnProfileInformationForOrg(connProfilePath, orgName)
if err != nil {
return endorsementPolicy, err
}
mspID := connProfConfig.Organizations[orgName].MSPID
identity.Role.Name = "member"
identity.Role.MSPID = mspID
identities = append(identities, identity)
}
numPolicies, err := strconv.Atoi(args[0][0:1])
if err != nil {
logger.ERROR("Failed to convert string to integer")
return endorsementPolicy, err
}
key := fmt.Sprintf("%d-of", numPolicies)
for i := 0; i < len(orgNames); i++ {
policy := Policy{SignedBy: i}
policies = append(policies, policy)
}
policyMap := make(map[string][]Policy)
policyMap[key] = policies
endorsementPolicy = &EndorsementPolicy{Identities: identities, Policy: policyMap}
return endorsementPolicy, nil
}
//ConnProfileInformationForOrg -- To get the MSP ID for an organization
func ConnProfileInformationForOrg(connProfilePath, orgName string) (ConnProfileOptions, error) {
var config ConnProfileOptions
if !(strings.HasSuffix(connProfilePath, "yaml") || strings.HasSuffix(connProfilePath, "yml")) {
files, err := ioutil.ReadDir(connProfilePath)
if err != nil {
return config, err
}
for _, file := range files {
if strings.Contains(file.Name(), orgName) {
connProfilePath = paths.JoinPath(connProfilePath, file.Name())
break
}
}
}
yamlFile, err := ioutil.ReadFile(connProfilePath)
if err != nil {
logger.ERROR("Failed to read connectionprofile to get MSPID ")
return config, err
}
err = yaml.Unmarshal(yamlFile, &config)
if err != nil {
logger.ERROR("Failed to create ConnProfileOptions object")
return config, err
}
return config, nil
}
func fetchOrdererInformation(currentDir string) ([]string, error) {
files, err := ioutil.ReadDir(fmt.Sprintf("%s/crypto-config/ordererOrganizations/", currentDir))
if err != nil {
logger.ERROR("failed opening directory")
return nil, err
}
ordererDirectory, err := ioutil.ReadDir(fmt.Sprintf("%s/crypto-config/ordererOrganizations/%s/orderers/", currentDir, files[0].Name()))
if err != nil {
logger.ERROR("failed opening orderer directory")
return nil, err
}
ordererName := strings.Split(ordererDirectory[0].Name(), ".")
return ordererName, nil
}
//queryInstalledusingCLI -- querying installed cc using cli
func (i InstantiateCCUIObject) queryInstalledusingCLI(orgName, peerName, peerAddress, TLS string) (InstalledCC, error) {
var queryInstalled InstalledCC
currentDir, err := paths.GetCurrentDir()
if err != nil {
return queryInstalled, err
}
args := []string{"lifecycle",
"chaincode",
"queryinstalled",
"--peerAddresses", peerAddress,
"--tlsRootCertFiles", fmt.Sprintf("%s/crypto-config/peerOrganizations/%s/peers/%s.%s/tls/ca.crt", currentDir, orgName, peerName, orgName),
"--output",
"json"}
if TLS == "clientauth" {
args = append(args, "--tls")
}
installedCC, err := networkclient.ExecuteCommand("peer", args, true)
if err != nil {
return queryInstalled, err
}
err = json.Unmarshal([]byte(installedCC), &queryInstalled)
if err != nil {
return queryInstalled, err
}
return queryInstalled, nil
}
//approveCCusingCLI -- approving cc for organization using CLI
func (i InstantiateCCUIObject) approveCCusingCLI(instantiateObject InstantiateCCUIObject) error {
var packageID string
for _, orgName := range instantiateObject.ChannelOpt.OrgName {
currentDir, err := paths.GetCurrentDir()
if err != nil {
return err
}
orgName = strings.TrimSpace(orgName)
connProfilePath := paths.GetConnProfilePath([]string{orgName}, instantiateObject.OrgConnProfilePaths)
connProfConfig, err := ConnProfileInformationForOrg(connProfilePath, orgName)
if err != nil {
return err
}
ordererName, err := fetchOrdererInformation(currentDir)
if err != nil {
return err
}
ordererURL, err := url.Parse(connProfConfig.Orderers[ordererName[0]].URL)
if err != nil {
logger.ERROR("Failed to get orderer url from connection profile")
return err
}
ordererAddress := ordererURL.Host
args := []string{
"lifecycle",
"chaincode",
"approveformyorg",
"--channelID", instantiateObject.ChannelOpt.Name,
"--name", instantiateObject.ChainCodeID,
"--version", instantiateObject.ChainCodeVer,
"--sequence", instantiateObject.Sequence,
"--waitForEvent",
"--orderer", ordererAddress,
"--cafile", fmt.Sprintf("%s/crypto-config/ordererOrganizations/%s/orderers/%s.%s/tls/ca.crt", currentDir, ordererName[1], ordererName[0], ordererName[1]),
// "--connectionProfile",
// instantiateObject.ConnProfilePath,
}
for _, peerName := range instantiateObject.TargetPeers {
peerOrgName := strings.Split(peerName, "-")
if peerOrgName[1] == orgName {
peerURL, err := url.Parse(connProfConfig.Peers[strings.TrimSpace(peerName)].URL)
if err != nil {
logger.ERROR("Failed to get peer url from connection profile")
return err
}
peerAddress := peerURL.Host
err = SetEnvForCLI(orgName, peerName, connProfilePath, instantiateObject.TLS, currentDir)
if err != nil {
return err
}
queryInstalled, _ := i.queryInstalledusingCLI(orgName, peerName, peerAddress, instantiateObject.TLS)
for j := 0; j < len(queryInstalled.CC); j++ {
if queryInstalled.CC[j].Label == fmt.Sprintf("%s_%s", instantiateObject.ChainCodeID, instantiateObject.ChainCodeVer) {
packageID = queryInstalled.CC[j].PackageID
break
}
}
args = append(args,
"--peerAddresses", peerAddress,
"--tlsRootCertFiles", fmt.Sprintf("%s/crypto-config/peerOrganizations/%s/peers/%s.%s/tls/ca.crt", currentDir, orgName, peerName, orgName),
)
}
}
args = append(args, "--package-id", packageID)
if instantiateObject.TLS == "clientauth" {
args = append(args, "--tls")
}
if instantiateObject.DeployOpt.Endorsement != nil && instantiateObject.SDK == "cli" {
args = append(args, "--signature-policy", instantiateObject.DeployOpt.Endorsement.SignaturePolicy)
}
if instantiateObject.DeployOpt.CollectionsConfigPath != "" {
args = append(args, "--collections-config", instantiateObject.DeployOpt.CollectionsConfigPath)
}
_, err = networkclient.ExecuteCommand("peer", args, true)
if err != nil {
return err
}
}
return nil
}
//commitCCusingCLI -- committing cc using CLI
func (i InstantiateCCUIObject) commitCCusingCLI(instantiateObject InstantiateCCUIObject) error {
ordererOrgName := instantiateObject.ChannelOpt.OrgName[0]
ordererOrgName = strings.TrimSpace(ordererOrgName)
ordererConnProfilePath := paths.GetConnProfilePath([]string{ordererOrgName}, instantiateObject.OrgConnProfilePaths)
ordererConnProfConfig, err := ConnProfileInformationForOrg(ordererConnProfilePath, ordererOrgName)
if err != nil {
return err
}
currentDir, err := paths.GetCurrentDir()
if err != nil {
return err
}
ordererName, err := fetchOrdererInformation(currentDir)
if err != nil {
return err
}
ordererURL, err := url.Parse(ordererConnProfConfig.Orderers[ordererName[0]].URL)
if err != nil {
logger.ERROR("Failed to get orderer url from connection profile")
return err
}
ordererAddress := ordererURL.Host
args := []string{"lifecycle",
"chaincode",
"commit",
"--channelID", instantiateObject.ChannelOpt.Name,
"--name", instantiateObject.ChainCodeID,
"--version", instantiateObject.ChainCodeVer,
"--sequence", instantiateObject.Sequence,
"--waitForEvent",
"--orderer", ordererAddress,
"--cafile", fmt.Sprintf("%s/crypto-config/ordererOrganizations/%s/orderers/%s.%s/tls/ca.crt", currentDir, ordererName[1], ordererName[0], ordererName[1]),
// "--connectionProfile",
// instantiateObject.ConnProfilePath,
}
for _, peerName := range instantiateObject.TargetPeers {
peerOrgName := strings.Split(peerName, "-")[1]
connProfilePath := paths.GetConnProfilePath([]string{peerOrgName}, instantiateObject.OrgConnProfilePaths)
connProfConfig, err := ConnProfileInformationForOrg(connProfilePath, peerOrgName)
if err != nil {
return err
}
peerURL, err := url.Parse(connProfConfig.Peers[peerName].URL)
if err != nil {
logger.ERROR("Failed to get peer url from connection profile")
return err
}
peerAddress := peerURL.Host
args = append(args,
"--peerAddresses", peerAddress,
"--tlsRootCertFiles", fmt.Sprintf("%s/crypto-config/peerOrganizations/%s/peers/%s.%s/tls/ca.crt", currentDir, peerOrgName, peerName, peerOrgName),
)
}
if instantiateObject.TLS == "clientauth" {
args = append(args, "--tls")
}
if instantiateObject.DeployOpt.Endorsement != nil && instantiateObject.SDK == "cli" {
args = append(args, "--signature-policy", instantiateObject.DeployOpt.Endorsement.SignaturePolicy)
}
if instantiateObject.DeployOpt.CollectionsConfigPath != "" {
args = append(args, "--collections-config", instantiateObject.DeployOpt.CollectionsConfigPath)
}
err = SetEnvForCLI(ordererOrgName, instantiateObject.TargetPeers[0], ordererConnProfilePath, instantiateObject.TLS, currentDir)
if err != nil {
return err
}
_, err = networkclient.ExecuteCommand("peer", args, true)
return err
}
//instantiateCC -- To instantiate chaincode
func (i InstantiateCCUIObject) instantiateCC(instantiateChainCodeObjects []InstantiateCCUIObject) error {
var err error
var jsonObject []byte
pteMainPath := paths.PTEPath()
for j := 0; j < len(instantiateChainCodeObjects); j++ {
if instantiateChainCodeObjects[j].SDK == "cli" {
err = i.approveCCusingCLI(instantiateChainCodeObjects[j])
if err != nil {
return err
}
err = i.commitCCusingCLI(instantiateChainCodeObjects[j])
if err != nil {
return err
}
} else {
jsonObject, err = json.Marshal(instantiateChainCodeObjects[j])
if err != nil {
return err
}
startTime := fmt.Sprintf("%s", time.Now())
args := []string{pteMainPath, strconv.Itoa(j), string(jsonObject), startTime}
_, err = networkclient.ExecuteCommand("node", args, true)
if err != nil {
return err
}
}
}
return err
}