forked from hashgraph/hedera-sdk-go
/
transaction.go
487 lines (410 loc) · 15.2 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
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
package hedera
import (
"bytes"
"crypto/sha512"
"encoding/hex"
"time"
protobuf "github.com/golang/protobuf/proto"
"github.com/hashgraph/hedera-sdk-go/proto"
)
// Transaction contains the protobuf of a prepared transaction which can be signed and executed.
type Transaction struct {
pbBody *proto.TransactionBody
id TransactionID
nextTransactionIndex int
transactions []*proto.Transaction
signatures []*proto.SignatureMap
nodeIDs []AccountID
}
func newTransaction() Transaction {
return Transaction{
pbBody: &proto.TransactionBody{
TransactionValidDuration: durationToProtobuf(120 * time.Second),
},
id: TransactionID{},
nextTransactionIndex: 0,
transactions: make([]*proto.Transaction, 0),
signatures: make([]*proto.SignatureMap, 0),
nodeIDs: make([]AccountID, 0),
}
}
func transactionFromProtobuf(transactions map[TransactionID]map[AccountID]*proto.Transaction, pb *proto.TransactionBody) Transaction {
tx := Transaction{
pbBody: pb,
id: transactionIDFromProtobuf(pb.TransactionID),
nextTransactionIndex: 0,
transactions: make([]*proto.Transaction, 0),
signatures: make([]*proto.SignatureMap, 0),
nodeIDs: make([]AccountID, 0),
}
var protoTxs map[AccountID]*proto.Transaction
for _, m := range transactions {
protoTxs = m
break
}
for nodeAccountID, protoTx := range protoTxs {
tx.nodeIDs = append(tx.nodeIDs, nodeAccountID)
tx.transactions = append(tx.transactions, protoTx)
tx.signatures = append(tx.signatures, protoTx.GetSigMap())
}
return tx
}
func TransactionFromBytes(bytes []byte) (interface{}, error) {
transactions := make(map[TransactionID]map[AccountID]*proto.Transaction)
buf := protobuf.NewBuffer(bytes)
var first *proto.TransactionBody = nil
for {
tx := proto.Transaction{}
if err := buf.DecodeMessage(&tx); err != nil {
break
}
var txBody proto.TransactionBody
if err := protobuf.Unmarshal(tx.GetBodyBytes(), &txBody); err != nil {
return Transaction{}, err
}
if first == nil {
first = &txBody
}
transactionID := transactionIDFromProtobuf(txBody.GetTransactionID())
nodeAccountID := accountIDFromProtobuf(txBody.GetNodeAccountID())
if _, ok := transactions[transactionID]; !ok {
transactions[transactionID] = make(map[AccountID]*proto.Transaction)
}
transactions[transactionID][nodeAccountID] = &tx
}
if first == nil {
return nil, errNoTransactionInBytes
}
switch first.Data.(type) {
case *proto.TransactionBody_ContractCall:
return contractExecuteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ContractCreateInstance:
return contractCreateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ContractUpdateInstance:
return contractUpdateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ContractDeleteInstance:
return contractDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_CryptoAddLiveHash:
return liveHashAddTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_CryptoCreateAccount:
return accountCreateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_CryptoDelete:
return accountDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_CryptoDeleteLiveHash:
return liveHashDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_CryptoTransfer:
return transferTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_CryptoUpdateAccount:
return accountUpdateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_FileAppend:
return fileAppendTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_FileCreate:
return fileCreateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_FileDelete:
return fileDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_FileUpdate:
return fileUpdateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_SystemDelete:
return systemDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_SystemUndelete:
return systemUndeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_Freeze:
return freezeTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ConsensusCreateTopic:
return topicCreateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ConsensusUpdateTopic:
return topicUpdateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ConsensusDeleteTopic:
return topicDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_ConsensusSubmitMessage:
return topicMessageSubmitTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenCreation:
return tokenCreateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenFreeze:
return tokenFreezeTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenUnfreeze:
return tokenUnfreezeTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenGrantKyc:
return tokenGrantKycTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenRevokeKyc:
return tokenRevokeKycTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenDeletion:
return tokenDeleteTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenUpdate:
return tokenUpdateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenMint:
return tokenMintTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenBurn:
return tokenBurnTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenWipe:
return tokenWipeTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenAssociate:
return tokenAssociateTransactionFromProtobuf(transactions, first), nil
case *proto.TransactionBody_TokenDissociate:
return tokenDissociateTransactionFromProtobuf(transactions, first), nil
default:
return Transaction{}, errFailedToDeserializeBytes
}
}
func (transaction *Transaction) GetSignatures() (map[AccountID]map[*PublicKey][]byte, error) {
returnMap := make(map[AccountID]map[*PublicKey][]byte, len(transaction.nodeIDs))
if len(transaction.transactions) == 0 {
return returnMap, nil
}
for i, nodeID := range transaction.nodeIDs {
inner := make(map[*PublicKey][]byte, len(transaction.transactions[i].SigMap.SigPair))
for _, sigPair := range transaction.transactions[i].SigMap.SigPair {
key, err := PublicKeyFromBytes(sigPair.PubKeyPrefix)
if err != nil {
return make(map[AccountID]map[*PublicKey][]byte, 0), err
}
switch sigPair.Signature.(type) {
case *proto.SignaturePair_Contract:
inner[&key] = sigPair.GetContract()
case *proto.SignaturePair_Ed25519:
inner[&key] = sigPair.GetEd25519()
case *proto.SignaturePair_RSA_3072:
inner[&key] = sigPair.GetRSA_3072()
case *proto.SignaturePair_ECDSA_384:
inner[&key] = sigPair.GetECDSA_384()
}
}
returnMap[nodeID] = inner
}
return returnMap, nil
}
func (transaction *Transaction) AddSignature(publicKey PublicKey, signature []byte) *Transaction {
transaction.requireExactNode()
if transaction.keyAlreadySigned(publicKey) {
return transaction
}
if len(transaction.signatures) == 0 {
return transaction
}
transaction.signatures[0].SigPair = append(transaction.signatures[0].SigPair, publicKey.toSignaturePairProtobuf(signature))
return transaction
}
func (transaction *Transaction) GetTransactionHash() ([]byte, error) {
hashes, err := transaction.GetTransactionHashPerNode()
if err != nil {
return []byte{}, err
}
return hashes[transaction.nodeIDs[0]], nil
}
func (transaction *Transaction) GetTransactionHashPerNode() (map[AccountID][]byte, error) {
transactionHash := make(map[AccountID][]byte)
if len(transaction.transactions) == 0 {
return transactionHash, errTransactionIsNotFrozen
}
for i, node := range transaction.nodeIDs {
data, err := protobuf.Marshal(transaction.transactions[i])
if err != nil {
// This should be unreachable
// From the documentation this appears to only be possible if there are missing proto types
return transactionHash, err
}
hash := sha512.New384()
_, err = hash.Write(data)
if err != nil {
return transactionHash, err
}
transactionHash[node] = []byte(hex.EncodeToString(hash.Sum(nil)))
}
return transactionHash, nil
}
func (transaction *Transaction) initFee(client *Client) {
if client != nil && transaction.pbBody.TransactionFee == 0 {
transaction.SetMaxTransactionFee(client.maxTransactionFee)
}
}
func (transaction *Transaction) initTransactionID(client *Client) error {
if transaction.pbBody.TransactionID == nil {
if client.operator != nil {
transaction.id = TransactionIDGenerate(client.operator.accountID)
transaction.SetTransactionID(transaction.id)
} else {
return errNoClientOrTransactionID
}
}
return nil
}
func (transaction *Transaction) isFrozen() bool {
return len(transaction.transactions) > 0
}
func (transaction *Transaction) requireNotFrozen() {
if transaction.isFrozen() {
panic("Transaction is immutable; it has at least one signature or has been explicitly frozen")
}
}
func (transaction *Transaction) requireExactNode() {
if len(transaction.nodeIDs) > 1 {
panic("Transaction has more than one node ID set")
}
if transaction.isFrozen() {
panic("Transaction did not have an exact node ID set")
}
}
func transaction_freezeWith(
transaction *Transaction,
client *Client,
) error {
if len(transaction.nodeIDs) == 0 {
if client == nil {
return errNoClientOrTransactionIDOrNodeId
} else {
transaction.nodeIDs = client.network.getNodeAccountIDsForExecute()
}
}
for _, nodeAccountID := range transaction.nodeIDs {
transaction.pbBody.NodeAccountID = nodeAccountID.toProtobuf()
bodyBytes, err := protobuf.Marshal(transaction.pbBody)
if err != nil {
// This should be unreachable
// From the documentation this appears to only be possible if there are missing proto types
panic(err)
}
sigmap := proto.SignatureMap{
SigPair: make([]*proto.SignaturePair, 0),
}
transaction.signatures = append(transaction.signatures, &sigmap)
transaction.transactions = append(transaction.transactions, &proto.Transaction{
BodyBytes: bodyBytes,
SigMap: &sigmap,
})
}
return nil
}
func (transaction *Transaction) keyAlreadySigned(
pk PublicKey,
) bool {
if len(transaction.signatures) > 0 {
for _, pair := range transaction.signatures[0].SigPair {
if bytes.HasPrefix(pk.keyData, pair.PubKeyPrefix) {
return true
}
}
}
return false
}
func transaction_shouldRetry(status Status, _ response) bool {
return status == StatusBusy
}
func transaction_makeRequest(request request) protoRequest {
return protoRequest{
transaction: request.transaction.transactions[request.transaction.nextTransactionIndex],
}
}
func transaction_advanceRequest(request request) {
length := len(request.transaction.transactions)
currentIndex := request.transaction.nextTransactionIndex
request.transaction.nextTransactionIndex = (currentIndex + 1) % length
}
func transaction_getNodeAccountID(request request) AccountID {
return request.transaction.nodeIDs[request.transaction.nextTransactionIndex]
}
func transaction_mapResponseStatus(
_ request,
response response,
) Status {
return Status(response.transaction.NodeTransactionPrecheckCode)
}
func transaction_mapResponse(request request, _ response, nodeID AccountID, protoRequest protoRequest) (intermediateResponse, error) {
hash, err := protobuf.Marshal(protoRequest.transaction)
if err != nil {
return intermediateResponse{}, err
}
return intermediateResponse{
transaction: TransactionResponse{
NodeID: nodeID,
TransactionID: request.transaction.id,
Hash: hash,
},
}, nil
}
func (transaction *Transaction) String() string {
return protobuf.MarshalTextString(transaction.transactions[0]) +
protobuf.MarshalTextString(transaction.body())
}
func (transaction *Transaction) ToBytes() ([]byte, error) {
buf := protobuf.NewBuffer(make([]byte, 0))
if len(transaction.transactions) == 0 {
return buf.Bytes(), errTransactionIsNotFrozen
}
for _, tx := range transaction.transactions {
err := buf.EncodeMessage(tx)
if err != nil {
return buf.Bytes(), err
}
}
return buf.Bytes(), nil
}
// The protobuf stores the transaction body as raw bytes so we need to first
// decode what we have to inspect the Kind, TransactionID, and the NodeAccountID so we know how to
// properly execute it
func (transaction *Transaction) body() *proto.TransactionBody {
transactionBody := new(proto.TransactionBody)
err := protobuf.Unmarshal(transaction.transactions[0].GetBodyBytes(), transactionBody)
if err != nil {
// The bodyBytes inside of the transaction at this point have been verified and this should be impossible
panic(err)
}
return transactionBody
}
//
// Shared
//
func (transaction *Transaction) GetMaxTransactionFee() Hbar {
return HbarFromTinybar(int64(transaction.pbBody.TransactionFee))
}
// SetMaxTransactionFee sets the max transaction fee for this Transaction.
func (transaction *Transaction) SetMaxTransactionFee(fee Hbar) *Transaction {
transaction.pbBody.TransactionFee = uint64(fee.AsTinybar())
return transaction
}
func (transaction *Transaction) GetTransactionMemo() string {
return transaction.pbBody.Memo
}
// SetTransactionMemo sets the memo for this Transaction.
func (transaction *Transaction) SetTransactionMemo(memo string) *Transaction {
transaction.pbBody.Memo = memo
return transaction
}
func (transaction *Transaction) GetTransactionValidDuration() time.Duration {
if transaction.pbBody.TransactionValidDuration != nil {
return durationFromProtobuf(transaction.pbBody.TransactionValidDuration)
} else {
return 0
}
}
// SetTransactionValidDuration sets the valid duration for this Transaction.
func (transaction *Transaction) SetTransactionValidDuration(duration time.Duration) *Transaction {
transaction.pbBody.TransactionValidDuration = durationToProtobuf(duration)
return transaction
}
func (transaction *Transaction) GetTransactionID() TransactionID {
if transaction.pbBody.TransactionID != nil {
return transactionIDFromProtobuf(transaction.pbBody.TransactionID)
} else {
return TransactionID{}
}
}
// SetTransactionID sets the TransactionID for this Transaction.
func (transaction *Transaction) SetTransactionID(transactionID TransactionID) *Transaction {
transaction.pbBody.TransactionID = transactionID.toProtobuf()
return transaction
}
func (transaction *Transaction) GetNodeAccountIDs() []AccountID {
if transaction.nodeIDs != nil {
return transaction.nodeIDs
} else {
return make([]AccountID, 0)
}
}
// SetNodeAccountID sets the node AccountID for this Transaction.
func (transaction *Transaction) SetNodeAccountIDs(nodeID []AccountID) *Transaction {
if transaction.nodeIDs == nil {
transaction.nodeIDs = make([]AccountID, 0)
}
transaction.nodeIDs = append(transaction.nodeIDs, nodeID...)
return transaction
}