/
transasction.go
726 lines (625 loc) · 18.2 KB
/
transasction.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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package transaction
import (
"bytes"
"encoding/base64"
"encoding/json"
"github.com/hyperledger-labs/fabric-smart-client/platform/fabric/core/generic/fabricutils"
"github.com/hyperledger-labs/fabric-smart-client/pkg/utils/proto"
"github.com/hyperledger-labs/fabric-smart-client/platform/fabric/driver"
view2 "github.com/hyperledger-labs/fabric-smart-client/platform/view"
"github.com/hyperledger-labs/fabric-smart-client/platform/view/view"
pcommon "github.com/hyperledger/fabric-protos-go/common"
pb "github.com/hyperledger/fabric-protos-go/peer"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
"go.uber.org/zap/zapcore"
)
type Proposal struct {
p *pb.Proposal
}
func (p *Proposal) Header() []byte {
return p.p.Header
}
func (p *Proposal) Payload() []byte {
return p.p.Payload
}
type SignedProposal struct {
s *pb.SignedProposal
up *UnpackedProposal
}
func newSignedProposal(s *pb.SignedProposal) (*SignedProposal, error) {
logger.Debugf("new signed proposal with...")
up, err := UnpackSignedProposal(s)
if err != nil {
return nil, err
}
logger.Debugf("new signed proposal with [%v]", up.ProposalHash)
return &SignedProposal{
s: s,
up: up,
}, nil
}
func (p *SignedProposal) ProposalBytes() []byte {
return p.s.ProposalBytes
}
func (p *SignedProposal) Signature() []byte {
return p.s.Signature
}
func (p *SignedProposal) ProposalHash() []byte {
return p.up.ProposalHash
}
func (p *SignedProposal) ChaincodeName() string {
return p.up.ChaincodeName
}
func (p *SignedProposal) ChaincodeVersion() string {
return p.up.ChaincodeVersion
}
type Transaction struct {
sp view2.ServiceProvider
fns driver.FabricNetworkService
rwset driver.RWSet
channel driver.Channel
signedProposal *SignedProposal
proposalResponse *pb.ProposalResponse
TCreator view.Identity
TNonce []byte
TTxID string
TNetwork string
TChannel string
TChaincode string
TChaincodeVersion string
TFunction string
TParameters [][]byte
RWSet []byte
TTransient driver.TransientMap
TProposal *pb.Proposal
TSignedProposal *pb.SignedProposal
TProposalResponses []*pb.ProposalResponse
}
func (t *Transaction) Creator() view.Identity {
return t.TCreator
}
func (t *Transaction) Nonce() []byte {
return t.TNonce
}
func (t *Transaction) ID() string {
return t.TTxID
}
func (t *Transaction) Network() string {
return t.TNetwork
}
func (t *Transaction) Channel() string {
return t.TChannel
}
func (t *Transaction) Function() string {
return t.TFunction
}
func (t *Transaction) Parameters() [][]byte {
return t.TParameters
}
func (t *Transaction) FunctionAndParameters() (string, []string) {
var params []string
for _, parameter := range t.Parameters() {
params = append(params, string(parameter))
}
return t.Function(), params
}
func (t *Transaction) Chaincode() string {
return t.TChaincode
}
func (t *Transaction) ChaincodeVersion() string {
return t.TChaincodeVersion
}
func (t *Transaction) Results() ([]byte, error) {
upr, err := UnpackProposalResponse(t.TProposalResponses[0])
if err != nil {
return nil, err
}
return upr.Results(), nil
}
func (t *Transaction) From(tx driver.Transaction) (err error) {
payload := tx.(*Transaction)
t.TCreator = payload.TCreator
t.TNonce = payload.TNonce
t.TTxID = payload.TTxID
t.TCreator = payload.TCreator
t.TNetwork = payload.TNetwork
t.TChannel = payload.TChannel
t.TChaincode = payload.TChaincode
t.TChaincodeVersion = payload.TChaincodeVersion
t.TFunction = payload.TFunction
t.TParameters = payload.TParameters
t.RWSet = payload.RWSet
t.TProposal = payload.TProposal
t.TSignedProposal = payload.TSignedProposal
if payload.TSignedProposal != nil {
t.signedProposal, err = newSignedProposal(payload.TSignedProposal)
if err != nil {
return
}
}
t.TProposalResponses = payload.TProposalResponses
t.TTransient = payload.TTransient
return
}
func (t *Transaction) SetFromBytes(raw []byte) error {
err := json.Unmarshal(raw, t)
if err != nil {
return errors.Wrapf(err, "SetFromBytes: failed unmarshalling payload [%s]", string(raw))
}
logger.Debugf("set transient [%v]", t.TTransient)
if t.TSignedProposal != nil {
// TODO: check the current payload is compatible with the content of the signed proposal
up, err := UnpackSignedProposal(t.TSignedProposal)
if err != nil {
return errors.Wrapf(err, "SetFromBytes: failed unpacking proposal [%s]", string(raw))
}
t.TTxID = up.TxID()
t.TNonce = up.Nonce()
t.TChaincode = up.ChaincodeName
t.TChaincodeVersion = up.ChaincodeVersion
t.TFunction = string(up.Input.Args[0])
t.TParameters = [][]byte{}
for i := 1; i < len(up.Input.Args); i++ {
t.TParameters = append(t.TParameters, up.Input.Args[i])
}
t.TChannel = up.ChannelHeader.ChannelId
t.TProposal = up.Proposal
if len(t.TCreator) == 0 {
t.TCreator = up.SignatureHeader.Creator
}
t.signedProposal, err = newSignedProposal(t.TSignedProposal)
if err != nil {
return err
}
}
// Set the channel
ch, err := t.fns.Channel(t.Channel())
if err != nil {
return err
}
t.channel = ch
return nil
}
func (t *Transaction) SetFromEnvelopeBytes(raw []byte) error {
// TODO: check the current payload is compatible with the content of the signed proposal
upe, _, err := UnpackEnvelopeFromBytes(raw)
if err != nil {
return err
}
t.TTxID = upe.TxID
t.TNonce = upe.Nonce
t.TChannel = upe.Ch
t.TChaincode = upe.ChaincodeName
t.TChaincodeVersion = upe.ChaincodeVersion
t.TFunction = string(upe.Input.Args[0])
t.TParameters = [][]byte{}
for i := 1; i < len(upe.Input.Args); i++ {
t.TParameters = append(t.TParameters, upe.Input.Args[i])
}
t.TChannel = upe.ChannelHeader.ChannelId
if len(t.TCreator) == 0 {
t.TCreator = upe.SignatureHeader.Creator
}
t.TProposalResponses = upe.ProposalResponses
// Set the channel
ch, err := t.fns.Channel(t.Channel())
if err != nil {
return err
}
t.channel = ch
return nil
}
func (t *Transaction) Proposal() driver.Proposal {
return &Proposal{
p: t.TProposal,
}
}
func (t *Transaction) SignedProposal() driver.SignedProposal {
if t.signedProposal == nil {
return nil
}
return t.signedProposal
}
func (t *Transaction) SetProposal(chaincode string, version string, function string, params ...string) {
t.TChaincode = chaincode
t.TChaincodeVersion = version
t.TFunction = function
t.TParameters = [][]byte{}
for _, param := range params {
t.TParameters = append(t.TParameters, []byte(param))
}
}
func (t *Transaction) AppendParameter(p []byte) {
t.TParameters = append(t.TParameters, p)
}
func (t *Transaction) SetParameterAt(i int, p []byte) error {
if i >= len(t.TParameters) {
return errors.Errorf("invalid index, got [%d]>=[%d]", i, len(t.TParameters))
}
t.TParameters[i] = p
return nil
}
func (t *Transaction) Transient() driver.TransientMap {
return t.TTransient
}
func (t *Transaction) ResetTransient() {
t.TTransient = map[string][]byte{}
}
func (t *Transaction) SetRWSet() error {
switch {
case len(t.TProposalResponses) != 0:
logger.Debugf("populate rws from proposal response")
results, err := t.Results()
if err != nil {
return errors.WithMessagef(err, "failed to get rws from proposal response")
}
t.rwset, err = t.channel.GetRWSet(t.ID(), results)
if err != nil {
return errors.WithMessagef(err, "failed to populate rws from proposal response")
}
case len(t.RWSet) != 0:
logger.Debugf("populate rws from rwset")
var err error
t.rwset, err = t.channel.GetRWSet(t.ID(), t.RWSet)
if err != nil {
return errors.WithMessagef(err, "failed to populate rws from existing rws")
}
default:
logger.Debugf("populate rws from scratch")
var err error
t.rwset, err = t.channel.NewRWSet(t.ID())
if err != nil {
return errors.WithMessagef(err, "failed to create fresh rws")
}
}
return nil
}
func (t *Transaction) RWS() driver.RWSet {
return t.rwset
}
func (t *Transaction) Done() error {
if t.rwset != nil {
// There is a simulation in progress:
// 1. terminate it
// 2. append it to the payload
t.rwset.Done()
var err error
t.RWSet, err = t.rwset.Bytes()
if err != nil {
return errors.Wrapf(err, "failed marshalling rws")
}
if logger.IsEnabledFor(zapcore.DebugLevel) {
logger.Debugf("terminated simulation with [%s][len:%d]", t.rwset.Namespaces(), len(t.RWSet))
}
}
return nil
}
func (t *Transaction) Close() {
if logger.IsEnabledFor(zapcore.DebugLevel) {
logger.Debugf("closing transaction [%s,%v]", t.ID(), t.rwset != nil)
}
if t.rwset != nil {
t.rwset.Done()
t.rwset = nil
}
}
func (t *Transaction) Raw() ([]byte, error) {
if t.rwset != nil {
var err error
t.RWSet, err = t.rwset.Bytes()
if err != nil {
return nil, err
}
}
return json.Marshal(t)
}
func (t *Transaction) GetRWSet() (driver.RWSet, error) {
if t.rwset == nil {
err := t.SetRWSet()
if err != nil {
return nil, err
}
}
return t.rwset, nil
}
func (t *Transaction) Bytes() ([]byte, error) {
if err := t.Done(); err != nil {
return nil, err
}
logger.Debugf("get transient [%v]", t.TTransient)
return json.Marshal(t)
}
func (t *Transaction) BytesNoTransient() ([]byte, error) {
if err := t.Done(); err != nil {
return nil, err
}
temp := &Transaction{}
if err := temp.From(t); err != nil {
return nil, err
}
temp.ResetTransient()
return json.Marshal(temp)
}
func (t *Transaction) Endorse() error {
return t.EndorseWithIdentity(t.Creator())
}
func (t *Transaction) EndorseWithIdentity(identity view.Identity) error {
if logger.IsEnabledFor(zapcore.DebugLevel) {
logger.Debugf("endorse transaction [%s] with identity [%s]", t.ID(), identity.String())
}
// prepare signer
s, err := t.fns.SignerService().GetSigner(identity)
if err != nil {
return err
}
signer := &signerWrapper{creator: identity, signer: s}
// is there a proposal already signed?
if t.SignedProposal() == nil {
// Endorse it
if err := t.generateProposal(signer); err != nil {
return errors.Wrapf(err, "failed setting proposal")
}
} else {
logger.Debugf("signed proposal already set [%v]", t.signedProposal)
}
// is there already a response or a simulation is in progress?
if len(t.TProposalResponses) != 0 || len(t.RWSet) != 0 || t.RWS() != nil {
defer t.Close()
t.proposalResponse, err = t.getProposalResponse(signer)
if err != nil {
return errors.Wrapf(err, "failed getting proposal response")
}
err = t.appendProposalResponse(t.proposalResponse)
if err != nil {
return errors.Wrapf(err, "failed appending proposal response")
}
}
err = t.StoreTransient()
if err != nil {
return errors.Wrapf(err, "failed storing transient")
}
return nil
}
func (t *Transaction) EndorseWithSigner(identity view.Identity, s driver.Signer) error {
// prepare signer
var err error
signer := &signerWrapper{creator: identity, signer: s}
// is there a proposal already signed?
if t.SignedProposal() == nil {
// Endorse it
if err := t.generateProposal(signer); err != nil {
return errors.Wrapf(err, "failed setting proposal")
}
}
// is there already a response or a simulation is in progress?
if len(t.TProposalResponses) != 0 || len(t.RWSet) != 0 || t.RWS() != nil {
defer t.Close()
t.proposalResponse, err = t.getProposalResponse(signer)
if err != nil {
return errors.Wrapf(err, "failed getting proposal response")
}
err = t.appendProposalResponse(t.proposalResponse)
if err != nil {
return errors.Wrapf(err, "failed appending proposal response")
}
}
err = t.StoreTransient()
if err != nil {
return errors.Wrapf(err, "failed storing transient")
}
return nil
}
func (t *Transaction) EndorseProposal() error {
return t.EndorseProposalWithIdentity(t.Creator())
}
func (t *Transaction) EndorseProposalWithIdentity(identity view.Identity) error {
// prepare signer
s, err := t.fns.SignerService().GetSigner(identity)
if err != nil {
return err
}
signer := &signerWrapper{creator: identity, signer: s}
defer t.Close()
if err := t.generateProposal(signer); err != nil {
return err
}
return nil
}
func (t *Transaction) EndorseProposalResponse() error {
return t.EndorseProposalResponseWithIdentity(t.Creator())
}
func (t *Transaction) EndorseProposalResponseWithIdentity(identity view.Identity) error {
// prepare signer
s, err := t.fns.SignerService().GetSigner(identity)
if err != nil {
return err
}
signer := &signerWrapper{creator: identity, signer: s}
defer t.Close()
t.proposalResponse, err = t.getProposalResponse(signer)
if err != nil {
return nil
}
return t.appendProposalResponse(t.proposalResponse)
}
func (t *Transaction) AppendProposalResponse(response driver.ProposalResponse) error {
return t.appendProposalResponse(response.(*ProposalResponse).pr)
}
func (t *Transaction) ProposalHasBeenEndorsedBy(party view.Identity) error {
verifier, err := t.channel.GetVerifier(party)
if err != nil {
return err
}
return verifier.Verify(t.SignedProposal().ProposalBytes(), t.SignedProposal().Signature())
}
func (t *Transaction) StoreTransient() error {
logger.Debugf("Storing transient for [%s]", t.ID())
return t.channel.MetadataService().StoreTransient(t.ID(), t.TTransient)
}
func (t *Transaction) ProposalResponses() []driver.ProposalResponse {
var res []driver.ProposalResponse
for _, resp := range t.TProposalResponses {
r, err := NewProposalResponseFromResponse(resp)
if err != nil {
panic(err)
}
res = append(res, r)
}
return res
}
func (t *Transaction) ProposalResponse() ([]byte, error) {
raw, err := proto.Marshal(t.proposalResponse)
if err != nil {
return nil, err
}
return raw, nil
}
func (t *Transaction) Envelope() (driver.Envelope, error) {
signerID := t.Creator()
signer, err := t.fns.SignerService().GetSigner(signerID)
if err != nil {
logger.Errorf("signer not found for %s while creating tx envelope for ordering [%s]", signerID.UniqueID(), err)
return nil, errors.Wrapf(err, "signer not found for %s while creating tx envelope for ordering", signerID.UniqueID())
}
env, err := fabricutils.CreateEndorserSignedTX(&signerWrapper{signerID, signer}, t.Proposal(), t.ProposalResponses()...)
if err != nil {
return nil, errors.WithMessage(err, "could not assemble transaction")
}
return NewEnvelopeFromEnv(env)
}
func (t *Transaction) generateProposal(signer SerializableSigner) error {
logger.Debugf("generate proposal...")
// Build the spec
params := append([][]byte{[]byte(t.TFunction)}, t.TParameters...)
input := pb.ChaincodeInput{
Args: params,
Decorations: nil,
IsInit: false,
}
spec := &pb.ChaincodeSpec{
Type: pb.ChaincodeSpec_GOLANG,
ChaincodeId: &pb.ChaincodeID{Name: t.TChaincode, Version: t.TChaincodeVersion},
Input: &input,
}
invocation := &pb.ChaincodeInvocationSpec{ChaincodeSpec: spec}
funcName := "invoke"
proposal, _, err := protoutil.CreateChaincodeProposalWithTxIDNonceAndTransient(
t.TTxID,
pcommon.HeaderType_ENDORSER_TRANSACTION,
t.TChannel, invocation,
t.TNonce,
t.TCreator,
nil)
if err != nil {
return errors.WithMessagef(err, "error creating proposal for %s", funcName)
}
t.TProposal = proposal
t.TSignedProposal, err = protoutil.GetSignedProposal(proposal, signer)
if err != nil {
return errors.WithMessagef(err, "error creating underlying signed proposal for %s", funcName)
}
t.signedProposal, err = newSignedProposal(t.TSignedProposal)
if err != nil {
return err
}
logger.Debugf("signed proposal set [%s]", t.signedProposal.ProposalHash())
return nil
}
func (t *Transaction) appendProposalResponse(response *pb.ProposalResponse) error {
for _, r := range t.TProposalResponses {
if bytes.Equal(r.Endorsement.Endorser, response.Endorsement.Endorser) {
logger.Debugf("an endorsement from [%s] found, skip it", view.Identity(r.Endorsement.Endorser))
return nil
}
}
t.TProposalResponses = append(t.TProposalResponses, response)
return nil
}
func (t *Transaction) getProposalResponse(signer SerializableSigner) (*pb.ProposalResponse, error) {
rwset, err := t.GetRWSet()
if err != nil {
return nil, err
}
pubSimResBytes, err := rwset.Bytes()
if err != nil {
return nil, err
}
signedProposal := t.SignedProposal()
if signedProposal == nil {
panic("signed proposal must not be nil")
}
response := &pb.Response{
Status: 200,
Message: "",
Payload: nil,
}
version := signedProposal.ChaincodeName()
if len(signedProposal.ChaincodeVersion()) == 0 {
// fetch current chaincode version
chaincode := t.channel.Chaincode(signedProposal.ChaincodeName())
var err error
version, err = chaincode.Version()
if err != nil {
return nil, errors.WithMessagef(err, "failed to get chaincode version, proposal didn't contain it")
}
}
// Note, mPrpBytes is the same as prpBytes by default endorsement plugin, but others could change it.
// serialize the signing identity
// sign the concatenation of the proposal response and the serialized endorser identity with this endorser's key
creator, err := signer.Serialize()
if err != nil {
return nil, errors.Wrapf(err, "could not get the signer's identity")
}
prpBytes, err := protoutil.GetBytesProposalResponsePayload(
signedProposal.ProposalHash(),
response,
pubSimResBytes,
nil,
&pb.ChaincodeID{
Name: signedProposal.ChaincodeName(),
Version: version,
},
)
logger.Debugf("ProposalResponse [%s][%s]->\n[%s]\n[%s] \n",
base64.StdEncoding.EncodeToString(signedProposal.ProposalHash()),
base64.StdEncoding.EncodeToString(pubSimResBytes),
base64.StdEncoding.EncodeToString(prpBytes),
base64.StdEncoding.EncodeToString(creator),
)
if err != nil {
return nil, errors.WithMessage(err, "failed to create the proposal response")
}
signature, err := signer.Sign(append(prpBytes, creator...))
if err != nil {
return nil, errors.Wrapf(err, "could not sign the proposal response payload")
}
endorsement := &pb.Endorsement{Signature: signature, Endorser: creator}
return &pb.ProposalResponse{
Version: 1,
Endorsement: endorsement,
Payload: prpBytes,
Response: response,
}, nil
}
type Signer interface {
Sign(message []byte) ([]byte, error)
}
type SerializableSigner interface {
Sign(message []byte) ([]byte, error)
Serialize() ([]byte, error)
}
type signerWrapper struct {
creator view.Identity
signer Signer
}
func (s *signerWrapper) Sign(message []byte) ([]byte, error) {
return s.signer.Sign(message)
}
func (s *signerWrapper) Serialize() ([]byte, error) {
return s.creator, nil
}