forked from hyperledger/fabric
/
commit.go
311 lines (270 loc) · 8.77 KB
/
commit.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package chaincode
import (
"context"
"crypto/tls"
"fmt"
"time"
"github.com/golang/protobuf/proto"
cb "github.com/hyperledger/fabric-protos-go/common"
pb "github.com/hyperledger/fabric-protos-go/peer"
lb "github.com/hyperledger/fabric-protos-go/peer/lifecycle"
"github.com/hyperledger/fabric/bccsp"
"github.com/hyperledger/fabric/internal/peer/chaincode"
"github.com/hyperledger/fabric/internal/peer/common"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Committer holds the dependencies needed to commit
// a chaincode
type Committer struct {
Certificate tls.Certificate
Command *cobra.Command
BroadcastClient common.BroadcastClient
EndorserClients []EndorserClient
DeliverClients []pb.DeliverClient
Input *CommitInput
Signer Signer
}
// CommitInput holds all of the input parameters for committing a
// chaincode definition. ValidationParameter bytes is the (marshalled)
// endorsement policy when using the default endorsement and validation
// plugins
type CommitInput struct {
ChannelID string
Name string
Version string
Hash []byte
Sequence int64
EndorsementPlugin string
ValidationPlugin string
ValidationParameterBytes []byte
CollectionConfigPackage *pb.CollectionConfigPackage
InitRequired bool
PeerAddresses []string
WaitForEvent bool
WaitForEventTimeout time.Duration
TxID string
}
// Validate the input for a CommitChaincodeDefinition proposal
func (c *CommitInput) Validate() error {
if c.ChannelID == "" {
return errors.New("The required parameter 'channelID' is empty. Rerun the command with -C flag")
}
if c.Name == "" {
return errors.New("The required parameter 'name' is empty. Rerun the command with -n flag")
}
if c.Version == "" {
return errors.New("The required parameter 'version' is empty. Rerun the command with -v flag")
}
if c.Sequence == 0 {
return errors.New("The required parameter 'sequence' is empty. Rerun the command with --sequence flag")
}
return nil
}
// CommitCmd returns the cobra command for chaincode Commit
func CommitCmd(c *Committer, cryptoProvider bccsp.BCCSP) *cobra.Command {
chaincodeCommitCmd := &cobra.Command{
Use: "commit",
Short: fmt.Sprintf("Commit the chaincode definition on the channel."),
Long: fmt.Sprintf("Commit the chaincode definition on the channel."),
RunE: func(cmd *cobra.Command, args []string) error {
if c == nil {
// set input from CLI flags
input, err := c.createInput()
if err != nil {
return err
}
ccInput := &ClientConnectionsInput{
CommandName: cmd.Name(),
EndorserRequired: true,
OrdererRequired: true,
ChannelID: channelID,
PeerAddresses: peerAddresses,
TLSRootCertFiles: tlsRootCertFiles,
ConnectionProfilePath: connectionProfilePath,
TLSEnabled: viper.GetBool("peer.tls.enabled"),
}
cc, err := NewClientConnections(ccInput, cryptoProvider)
if err != nil {
return err
}
endorserClients := make([]EndorserClient, len(cc.EndorserClients))
for i, e := range cc.EndorserClients {
endorserClients[i] = e
}
c = &Committer{
Command: cmd,
Input: input,
Certificate: cc.Certificate,
BroadcastClient: cc.BroadcastClient,
DeliverClients: cc.DeliverClients,
EndorserClients: endorserClients,
Signer: cc.Signer,
}
}
return c.Commit()
},
}
flagList := []string{
"channelID",
"name",
"version",
"sequence",
"endorsement-plugin",
"validation-plugin",
"signature-policy",
"channel-config-policy",
"init-required",
"collections-config",
"peerAddresses",
"tlsRootCertFiles",
"connectionProfile",
"waitForEvent",
"waitForEventTimeout",
}
attachFlags(chaincodeCommitCmd, flagList)
return chaincodeCommitCmd
}
// Commit submits a CommitChaincodeDefinition proposal
func (c *Committer) Commit() error {
err := c.Input.Validate()
if err != nil {
return err
}
if c.Command != nil {
// Parsing of the command line is done so silence cmd usage
c.Command.SilenceUsage = true
}
proposal, txID, err := c.createProposal(c.Input.TxID)
if err != nil {
return errors.WithMessage(err, "failed to create proposal")
}
signedProposal, err := signProposal(proposal, c.Signer)
if err != nil {
return errors.WithMessage(err, "failed to create signed proposal")
}
var responses []*pb.ProposalResponse
for _, endorser := range c.EndorserClients {
proposalResponse, err := endorser.ProcessProposal(context.Background(), signedProposal)
if err != nil {
return errors.WithMessage(err, "failed to endorse proposal")
}
responses = append(responses, proposalResponse)
}
if len(responses) == 0 {
// this should only be empty due to a programming bug
return errors.New("no proposal responses received")
}
// all responses will be checked when the signed transaction is created.
// for now, just set this so we check the first response's status
proposalResponse := responses[0]
if proposalResponse == nil {
return errors.New("received nil proposal response")
}
if proposalResponse.Response == nil {
return errors.New("received proposal response with nil response")
}
if proposalResponse.Response.Status != int32(cb.Status_SUCCESS) {
return errors.Errorf("proposal failed with status: %d - %s", proposalResponse.Response.Status, proposalResponse.Response.Message)
}
// assemble a signed transaction (it's an Envelope message)
env, err := protoutil.CreateSignedTx(proposal, c.Signer, responses...)
if err != nil {
return errors.WithMessage(err, "failed to create signed transaction")
}
var dg *chaincode.DeliverGroup
var ctx context.Context
if c.Input.WaitForEvent {
var cancelFunc context.CancelFunc
ctx, cancelFunc = context.WithTimeout(context.Background(), c.Input.WaitForEventTimeout)
defer cancelFunc()
dg = chaincode.NewDeliverGroup(
c.DeliverClients,
c.Input.PeerAddresses,
c.Signer,
c.Certificate,
c.Input.ChannelID,
txID,
)
// connect to deliver service on all peers
err := dg.Connect(ctx)
if err != nil {
return err
}
}
if err = c.BroadcastClient.Send(env); err != nil {
return errors.WithMessage(err, "failed to send transaction")
}
if dg != nil && ctx != nil {
// wait for event that contains the txID from all peers
err = dg.Wait(ctx)
if err != nil {
return err
}
}
return err
}
// createInput creates the input struct based on the CLI flags
func (c *Committer) createInput() (*CommitInput, error) {
policyBytes, err := createPolicyBytes(signaturePolicy, channelConfigPolicy)
if err != nil {
return nil, err
}
ccp, err := createCollectionConfigPackage(collectionsConfigFile)
if err != nil {
return nil, err
}
input := &CommitInput{
ChannelID: channelID,
Name: chaincodeName,
Version: chaincodeVersion,
Sequence: int64(sequence),
EndorsementPlugin: endorsementPlugin,
ValidationPlugin: validationPlugin,
ValidationParameterBytes: policyBytes,
InitRequired: initRequired,
CollectionConfigPackage: ccp,
PeerAddresses: peerAddresses,
WaitForEvent: waitForEvent,
WaitForEventTimeout: waitForEventTimeout,
}
return input, nil
}
func (c *Committer) createProposal(inputTxID string) (proposal *pb.Proposal, txID string, err error) {
args := &lb.CommitChaincodeDefinitionArgs{
Name: c.Input.Name,
Version: c.Input.Version,
Sequence: c.Input.Sequence,
EndorsementPlugin: c.Input.EndorsementPlugin,
ValidationPlugin: c.Input.ValidationPlugin,
ValidationParameter: c.Input.ValidationParameterBytes,
InitRequired: c.Input.InitRequired,
Collections: c.Input.CollectionConfigPackage,
}
argsBytes, err := proto.Marshal(args)
if err != nil {
return nil, "", err
}
ccInput := &pb.ChaincodeInput{Args: [][]byte{[]byte(commitFuncName), argsBytes}}
cis := &pb.ChaincodeInvocationSpec{
ChaincodeSpec: &pb.ChaincodeSpec{
ChaincodeId: &pb.ChaincodeID{Name: lifecycleName},
Input: ccInput,
},
}
creatorBytes, err := c.Signer.Serialize()
if err != nil {
return nil, "", errors.WithMessage(err, "failed to serialize identity")
}
proposal, txID, err = protoutil.CreateChaincodeProposalWithTxIDAndTransient(cb.HeaderType_ENDORSER_TRANSACTION, c.Input.ChannelID, cis, creatorBytes, inputTxID, nil)
if err != nil {
return nil, "", errors.WithMessage(err, "failed to create ChaincodeInvocationSpec proposal")
}
return proposal, txID, nil
}