forked from hiero-ledger/hiero-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfile_append_transaction.py
More file actions
472 lines (378 loc) · 17.3 KB
/
Copy pathfile_append_transaction.py
File metadata and controls
472 lines (378 loc) · 17.3 KB
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
"""
Represents a file append transaction on the network.
This transaction appends data to an existing file on the network. If a file has multiple keys,
all keys must sign to modify its contents.
The transaction supports chunking for large files, automatically breaking content into
smaller chunks if the content exceeds the chunk size limit.
Inherits from the base Transaction class and implements the required methods
to build and execute a file append transaction.
"""
from __future__ import annotations
import math
from typing import TYPE_CHECKING, Any, Literal, overload
from hiero_sdk_python.file.file_id import FileId
from hiero_sdk_python.hapi.services import file_append_pb2, timestamp_pb2
from hiero_sdk_python.hapi.services.schedulable_transaction_body_pb2 import (
SchedulableTransactionBody,
)
from hiero_sdk_python.hbar import Hbar
from hiero_sdk_python.transaction.transaction import Transaction
from hiero_sdk_python.transaction.transaction_id import TransactionId
# Use TYPE_CHECKING to avoid circular import errors
if TYPE_CHECKING:
from hiero_sdk_python.channels import _Channel
from hiero_sdk_python.client.client import Client
from hiero_sdk_python.crypto.private_key import PrivateKey
from hiero_sdk_python.executable import _Method
from hiero_sdk_python.transaction.transaction import TransactionReceipt
from hiero_sdk_python.transaction.transaction_response import TransactionResponse
# pylint: disable=too-many-instance-attributes
class FileAppendTransaction(Transaction):
"""
Represents a file append transaction on the network.
This transaction appends data to an existing file on the network. If a file has multiple keys,
all keys must sign to modify its contents.
The transaction supports chunking for large files, automatically breaking content into
smaller chunks if the content exceeds the chunk size limit.
Inherits from the base Transaction class and implements the required methods
to build and execute a file append transaction.
"""
def __init__(
self,
file_id: FileId | None = None,
contents: str | bytes | None = None,
max_chunks: int | None = None,
chunk_size: int | None = None,
):
"""
Initializes a new FileAppendTransaction instance with the specified parameters.
Args:
file_id (Optional[FileId], optional): The ID of the file to append to.
contents (Optional[str | bytes], optional): The contents to append to the file.
Strings will be automatically encoded as UTF-8 bytes.
max_chunks (Optional[int], optional): Maximum number of chunks allowed. Defaults to 20.
chunk_size (Optional[int], optional): Size of each chunk in bytes. Defaults to 4096.
"""
super().__init__()
self.file_id: FileId | None = file_id
self.contents: bytes | None = self._encode_contents(contents)
self.max_chunks: int = max_chunks if max_chunks is not None else 20
self.chunk_size: int = chunk_size if chunk_size is not None else 4096
self._default_transaction_fee = Hbar(5).to_tinybars()
# Internal tracking for chunking
self._current_chunk_index: int = 0
self._total_chunks: int = self._calculate_total_chunks()
self._transaction_ids: list[TransactionId] = []
self._signing_keys: list[PrivateKey] = [] # Use string annotation to avoid import issues
def _encode_contents(self, contents: str | bytes | None) -> bytes | None:
"""
Helper method to encode string contents to UTF-8 bytes.
Args:
contents (Optional[str | bytes]): The contents to encode.
Returns:
Optional[bytes]: The encoded contents or None if input is None.
"""
if contents is None:
return None
if isinstance(contents, str):
return contents.encode("utf-8")
return contents
def _calculate_total_chunks(self) -> int:
"""
Calculates the total number of chunks needed for the current contents.
Returns:
int: The total number of chunks needed.
"""
if self.contents is None:
return 1
return math.ceil(len(self.contents) / self.chunk_size)
def get_required_chunks(self) -> int:
"""
Gets the number of chunks required for the current contents.
Returns:
int: The number of chunks required.
"""
return self._calculate_total_chunks()
def set_file_id(self, file_id: FileId) -> FileAppendTransaction:
"""
Sets the file ID for this file append transaction.
Args:
file_id (FileId): The file ID to append to.
Returns:
FileAppendTransaction: This transaction instance.
"""
self._require_not_frozen()
self.file_id = file_id
return self
def set_contents(self, contents: str | bytes | None) -> FileAppendTransaction:
"""
Sets the contents for this file append transaction.
Args:
contents (Optional[str | bytes]): The contents to append to the file.
Strings will be automatically encoded as UTF-8 bytes.
Returns:
FileAppendTransaction: This transaction instance.
"""
self._require_not_frozen()
self.contents = self._encode_contents(contents)
self._total_chunks = self._calculate_total_chunks()
return self
def set_max_chunks(self, max_chunks: int) -> FileAppendTransaction:
"""
Sets the maximum number of chunks allowed for this transaction.
Args:
max_chunks (int): The maximum number of chunks allowed.
Returns:
FileAppendTransaction: This transaction instance.
"""
self._require_not_frozen()
self.max_chunks = max_chunks
return self
def set_chunk_size(self, chunk_size: int) -> FileAppendTransaction:
"""
Sets the chunk size for this transaction.
Args:
chunk_size (int): The size of each chunk in bytes.
Returns:
FileAppendTransaction: This transaction instance.
"""
self._require_not_frozen()
self.chunk_size = chunk_size
self._total_chunks = self._calculate_total_chunks()
return self
def _build_proto_body(self) -> file_append_pb2.FileAppendTransactionBody:
"""
Returns the protobuf body for the file append transaction.
Returns:
FileAppendTransactionBody: The protobuf body for this transaction.
Raises:
ValueError: If file_id is not set.
"""
# Calculate the current chunk's content
if self.file_id is None:
raise ValueError("Missing required FileID")
if self.contents is None:
chunk_contents = b""
else:
start_index = self._current_chunk_index * self.chunk_size
end_index = min(start_index + self.chunk_size, len(self.contents))
chunk_contents = self.contents[start_index:end_index]
return file_append_pb2.FileAppendTransactionBody(
fileID=self.file_id._to_proto() if self.file_id else None, contents=chunk_contents
)
def build_transaction_body(self) -> Any:
"""
Builds the transaction body for this file append transaction.
Returns:
TransactionBody: The built transaction body.
"""
file_append_body = self._build_proto_body()
transaction_body = self.build_base_transaction_body()
transaction_body.fileAppend.CopyFrom(file_append_body)
return transaction_body
def build_scheduled_body(self) -> SchedulableTransactionBody:
"""
Builds the scheduled transaction body for this file append transaction.
Returns:
SchedulableTransactionBody: The built scheduled transaction body.
"""
file_append_body = self._build_proto_body()
schedulable_body = self.build_base_scheduled_body()
schedulable_body.fileAppend.CopyFrom(file_append_body)
return schedulable_body
def _get_method(self, channel: _Channel) -> _Method:
"""
Gets the method to execute the file append transaction.
This internal method returns a _Method object containing the appropriate gRPC
function to call when executing this transaction on the Hedera network.
Args:
channel (_Channel): The channel containing service stubs
Returns:
_Method: An object containing the transaction function to append to a file.
"""
from hiero_sdk_python.executable import _Method
return _Method(transaction_func=channel.file.appendContent, query_func=None)
def _from_proto(self, proto: file_append_pb2.FileAppendTransactionBody) -> FileAppendTransaction:
"""
Initializes a new FileAppendTransaction instance from a protobuf object.
Args:
proto: The protobuf object to initialize from.
Returns:
FileAppendTransaction: This transaction instance.
"""
self.file_id = FileId._from_proto(proto.fileID) if proto.fileID else None
self.contents = proto.contents
self._total_chunks = self._calculate_total_chunks()
return self
def _validate_chunking(self) -> None:
"""
Validates that the transaction doesn't exceed the maximum number of chunks.
Raises:
ValueError: If the transaction exceeds the maximum number of chunks.
"""
if self.max_chunks and self.get_required_chunks() > self.max_chunks:
raise ValueError(
f"Cannot execute FileAppendTransaction with more than {self.max_chunks} chunks. "
f"Required: {self.get_required_chunks()}"
)
def freeze_with(self, client: Client) -> FileAppendTransaction:
"""
Freezes the transaction by building the transaction body and setting necessary IDs.
For multi-chunk transactions, this method generates multiple transaction IDs
with incremented timestamps based on the chunk interval.
Args:
client (Client): The client instance to use for setting defaults.
Returns:
FileAppendTransaction: The current transaction instance for method chaining.
"""
if self._transaction_body_bytes:
return self
self._resolve_transaction_id(client)
# Generate transaction IDs for all chunks
if not self._transaction_ids:
base_timestamp = self.transaction_id.valid_start
for i in range(self.get_required_chunks()):
if i == 0:
# First chunk uses the original transaction ID
chunk_transaction_id = self.transaction_id
else:
# Subsequent chunks get incremented timestamps
# Add i nanoseconds to space out chunks
next_nanos = base_timestamp.nanos + i
chunk_valid_start = timestamp_pb2.Timestamp(
seconds=base_timestamp.seconds + next_nanos // 1_000_000_000, nanos=next_nanos % 1_000_000_000
)
chunk_transaction_id = TransactionId(
account_id=self.transaction_id.account_id, valid_start=chunk_valid_start
)
self._transaction_ids.append(chunk_transaction_id)
return super().freeze_with(client)
@overload
def execute(
self,
client: Client,
timeout: int | float | None = None,
wait_for_receipt: Literal[True] = True,
validate_status: bool = False,
) -> TransactionReceipt: ...
@overload
def execute(
self,
client: Client,
timeout: int | float | None = None,
wait_for_receipt: Literal[False] = False,
validate_status: bool = False,
) -> TransactionResponse: ...
def execute(
self,
client: Client,
timeout: int | float | None = None,
wait_for_receipt: bool = True,
validate_status: bool = False,
) -> TransactionReceipt | TransactionResponse:
"""
Executes the file append transaction.
For multi-chunk transactions, this method will execute all chunks sequentially and return first response.
Args:
client: The client to execute the transaction with.
timeout (int | float | None, optional): The total execution timeout (in seconds) for this execution.
wait_for_receipt (bool, optional): Whether to wait for consensus and return the receipt.
If False, the method returns a TransactionResponse immediately after submission.
validate_status: (bool): Whether the query should automatically validate the transaction status (default False).
Returns:
TransactionReceipt: If wait_for_receipt is True (default)
TransactionResponse: If wait_for_receipt is False
"""
# Return the first response (as per JavaScript implementation)
return self.execute_all(client, timeout, wait_for_receipt, validate_status)[0]
@overload
def execute_all(
self,
client: Client,
timeout: int | float | None = None,
wait_for_receipt: Literal[True] = True,
validate_status: bool = False,
) -> list[TransactionReceipt]: ...
@overload
def execute_all(
self,
client: Client,
timeout: int | float | None = None,
wait_for_receipt: Literal[False] = False,
validate_status: bool = False,
) -> list[TransactionResponse]: ...
def execute_all(
self,
client: Client,
timeout: int | float | None = None,
wait_for_receipt: bool = True,
validate_status: bool = False,
) -> list[TransactionReceipt] | list[TransactionResponse]:
"""
Executes the file append transaction.
This method will execute all chunks sequentially and return list of response for each chunked
Args:
client: The client to execute the transaction with.
timeout (int | float | None, optional): The total execution timeout (in seconds) for this execution.
wait_for_receipt (bool, optional): Whether to wait for consensus and return the receipt.
If False, the method returns a TransactionResponse immediately after submission.
validate_status: (bool): Whether the query should automatically validate the transaction status (default False).
Returns:
List[TransactionReceipt]: If wait_for_receipt is True (default)
List[TransactionResponse]: If wait_for_receipt is False
"""
self._validate_chunking()
if self.get_required_chunks() == 1:
# Single chunk transaction
return [super().execute(client, timeout, wait_for_receipt, validate_status)]
# Multi-chunk transaction - execute all chunks
responses = []
for chunk_index in range(self.get_required_chunks()):
self._current_chunk_index = chunk_index
# Set the transaction ID for this chunk
if self._transaction_ids and chunk_index < len(self._transaction_ids):
self.transaction_id = self._transaction_ids[chunk_index]
# Clear the frozen state to allow rebuilding with new transaction ID
self._transaction_body_bytes.clear()
self._signature_map.clear()
# Freeze the transaction for this chunk if not already frozen
self.freeze_with(client)
# Sign with all stored signing keys for this chunk
for signing_key in self._signing_keys:
# Call parent sign directly to avoid modifying _signing_keys
super().sign(signing_key)
# Execute the chunk
response = super().execute(client, timeout, wait_for_receipt, validate_status)
responses.append(response)
return responses
def sign(self, private_key: PrivateKey) -> FileAppendTransaction:
"""
Signs the transaction using the provided private key.
For multi-chunk transactions, this stores the signing key for later use.
Args:
private_key (PrivateKey): The private key to sign the transaction with.
Returns:
FileAppendTransaction: The current transaction instance for method chaining.
"""
# Store the signing key for multi-chunk transactions (avoid duplicates)
if private_key not in self._signing_keys:
self._signing_keys.append(private_key)
# Call the parent sign method for the current transaction
super().sign(private_key)
return self
@property
def body_size_all_chunks(self) -> list[int]:
"""Returns an array of body sizes for transactions with multiple chunks."""
self._require_frozen()
sizes = []
original_index = self._current_chunk_index
original_transaction_id = self.transaction_id
try:
for i, transaction_id in enumerate(self._transaction_ids):
self._current_chunk_index = i
self.transaction_id = transaction_id
sizes.append(self.body_size)
finally:
self._current_chunk_index = original_index
self.transaction_id = original_transaction_id
return sizes