forked from CognitionFoundry/gohfc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
361 lines (319 loc) · 9.38 KB
/
transaction.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
/*
Copyright: Cognition Foundry. All Rights Reserved.
License: Apache License Version 2.0
*/
package gohfc
import (
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric/protos/msp"
"encoding/pem"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"github.com/hyperledger/fabric/protos/common"
"github.com/golang/protobuf/ptypes"
"time"
"github.com/hyperledger/fabric/protos/peer"
"bytes"
)
// TransactionId represents transaction identifier. TransactionId is the unique transaction number.
type TransactionId struct {
Nonce []byte
TransactionId string
Creator []byte
}
// QueryResponse represent result from query operation
type QueryResponse struct {
PeerName string
Error error
Response *peer.ProposalResponse
}
// InvokeResponse represent result from invoke operation. Please note that this is the result of simulation,
// not the result of actual block commit.
type InvokeResponse struct {
Status common.Status
// TxID is transaction id. This id can be used to track transactions and their status
TxID string
}
// QueryTransactionResponse holds data from `client.QueryTransaction`
// TODO it is not fully implemented!
type QueryTransactionResponse struct {
PeerName string
Error error
StatusCode int32
}
type transactionProposal struct {
proposal []byte
transactionId string
}
// marshalProtoIdentity creates SerializedIdentity from certificate and MSPid
func marshalProtoIdentity(identity *Identity, channel *Channel) ([]byte, error) {
creator, err := proto.Marshal(&msp.SerializedIdentity{
Mspid: channel.MspId,
IdBytes: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: identity.Certificate.Raw})})
if err != nil {
return nil, err
}
return creator, nil
}
// signatureHeader creates and marshal new signature header proto from creator and transaction nonce
func signatureHeader(creator []byte, tx *TransactionId) ([]byte, error) {
sh := new(common.SignatureHeader)
sh.Creator = creator
sh.Nonce = tx.Nonce
shBytes, err := proto.Marshal(sh)
if err != nil {
return nil, err
}
return shBytes, nil
}
// header creates new common.header from signature header and channel header
func header(signatureHeader, channelHeader []byte) (*common.Header) {
header := new(common.Header)
header.SignatureHeader = signatureHeader
header.ChannelHeader = channelHeader
return header
}
func channelHeader(headerType common.HeaderType, tx *TransactionId, channel *Channel, epoch uint64, extension *peer.ChaincodeHeaderExtension) ([]byte, error) {
ts, err := ptypes.TimestampProto(time.Now())
if err != nil {
return nil, err
}
var channelName string
if channel != nil {
channelName = channel.ChannelName
}
payloadChannelHeader := &common.ChannelHeader{
Type: int32(headerType),
Version: 1,
Timestamp: ts,
ChannelId: channelName,
Epoch: epoch,
}
payloadChannelHeader.TxId = tx.TransactionId
if extension != nil {
serExt, err := proto.Marshal(extension)
if err != nil {
return nil, err
}
payloadChannelHeader.Extension = serExt
}
return proto.Marshal(payloadChannelHeader)
}
// payload creates new common.payload from commonHeader and envelope data
func payload(header *common.Header, data []byte) ([]byte, error) {
p := new(common.Payload)
p.Header = header
p.Data = data
return proto.Marshal(p)
}
// newTransactionId generate new transaction id from creator and random bytes
func newTransactionId(creator []byte) (*TransactionId, error) {
nonce, err := generateRandomBytes(24)
if err != nil {
return nil, err
}
id := generateTxId(nonce, creator)
return &TransactionId{Creator: creator, Nonce: nonce, TransactionId: id}, nil
}
// generateRandomBytes get random bytes from crypto/random
func generateRandomBytes(len int) ([]byte, error) {
b := make([]byte, len)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
// sha256 is hardcoded in hyperledger
func generateTxId(nonce, creator []byte) string {
f := sha256.New()
f.Write(append(nonce, creator...))
return hex.EncodeToString(f.Sum(nil))
}
func chainCodeInvocationSpec(chainCode *ChainCode) ([]byte, error) {
invocation := &peer.ChaincodeInvocationSpec{
ChaincodeSpec: &peer.ChaincodeSpec{
Type: peer.ChaincodeSpec_Type(chainCode.Type),
ChaincodeId: &peer.ChaincodeID{Name: chainCode.Name},
Input: &peer.ChaincodeInput{Args: chainCode.toChainCodeArgs()},
},
}
invocationBytes, err := proto.Marshal(invocation)
if err != nil {
return nil, err
}
return invocationBytes, nil
}
func proposal(header, payload []byte) ([]byte, error) {
prop := new(peer.Proposal)
prop.Header = header
prop.Payload = payload
propBytes, err := proto.Marshal(prop)
if err != nil {
return nil, err
}
return propBytes, nil
}
func signedProposal(prop []byte, identity *Identity, crypt CryptoSuite) (*peer.SignedProposal, error) {
sb, err := crypt.Sign(prop, identity.PrivateKey)
if err != nil {
return nil, err
}
return &peer.SignedProposal{ProposalBytes: prop, Signature: sb}, nil
}
// sendToPeers send proposal to all peers in the list for endorsement asynchronously and wait for there response.
func sendToPeers(peers []*Peer, prop *peer.SignedProposal) []*PeerResponse {
ch := make(chan *PeerResponse)
l := len(peers)
resp := make([]*PeerResponse, 0, l)
for _, p := range peers {
go p.Endorse(ch, prop)
}
for i := 0; i < l; i++ {
resp = append(resp, <-ch)
}
close(ch)
return resp
}
func createTransactionProposal(identity *Identity, cc *ChainCode) (*transactionProposal, error) {
spec, err := chainCodeInvocationSpec(cc)
if err != nil {
return nil, err
}
creator, err := marshalProtoIdentity(identity, cc.Channel)
if err != nil {
return nil, err
}
txId, err := newTransactionId(creator)
if err != nil {
return nil, err
}
extension := &peer.ChaincodeHeaderExtension{ChaincodeId: &peer.ChaincodeID{Name: cc.Name}}
channelHeader, err := channelHeader(common.HeaderType_ENDORSER_TRANSACTION, txId, cc.Channel, 0, extension)
if err != nil {
return nil, err
}
signatureHeader, err := signatureHeader(creator, txId)
if err != nil {
return nil, err
}
proposalPayload, err := proto.Marshal(&peer.ChaincodeProposalPayload{Input: spec,TransientMap:cc.TransientMap})
if err != nil {
return nil, err
}
header, err := proto.Marshal(header(signatureHeader, channelHeader))
if err != nil {
return nil, err
}
proposal, err := proposal(header, proposalPayload)
if err != nil {
return nil, err
}
return &transactionProposal{proposal: proposal, transactionId: txId.TransactionId}, nil
}
func decodeChainCodeQueryResponse(data []byte) ([]*peer.ChaincodeInfo, error) {
response := new(peer.ChaincodeQueryResponse)
err := proto.Unmarshal(data, response)
if err != nil {
return nil, err
}
return response.GetChaincodes(), nil
}
func createTransaction(proposal []byte, endorsement []*PeerResponse) ([]byte, error) {
var propResp *peer.ProposalResponse
var pl []byte
mEndorsements := make([]*peer.Endorsement, 0, len(endorsement))
for _, e := range endorsement {
if e.Err == nil && e.Response.Response.Status == 200 {
propResp = e.Response
mEndorsements = append(mEndorsements, e.Response.Endorsement)
if pl == nil {
pl = e.Response.Payload
}
} else {
if e.Err!=nil{
return nil,e.Err
}
return nil, ErrBadTransactionStatus
}
if bytes.Compare(pl, e.Response.Payload) != 0 {
return nil, ErrEndorsementsDoNotMatch
}
}
// at least one is OK
if len(mEndorsements) < 1 {
return nil, ErrNoValidEndorsementFound
}
originalProposal, err := getProposal(proposal)
if err != nil {
return nil, err
}
originalProposalHeader, err := getHeader(originalProposal.Header)
if err != nil {
return nil, err
}
originalProposalPayload, err := getChainCodeProposalPayload(originalProposal.Payload)
if err != nil {
return nil, err
}
// create actual invocation
proposedPayload, err := proto.Marshal(&peer.ChaincodeProposalPayload{Input: originalProposalPayload.Input, TransientMap: nil})
if err != nil {
return nil, err
}
payload, err := proto.Marshal(&peer.ChaincodeActionPayload{
Action:&peer.ChaincodeEndorsedAction{
ProposalResponsePayload:propResp.Payload,
Endorsements:mEndorsements,
},
ChaincodeProposalPayload:proposedPayload,
})
if err != nil {
return nil, err
}
sTransaction, err := proto.Marshal(&peer.Transaction{
Actions:[]*peer.TransactionAction{{Header: originalProposalHeader.SignatureHeader, Payload: payload}},
})
if err != nil {
return nil, err
}
propBytes, err := proto.Marshal(&common.Payload{Header: originalProposalHeader, Data: sTransaction})
if err != nil {
return nil, err
}
return propBytes, nil
}
func getProposal(data []byte) (*peer.Proposal, error) {
prop := new(peer.Proposal)
err := proto.Unmarshal(data, prop)
if err != nil {
return nil, err
}
return prop, nil
}
func getHeader(bytes []byte) (*common.Header, error) {
h := &common.Header{}
err := proto.Unmarshal(bytes, h)
if err != nil {
return nil, err
}
return h, err
}
func getChainCodeProposalPayload(bytes []byte) (*peer.ChaincodeProposalPayload, error) {
cpp := &peer.ChaincodeProposalPayload{}
err := proto.Unmarshal(bytes, cpp)
if err != nil {
return nil, err
}
return cpp, err
}
// TODO not fully implemented!
func decodeTransaction(payload []byte) (int32, error) {
transaction := new(peer.ProcessedTransaction)
if err := proto.Unmarshal(payload, transaction); err != nil {
return 0,err
}
//DecodeBlockEnvelope(transaction.TransactionEnvelope)
return transaction.ValidationCode, nil
}