-
Notifications
You must be signed in to change notification settings - Fork 64
/
file_append_transaction.go
479 lines (400 loc) · 13.6 KB
/
file_append_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
package hedera
/*-
*
* Hedera Go SDK
*
* Copyright (C) 2020 - 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import (
"time"
"github.com/hashgraph/hedera-protobufs-go/services"
"github.com/pkg/errors"
protobuf "google.golang.org/protobuf/proto"
)
// FileAppendTransaction appends the given contents to the end of the file. If a file is too big to create with a single
// FileCreateTransaction, then it can be created with the first part of its contents, and then appended multiple times
// to create the entire file.
type FileAppendTransaction struct {
Transaction
maxChunks uint64
contents []byte
fileID *FileID
chunkSize int
}
// NewFileAppendTransaction creates a FileAppendTransaction transaction which can be
// used to construct and execute a File Append Transaction.
func NewFileAppendTransaction() *FileAppendTransaction {
tx := FileAppendTransaction{
Transaction: _NewTransaction(),
maxChunks: 20,
contents: make([]byte, 0),
chunkSize: 2048,
}
tx._SetDefaultMaxTransactionFee(NewHbar(5))
return &tx
}
func _FileAppendTransactionFromProtobuf(tx Transaction, pb *services.TransactionBody) *FileAppendTransaction {
return &FileAppendTransaction{
Transaction: tx,
maxChunks: 20,
contents: pb.GetFileAppend().GetContents(),
chunkSize: 2048,
fileID: _FileIDFromProtobuf(pb.GetFileAppend().GetFileID()),
}
}
// SetFileID sets the FileID of the file to which the bytes are appended to.
func (tx *FileAppendTransaction) SetFileID(fileID FileID) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.fileID = &fileID
return tx
}
// GetFileID returns the FileID of the file to which the bytes are appended to.
func (tx *FileAppendTransaction) GetFileID() FileID {
if tx.fileID == nil {
return FileID{}
}
return *tx.fileID
}
// SetMaxChunkSize Sets maximum amount of chunks append function can create
func (tx *FileAppendTransaction) SetMaxChunkSize(size int) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.chunkSize = size
return tx
}
// GetMaxChunkSize returns maximum amount of chunks append function can create
func (tx *FileAppendTransaction) GetMaxChunkSize() int {
return tx.chunkSize
}
// SetMaxChunks sets the maximum number of chunks that can be created
func (tx *FileAppendTransaction) SetMaxChunks(size uint64) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.maxChunks = size
return tx
}
// GetMaxChunks returns the maximum number of chunks that can be created
func (tx *FileAppendTransaction) GetMaxChunks() uint64 {
return tx.maxChunks
}
// SetContents sets the bytes to append to the contents of the file.
func (tx *FileAppendTransaction) SetContents(contents []byte) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.contents = contents
return tx
}
// GetContents returns the bytes to append to the contents of the file.
func (tx *FileAppendTransaction) GetContents() []byte {
return tx.contents
}
// ---- Required Interfaces ---- //
// Sign uses the provided privateKey to sign the transaction.
func (tx *FileAppendTransaction) Sign(
privateKey PrivateKey,
) *FileAppendTransaction {
tx.Transaction.Sign(privateKey)
return tx
}
// SignWithOperator signs the transaction with client's operator privateKey.
func (tx *FileAppendTransaction) SignWithOperator(
client *Client,
) (*FileAppendTransaction, error) {
// If the transaction is not signed by the _Operator, we need
// to sign the transaction with the _Operator
_, err := tx.Transaction.signWithOperator(client, tx)
if err != nil {
return nil, err
}
return tx, nil
}
// SignWith executes the TransactionSigner and adds the resulting signature data to the Transaction's signature map
// with the publicKey as the map key.
func (tx *FileAppendTransaction) SignWith(
publicKey PublicKey,
signer TransactionSigner,
) *FileAppendTransaction {
tx.Transaction.SignWith(publicKey, signer)
return tx
}
// AddSignature adds a signature to the transaction.
func (tx *FileAppendTransaction) AddSignature(publicKey PublicKey, signature []byte) *FileAppendTransaction {
tx.Transaction.AddSignature(publicKey, signature)
return tx
}
// When execution is attempted, a single attempt will timeout when tx deadline is reached. (The SDK may subsequently retry the execution.)
func (tx *FileAppendTransaction) SetGrpcDeadline(deadline *time.Duration) *FileAppendTransaction {
tx.Transaction.SetGrpcDeadline(deadline)
return tx
}
func (tx *FileAppendTransaction) Freeze() (*FileAppendTransaction, error) {
return tx.FreezeWith(nil)
}
func (tx *FileAppendTransaction) FreezeWith(client *Client) (*FileAppendTransaction, error) {
if tx.IsFrozen() {
return tx, nil
}
if tx.nodeAccountIDs._Length() == 0 {
if client == nil {
return tx, errNoClientOrTransactionIDOrNodeId
}
tx.SetNodeAccountIDs(client.network._GetNodeAccountIDsForExecute())
}
tx._InitFee(client)
err := tx.validateNetworkOnIDs(client)
if err != nil {
return &FileAppendTransaction{}, err
}
if err := tx._InitTransactionID(client); err != nil {
return tx, err
}
body := tx.build()
chunks := uint64((len(tx.contents) + (tx.chunkSize - 1)) / tx.chunkSize)
if chunks > tx.maxChunks {
return tx, ErrMaxChunksExceeded{
Chunks: chunks,
MaxChunks: tx.maxChunks,
}
}
nextTransactionID := tx.transactionIDs._GetCurrent().(TransactionID)
tx.transactionIDs = _NewLockableSlice()
tx.transactions = _NewLockableSlice()
tx.signedTransactions = _NewLockableSlice()
if b, ok := body.Data.(*services.TransactionBody_FileAppend); ok {
for i := 0; uint64(i) < chunks; i++ {
start := i * tx.chunkSize
end := start + tx.chunkSize
if end > len(tx.contents) {
end = len(tx.contents)
}
tx.transactionIDs._Push(_TransactionIDFromProtobuf(nextTransactionID._ToProtobuf()))
if err != nil {
panic(err)
}
b.FileAppend.Contents = tx.contents[start:end]
body.TransactionID = nextTransactionID._ToProtobuf()
body.Data = &services.TransactionBody_FileAppend{
FileAppend: b.FileAppend,
}
for _, nodeAccountID := range tx.GetNodeAccountIDs() {
body.NodeAccountID = nodeAccountID._ToProtobuf()
bodyBytes, err := protobuf.Marshal(body)
if err != nil {
return tx, errors.Wrap(err, "error serializing body for file append")
}
tx.signedTransactions._Push(&services.SignedTransaction{
BodyBytes: bodyBytes,
SigMap: &services.SignatureMap{},
})
}
validStart := *nextTransactionID.ValidStart
*nextTransactionID.ValidStart = validStart.Add(1 * time.Nanosecond)
}
}
return tx, nil
}
// SetMaxTransactionFee sets the maximum transaction fee the operator (paying account) is willing to pay.
func (tx *FileAppendTransaction) SetMaxTransactionFee(fee Hbar) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.Transaction.SetMaxTransactionFee(fee)
return tx
}
// SetRegenerateTransactionID sets if transaction IDs should be regenerated when `TRANSACTION_EXPIRED` is received
func (tx *FileAppendTransaction) SetRegenerateTransactionID(regenerateTransactionID bool) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.Transaction.SetRegenerateTransactionID(regenerateTransactionID)
return tx
}
// SetTransactionMemo sets the memo for this FileAppendTransaction.
func (tx *FileAppendTransaction) SetTransactionMemo(memo string) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.Transaction.SetTransactionMemo(memo)
return tx
}
// SetTransactionValidDuration sets the valid duration for this FileAppendTransaction.
func (tx *FileAppendTransaction) SetTransactionValidDuration(duration time.Duration) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.Transaction.SetTransactionValidDuration(duration)
return tx
}
// ToBytes serialise the tx to bytes, no matter if it is signed (locked), or not
func (tx *FileAppendTransaction) ToBytes() ([]byte, error) {
bytes, err := tx.Transaction.toBytes(tx)
if err != nil {
return nil, err
}
return bytes, nil
}
// SetTransactionID sets the TransactionID for this FileAppendTransaction.
func (tx *FileAppendTransaction) SetTransactionID(transactionID TransactionID) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.Transaction.SetTransactionID(transactionID)
return tx
}
// SetNodeAccountID sets the _Node AccountID for this FileAppendTransaction.
func (tx *FileAppendTransaction) SetNodeAccountIDs(nodeAccountIDs []AccountID) *FileAppendTransaction {
tx._RequireNotFrozen()
tx.Transaction.SetNodeAccountIDs(nodeAccountIDs)
return tx
}
// SetMaxRetry sets the max number of errors before execution will fail.
func (tx *FileAppendTransaction) SetMaxRetry(count int) *FileAppendTransaction {
tx.Transaction.SetMaxRetry(count)
return tx
}
// SetMaxBackoff The maximum amount of time to wait between retries.
// Every retry attempt will increase the wait time exponentially until it reaches this time.
func (tx *FileAppendTransaction) SetMaxBackoff(max time.Duration) *FileAppendTransaction {
tx.Transaction.SetMaxBackoff(max)
return tx
}
// SetMinBackoff sets the minimum amount of time to wait between retries.
func (tx *FileAppendTransaction) SetMinBackoff(min time.Duration) *FileAppendTransaction {
tx.Transaction.SetMinBackoff(min)
return tx
}
func (tx *FileAppendTransaction) SetLogLevel(level LogLevel) *FileAppendTransaction {
tx.Transaction.SetLogLevel(level)
return tx
}
// Execute executes the Transaction with the provided client
func (tx *FileAppendTransaction) Execute(
client *Client,
) (TransactionResponse, error) {
if client == nil {
return TransactionResponse{}, errNoClientProvided
}
if tx.freezeError != nil {
return TransactionResponse{}, tx.freezeError
}
list, err := tx.ExecuteAll(client)
if err != nil {
if len(list) > 0 {
return TransactionResponse{
TransactionID: tx.GetTransactionID(),
NodeID: list[0].NodeID,
Hash: make([]byte, 0),
}, err
}
return TransactionResponse{
TransactionID: tx.GetTransactionID(),
Hash: make([]byte, 0),
}, err
}
return list[0], nil
}
// ExecuteAll executes the all the Transactions with the provided client
func (tx *FileAppendTransaction) ExecuteAll(
client *Client,
) ([]TransactionResponse, error) {
if client == nil || client.operator == nil {
return []TransactionResponse{}, errNoClientProvided
}
if !tx.IsFrozen() {
_, err := tx.FreezeWith(client)
if err != nil {
return []TransactionResponse{}, err
}
}
var transactionID TransactionID
if tx.transactionIDs._Length() > 0 {
transactionID = tx.GetTransactionID()
} else {
return []TransactionResponse{}, errors.New("transactionID list is empty")
}
if !client.GetOperatorAccountID()._IsZero() && client.GetOperatorAccountID()._Equals(*transactionID.AccountID) {
tx.SignWith(
client.GetOperatorPublicKey(),
client.operator.signer,
)
}
size := tx.signedTransactions._Length() / tx.nodeAccountIDs._Length()
list := make([]TransactionResponse, size)
for i := 0; i < size; i++ {
resp, err := _Execute(client, tx)
if err != nil {
return list, err
}
list[i] = resp.(TransactionResponse)
_, err = NewTransactionReceiptQuery().
SetNodeAccountIDs([]AccountID{resp.(TransactionResponse).NodeID}).
SetTransactionID(resp.(TransactionResponse).TransactionID).
Execute(client)
if err != nil {
return list, err
}
}
return list, nil
}
func (tx *FileAppendTransaction) Schedule() (*ScheduleCreateTransaction, error) {
chunks := uint64((len(tx.contents) + (tx.chunkSize - 1)) / tx.chunkSize)
if chunks > 1 {
return &ScheduleCreateTransaction{}, ErrMaxChunksExceeded{
Chunks: chunks,
MaxChunks: 1,
}
}
return tx.Transaction.schedule(tx)
}
// ----------- Overridden functions ----------------
func (tx *FileAppendTransaction) getName() string {
return "FileAppendTransaction"
}
func (tx *FileAppendTransaction) validateNetworkOnIDs(client *Client) error {
if client == nil || !client.autoValidateChecksums {
return nil
}
if tx.fileID != nil {
if err := tx.fileID.ValidateChecksum(client); err != nil {
return err
}
}
return nil
}
func (tx *FileAppendTransaction) build() *services.TransactionBody {
return &services.TransactionBody{
TransactionFee: tx.transactionFee,
Memo: tx.Transaction.memo,
TransactionValidDuration: _DurationToProtobuf(tx.GetTransactionValidDuration()),
TransactionID: tx.transactionID._ToProtobuf(),
Data: &services.TransactionBody_FileAppend{
FileAppend: tx.buildProtoBody(),
},
}
}
func (tx *FileAppendTransaction) buildScheduled() (*services.SchedulableTransactionBody, error) {
return &services.SchedulableTransactionBody{
TransactionFee: tx.transactionFee,
Memo: tx.Transaction.memo,
Data: &services.SchedulableTransactionBody_FileAppend{
FileAppend: tx.buildProtoBody(),
},
}, nil
}
func (tx *FileAppendTransaction) buildProtoBody() *services.FileAppendTransactionBody {
body := &services.FileAppendTransactionBody{
Contents: tx.contents,
}
if tx.fileID != nil {
body.FileID = tx.fileID._ToProtobuf()
}
return body
}
func (tx *FileAppendTransaction) getMethod(channel *_Channel) _Method {
return _Method{
transaction: channel._GetFile().AppendContent,
}
}
func (tx *FileAppendTransaction) _ConstructScheduleProtobuf() (*services.SchedulableTransactionBody, error) {
return tx.buildScheduled()
}