PyOTA Types¶
PyOTA defines a few types that will make it easy for you to model objects like Transactions and Bundles in your own code.
Since everything in IOTA is represented as a sequence of trits
and trytes
,
let us take a look on how you can work with them in PyOTA.
TryteString¶
-
class
iota.
TryteString
(trytes: Union[AnyStr, bytearray, TryteString], pad: Optional[int] = None)¶ A string representation of a sequence of trytes.
A
TryteString
is an ASCII representation of a sequence of trytes. In many respects, it is similar to a Pythonbytes
object (which is an ASCII representation of a sequence of bytes).In fact, the two objects behave very similarly; they support concatenation, comparison, can be used as dict keys, etc.
However, unlike
bytes
, aTryteString
can only contain uppercase letters and the number 9 (as a regular expression:^[A-Z9]*$
).Important
A TryteString does not represent a numeric value!
- Parameters
trytes (TrytesCompatible) – Byte string or bytearray.
pad (Optional[int]) –
Ensure at least this many trytes.
If there are too few, null trytes will be appended to the TryteString.
Note
If the TryteString is too long, it will not be truncated!
Example usage:
from iota import TryteString
# Create a TryteString object from bytes.
trytes_1 = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA')
# Ensure the created object is 81 trytes long by padding it with zeros.
# The value zero is represented with character '9' in trytes.
trytes_1 = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA', pad=81)
# Create a TryteString object from text type.
# Note that this will throw error if text contains unsupported characters.
trytes_2 = TryteString('LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD')
# Comparison and concatenation:
if trytes_1 != trytes_2:
trytes_combined = trytes_1 + trytes_2
# As dictionary keys:
index = {
trytes_1: 42,
trytes_2: 86,
}
As you go through the API documentation, you will see many references to
TryteString
and its subclasses:
Fragment
: A signature or message fragment inside a transaction. Fragments are always 2187 trytes long.Hash
: An object identifier. Hashes are always 81 trytes long. There are many different types of hashes:Address
: Identifies an address on the Tangle.BundleHash
: Identifies a bundle on the Tangle.TransactionHash
: Identifies a transaction on the Tangle.Seed
: A TryteString that is used for crypto functions such as generating addresses, signing inputs, etc. Seeds can be any length, but 81 trytes offers the best security.Tag
: A tag used to classify a transaction. Tags are always 27 trytes long.TransactionTrytes
: A TryteString representation of a transaction on the Tangle.TransactionTrytes
are always 2673 trytes long.
Let’s explore the capabilities of the TryteString
base class.
Encoding¶
You may use classmethods to create a TryteString
from bytes
,
unicode string
or from a list of trits
.
from_bytes¶
-
classmethod
TryteString.
from_bytes
(bytes_: Union[bytes, bytearray], codec: str = 'trytes_ascii', *args: Any, **kwargs: Any) → T¶ Creates a TryteString from a sequence of bytes.
- Parameters
bytes_ (Union[bytes,bytearray]) – Source bytes. ASCII representation of a sequence of bytes. Note that only tryte alphabet supported!
codec (str) – Reserved for future use. Currently supports only the ‘trytes_ascii’ codec. See https://github.com/iotaledger/iota.py/issues/62 for more information.
args – Additional positional arguments to pass to the initializer.
kwargs – Additional keyword arguments to pass to the initializer.
- Returns
TryteString
object.
Example usage:
from iota import TryteString message_trytes = TryteString.from_bytes(b'HELLO999IOTA')
from_unicode¶
-
classmethod
TryteString.
from_unicode
(string: str, *args: Any, **kwargs: Any) → T¶ Creates a TryteString from a Unicode string.
- Parameters
string (str) – Source Unicode string.
args – Additional positional arguments to pass to the initializer.
kwargs – Additional keyword arguments to pass to the initializer.
- Returns
TryteString
object.
Example usage:
from iota import TryteString message_trytes = TryteString.from_unicode('Hello, IOTA!')
Note
PyOTA also supports encoding non-ASCII characters, but this functionality is experimental and has not yet been evaluated by the IOTA community!
Until this feature has been standardized, it is recommended that you only
use ASCII characters when generating TryteString
objects from
character strings.
from_trits¶
-
classmethod
TryteString.
from_trits
(trits: Iterable[int], *args: Any, **kwargs: Any) → T¶ Creates a TryteString from a sequence of trits.
- Parameters
trits (Iterable[int]) – Iterable of trit values (-1, 0, 1).
args – Additional positional arguments to pass to the initializer.
kwargs – Additional keyword arguments to pass to the initializer.
- Returns
TryteString
object.
Example usage:
from iota import TryteString message_trytes = TryteString.from_trits( [1, 0, -1, -1, 1, 0, 1, -1, 0, -1, 1, 0, 0, 1, 0, 0, 1, 0, -1, 1, 1, -1, 1, 0] )
References:
int_from_trits()
from_trytes¶
-
classmethod
TryteString.
from_trytes
(trytes: Iterable[Iterable[int]], *args: Any, **kwargs: Any) → T¶ Creates a TryteString from a sequence of trytes.
- Parameters
trytes (Iterable[Iterable[int]]) –
Iterable of tryte values.
In this context, a tryte is defined as a list containing 3 trits.
args – Additional positional arguments to pass to the initializer.
kwargs – Additional keyword arguments to pass to the initializer.
- Returns
TryteString
object.
Example usage:
from iota import TryteString message_trytes = TryteString.from_trytes( [ [1, 0, -1], [-1, 1, 0], [1, -1, 0], [-1, 1, 0], [0, 1, 0], [0, 1, 0], [-1, 1, 1], [-1, 1, 0], ] )
References:
Additionally, you can encode a TryteString
into a lower-level
primitive (usually bytes). This might be useful when the TryteString
contains ASCII encoded characters but you need it as bytes
. See the example
below:
encode¶
-
TryteString.
encode
(errors: str = 'strict', codec: str = 'trytes_ascii') → bytes¶ Encodes the TryteString into a lower-level primitive (usually bytes).
- Parameters
errors (str) –
How to handle trytes that can’t be converted:
- ’strict’
raise an exception (recommended).
- ’replace’
replace with ‘?’.
- ’ignore’
omit the tryte from the result.
codec (str) –
Reserved for future use.
See https://github.com/iotaledger/iota.py/issues/62 for more information.
- Raises
iota.codecs.TrytesDecodeError
if the trytes cannot be decoded into bytes.
- Returns
Python
bytes
object.
Example usage:
from iota import TryteString # Message payload as unicode string message = 'Hello, iota!' # Create TryteString message_trytes = TryteString.from_unicode(message) # Encode TryteString into bytes encoded_message_bytes = message_trytes.encode() # This will be b'Hello, iota' print(encoded_message_bytes) # Get the original message decoded = encoded_message_bytes.decode() print(decoded == message)
Decoding¶
You can also convert a tryte sequence into characters using
TryteString.decode()
. Note that not every tryte sequence can be
converted; garbage in, garbage out!
decode¶
-
TryteString.
decode
(errors: str = 'strict', strip_padding: bool = True) → str¶ Decodes the TryteString into a higher-level abstraction (usually Unicode characters).
- Parameters
errors (str) –
How to handle trytes that can’t be converted, or bytes that can’t be decoded using UTF-8:
- ’strict’
raise an exception (recommended).
- ’replace’
replace with a placeholder character.
- ’ignore’
omit the invalid tryte/byte sequence.
strip_padding (bool) – Whether to strip trailing null trytes before converting.
- Raises
iota.codecs.TrytesDecodeError
if the trytes cannot be decoded into bytes.UnicodeDecodeError
if the resulting bytes cannot be decoded using UTF-8.
- Returns
Unicode string
object.
Example usage:
from iota import TryteString trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') message = trytes.decode()
as_json_compatible¶
-
TryteString.
as_json_compatible
() → str¶ Returns a JSON-compatible representation of the object.
References:
iota.json.JsonEncoder
.
- Returns
JSON-compatible representation of the object (string).
Example usage:
from iota import TryteString trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') json_payload = trytes.as_json_compatible()
as_integers¶
-
TryteString.
as_integers
() → List[int]¶ Converts the TryteString into a sequence of integers.
Each integer is a value between -13 and 13.
See the tryte alphabet for more info.
- Returns
List[int]
Example usage:
from iota import TryteString trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') tryte_ints = trytes.as_integers()
as_trytes¶
-
TryteString.
as_trytes
() → List[List[int]]¶ Converts the TryteString into a sequence of trytes.
Each tryte is represented as a list with 3 trit values.
See
as_trits()
for more info.Important
TryteString
is not a numeric type, so the result of this method should not be interpreted as an integer!- Returns
List[List[int]]
Example usage:
from iota import TryteString trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') tryte_list = trytes.as_trytes()
as_trits¶
-
TryteString.
as_trits
() → List[int]¶ Converts the TryteString into a sequence of trit values.
A trit may have value 1, 0, or -1.
References:
Important
TryteString
is not a numeric type, so the result of this method should not be interpreted as an integer!- Returns
List[int]
Example usage:
from iota import TryteString trytes = TryteString(b'RBTC9D9DCDQAEASBYBCCKBFA') trits = trytes.as_trits()
Generation¶
random¶
-
classmethod
TryteString.
random
(length: Optional[int] = None) → T¶ Generates a random sequence of trytes.
- Parameters
length (Optional[int]) – Number of trytes to generate.
- Returns
TryteString
object.- Raises
TypeError –
if
length
is negative,if
length
is not defined, and the class doesn’t haveLEN
attribute.
Seed¶
-
class
iota.
Seed
(trytes: Union[AnyStr, bytearray, TryteString, None] = None)¶ An
iota.TryteString
that acts as a seed for crypto functions.Note: This class is identical to
iota.TryteString
, but it has a distinct type so that seeds can be identified in Python code.IMPORTANT: For maximum security, a seed must be EXACTLY 81 trytes!
- Parameters
trytes (TrytesCompatible) – Byte string or bytearray.
- Raises
Warning – if
trytes
are longer than 81 trytes in length.
References:
random¶
-
classmethod
Seed.
random
(length: int = 81) → iota.crypto.types.Seed¶ Generates a random seed using a CSPRNG.
- Parameters
length (int) –
Length of seed, in trytes.
For maximum security, this should always be set to 81, but you can change it if you’re 110% sure you know what you’re doing.
See https://iota.stackexchange.com/q/249 for more info.
- Returns
iota.Seed
object.
Example usage:
from iota import Seed my_seed = Seed.random() print(my_seed)
Address¶
-
class
iota.
Address
(trytes: Union[AnyStr, bytearray, TryteString], balance: Optional[int] = None, key_index: Optional[int] = None, security_level: Optional[int] = None)¶ A
TryteString
that acts as an address, with support for generating and validating checksums.- Parameters
trytes (TrytesCompatible) – Object to construct the address from.
balance (Optional[int]) – Known balance of the address.
key_index (Optional[int]) – Index of the address that was used during address generation. Must be greater than zero.
security_level (Optional[int]) – Security level that was used during address generation. Might be 1, 2 or 3.
- :raises
ValueError: if
trytes
is longer than 81 trytes, unless it is exactly 90 trytes long (address + checksum).
-
address
: TryteString = None¶ Address trytes without the checksum.
-
balance
= None¶ Balance owned by this address. Defaults to
None
; usually set via thegetInputs
command.References:
-
key_index
= None¶ Index of the key used to generate this address. Defaults to
None
; usually set viaAddressGenerator
.References:
-
security_level
= None¶ Number of hashes in the digest that was used to generate this address.
as_json_compatible¶
-
Address.
as_json_compatible
() → Dict[str, Union[str, int]]¶ Returns a JSON-compatible representation of the Address.
- Returns
dict
with the following structure:{ 'trytes': str, 'balance': int, 'key_index': int, 'security_level': int, }
Example usage:
from iota import Address # Example address only, do not use in your code! addy = Address( b'LVHHIXQNYKWQMGXGLFOKOCDFHPKXAUKWMSZVDRAT' b'TICUZXFACM9DNJELJGMLMK99KDVVOOWLINVBZIGWZ' ) print(addy.as_json_compatible())
is_checksum_valid¶
-
Address.
is_checksum_valid
() → bool¶ Returns whether this address has a valid checksum.
- Returns
bool
Example usage:
from iota import Address # Example address only, do not use in your code! addy = Address( b'LVHHIXQNYKWQMGXGLFOKOCDFHPKXAUKWMSZVDRAT' b'TICUZXFACM9DNJELJGMLMK99KDVVOOWLINVBZIGWZ' ) # Should be ``False`` print(addy.is_checksum_valid()) addy.add_checksum() # Should be ``True`` print(addy.is_checksum_valid())
with_valid_checksum¶
-
Address.
with_valid_checksum
() → iota.types.Address¶ Returns the address with a valid checksum attached.
- Returns
Address
object.
Example usage:
from iota import Address # Example address only, do not use in your code! addy = Address( b'LVHHIXQNYKWQMGXGLFOKOCDFHPKXAUKWMSZVDRAT' b'TICUZXFACM9DNJELJGMLMK99KDVVOOWLINVBZIGWZ' ) addy_with_checksum = addy.with_valid_checksum() print(addy_with_checksum) # Should be ``True`` print(addy_with_checksum.is_checksum_valid())
add_checksum¶
-
Address.
add_checksum
() → None¶ Adds checksum to
Address
object.- Returns
None
Example usage:
from iota import Address # Example address only, do not use in your code! addy = Address( b'LVHHIXQNYKWQMGXGLFOKOCDFHPKXAUKWMSZVDRAT' b'TICUZXFACM9DNJELJGMLMK99KDVVOOWLINVBZIGWZ' ) # Should be ``False`` print(addy.is_checksum_valid()) print(addy.checksum) addy.add_checksum() # Should be ``True`` print(addy.is_checksum_valid()) print(addy.checksum)
remove_checksum¶
-
Address.
remove_checksum
() → None¶ Removes checksum from
Address
object.- Returns
None
Example usage:
from iota import Address # Example address only, do not use in your code! addy = Address( b'LVHHIXQNYKWQMGXGLFOKOCDFHPKXAUKWMSZVDRAT' b'TICUZXFACM9DNJELJGMLMK99KDVVOOWLINVBZIGWZ' b'AACAMCWUW' # 9 checksum trytes ) # Should be ``True`` print(addy.is_checksum_valid()) print(addy.checksum) addy.remove_checksum() # Should be ``False`` print(addy.is_checksum_valid()) print(addy.checksum)
AddressChecksum¶
-
class
iota.
AddressChecksum
(trytes: Union[AnyStr, bytearray, TryteString])¶ A
TryteString
that acts as an address checksum.- Parameters
trytes (TrytesCompatible) – Checksum trytes.
- Raises
ValueError – if
trytes
is not exactly 9 trytes in length.
-
LEN
= 9¶ Length of an address checksum.
Hash¶
-
class
iota.
Hash
(trytes: Union[AnyStr, bytearray, TryteString])¶ A
TryteString
that is exactly one hash long.- Parameters
trytes (TrytesCompatible) – Object to construct the hash from.
- Raises
ValueError – if
trytes
is longer than 81 trytes.
-
LEN
= 81¶ Length is always 81 trytes long.
TransactionHash¶
-
class
iota.
TransactionHash
(trytes: Union[AnyStr, bytearray, TryteString])¶ An
TryteString
(Hash
) that acts as a transaction hash.
BundleHash¶
-
class
iota.
BundleHash
(trytes: Union[AnyStr, bytearray, TryteString])¶ An
TryteString
(Hash
) that acts as a bundle hash.
TransactionTrytes¶
-
class
iota.
TransactionTrytes
(trytes: Union[AnyStr, bytearray, TryteString])¶ An
TryteString
representation of a Transaction.- Raises
ValueError – if
trytes
is longer than 2673 trytes in length.
-
LEN
= 2673¶ Length of a transaction in trytes.
Fragment¶
-
class
iota.
Fragment
(trytes: Union[AnyStr, bytearray, TryteString])¶ An
TryteString
representation of a signature/message fragment in a transaction.- Raises
ValueError – if
trytes
is longer than 2187 trytes in length.
-
LEN
= 2187¶ Length of a fragment in trytes.
Nonce¶
-
class
iota.
Nonce
(trytes: Union[AnyStr, bytearray, TryteString])¶ An
TryteString
that acts as a transaction nonce.- Raises
ValueError – if
trytes
is longer than 27 trytes in length.
-
LEN
= 27¶ Length of a nonce in trytes.
Tag¶
Transaction Types¶
PyOTA defines two different types used to represent transactions:
Transaction
for transactions that have already been attached to the Tangle. Generally, you will never need to createTransaction
objects; the API will build them for you, as the result of various API methods.
ProposedTransaction
for transactions that have been created locally and have not been broadcast yet.
Transaction¶
Each Transaction
object has several instance attributes that you
may manipulate and properties you can use to extract their values as trytes.
See the class documentation below:
-
class
iota.
Transaction
(hash_: Optional[iota.transaction.types.TransactionHash], signature_message_fragment: Optional[iota.transaction.types.Fragment], address: iota.types.Address, value: int, timestamp: int, current_index: Optional[int], last_index: Optional[int], bundle_hash: Optional[iota.transaction.types.BundleHash], trunk_transaction_hash: Optional[iota.transaction.types.TransactionHash], branch_transaction_hash: Optional[iota.transaction.types.TransactionHash], tag: Optional[iota.types.Tag], attachment_timestamp: Optional[int], attachment_timestamp_lower_bound: Optional[int], attachment_timestamp_upper_bound: Optional[int], nonce: Optional[iota.transaction.types.Nonce], legacy_tag: Optional[iota.types.Tag] = None)¶ A transaction that has been attached to the Tangle.
- Parameters
hash (Optional[TransactionHash]) – Transaction ID
signature_message_fragment (Optional[Fragment]) – Signature or message fragment.
address (Address) – The address associated with this transaction.
value (int) – Value of the transaction in iotas. Can be negative as well (spending from address).
timestamp (int) – Unix timestamp in seconds.
current_index (Optional[int]) – Index of the transaction within the bundle.
last_index (Optional[int]) – Index of head transaction in the bundle.
bundle_hash (Optional[BundleHash]) – Bundle hash of the bundle containing the transaction.
trunk_transaction_hash (Optional[TransactionHash]) – Hash of trunk transaction.
branch_transaction_hash (Optional[TransactionHash]) – Hash of branch transaction.
tag (Optional[Tag]) – Optional classification tag applied to this transaction.
attachment_timestamp (Optional[int]) – Unix timestamp in milliseconds, decribes when the proof-of-work for this transaction was done.
attachment_timestamp_lower_bound (Optional[int]) – Unix timestamp in milliseconds, lower bound of attachment.
attachment_timestamp_upper_bound (Optional[int]) – Unix timestamp in milliseconds, upper bound of attachment.
nonce (Optional[Nonce]) – Unique value used to increase security of the transaction hash. Result of the proof-of-work aglorithm.
legacy_tag (Optional[Tag]) – Optional classification legacy_tag applied to this transaction.
- Returns
Transaction
object.
-
address
: Address = None¶ The address associated with this transaction.
Depending on the transaction’s
value
, this address may be a sender or a recipient. Ifvalue
is != 0, the associated address’ balance is adjusted as a result of this transaction.- Type
-
attachment_timestamp
: Optional[int] = None¶ Estimated epoch time of the attachment to the tangle.
Decribes when the proof-of-work for this transaction was done.
- Type
int
, unix timestamp in milliseconds,
-
property
attachment_timestamp_as_trytes
¶ Returns a TryteString representation of the transaction’s
attachment_timestamp
.
-
attachment_timestamp_lower_bound
: Optional[int] = None¶ The lowest possible epoch time of the attachment to the tangle.
- Type
int
, unix timestamp in milliseconds.
-
property
attachment_timestamp_lower_bound_as_trytes
¶ Returns a TryteString representation of the transaction’s
attachment_timestamp_lower_bound
.
-
attachment_timestamp_upper_bound
: Optional[int] = None¶ The highest possible epoch time of the attachment to the tangle.
- Type
int
, unix timestamp in milliseconds.
-
property
attachment_timestamp_upper_bound_as_trytes
¶ Returns a TryteString representation of the transaction’s
attachment_timestamp_upper_bound
.
-
branch_transaction_hash
: Optional[TransactionHash] = None¶ An unrelated transaction that this transaction “approves”.
In order to add a transaction to the Tangle, the client must perform PoW to “approve” two existing transactions, called the “trunk” and “branch” transactions.
The branch transaction may be selected strategically to maximize the bundle’s chances of getting confirmed; otherwise it usually has no significance.
- Type
-
bundle_hash
: Optional[BundleHash] = None¶ The bundle hash, used to identify transactions that are part of the same bundle.
This value is generated by taking a hash of the metadata from all transactions in the bundle.
- Type
-
current_index
: Optional[int] = None¶ The position of the transaction inside the bundle.
If the
current_index
value is 0, then this is the “head transaction”.If it is equal to
last_index
, then this is the “tail transaction”.
For value transfers, the “spend” transaction is generally in the 0th position, followed by inputs, and the “change” transaction is last.
- Type
int
-
property
current_index_as_trytes
¶ Returns a TryteString representation of the transaction’s
current_index
.
-
hash
: TransactionHash = None¶ The transaction hash, used to uniquely identify the transaction on the Tangle.
This value is generated by taking a hash of the raw transaction trits.
- Type
-
is_confirmed
: bool = None¶ Whether this transaction has been confirmed by neighbor nodes. Must be set manually via the
getInclusionStates
API command.- Type
Optional[bool]
References:
-
property
is_tail
¶ Returns whether this transaction is a tail (first one in the bundle).
Because of the way the Tangle is organized, the tail transaction is generally the last one in the bundle that gets attached, even though it occupies the first logical position inside the bundle.
-
last_index
: Optional[int] = None¶ The index of the final transaction in the bundle.
This value is attached to every transaction to make it easier to traverse and verify bundles.
- Type
int
-
property
last_index_as_trytes
¶ Returns a TryteString representation of the transaction’s
last_index
.
-
property
legacy_tag
¶ Return the legacy tag of the transaction. If no legacy tag was set, returns the tag instead.
-
nonce
: Optional[Nonce] = None¶ Unique value used to increase security of the transaction hash.
This is the product of the PoW process.
- Type
-
signature_message_fragment
: Optional[Fragment] = None¶ “Signature/Message Fragment” (note the slash):
For inputs, this contains a fragment of the cryptographic signature, used to verify the transaction (depending on the security level of the corresponding address, the entire signature is usually too large to fit into a single transaction, so it is split across multiple transactions instead).
For other transactions, this contains a fragment of the message attached to the transaction (if any). This can be pretty much any value. Like signatures, the message may be split across multiple transactions if it is too large to fit inside a single transaction.
- Type
-
tag
: Optional[Tag] = None¶ Optional classification tag applied to this transaction.
Many transactions have empty tags (
Tag(b'999999999999999999999999999')
).- Type
-
timestamp
: int = None¶ Timestamp used to increase the security of the transaction hash.
Describes when the transaction was created.
Important
This value is easy to forge! Do not rely on it when resolving conflicts!
- Type
int
, unix timestamp in seconds.
-
trunk_transaction_hash
: Optional[TransactionHash] = None¶ The transaction hash of the next transaction in the bundle.
In order to add a transaction to the Tangle, the client must perform PoW to “approve” two existing transactions, called the “trunk” and “branch” transactions.
The trunk transaction is generally used to link transactions within a bundle.
- Type
-
value
: int = None¶ The number of iotas being transferred in this transaction:
If this value is negative, then the
address
is spending iotas.If it is positive, then the
address
is receiving iotas.If it is zero, then this transaction is being used to carry metadata (such as a signature fragment or a message) instead of transferring iotas.
- Type
int
as_json_compatible¶
-
Transaction.
as_json_compatible
() → dict¶ Returns a JSON-compatible representation of the object.
- Returns
dict
with the following structure:{ 'hash_': TransactionHash, 'signature_message_fragment': Fragment, 'address': Address, 'value': int, 'legacy_tag': Tag, 'timestamp': int, 'current_index': int, 'last_index': int, 'bundle_hash': BundleHash, 'trunk_transaction_hash': TransactionHash, 'branch_transaction_hash': TransactionHash, 'tag': Tag, 'attachment_timestamp': int, 'attachment_timestamp_lower_bound': int, 'attachment_timestamp_upper_bound': int, 'nonce': Nonce, }
References:
iota.json.JsonEncoder
.
as_tryte_string¶
-
Transaction.
as_tryte_string
() → iota.transaction.types.TransactionTrytes¶ Returns a TryteString representation of the transaction.
- Returns
TryteString
object.
from_tryte_string¶
-
classmethod
Transaction.
from_tryte_string
(trytes: Union[AnyStr, bytearray, TryteString], hash_: Optional[iota.transaction.types.TransactionHash] = None) → T¶ Creates a Transaction object from a sequence of trytes.
- Parameters
trytes (TrytesCompatible) – Raw trytes. Should be exactly 2673 trytes long.
hash (Optional[TransactionHash]) –
The transaction hash, if available.
If not provided, it will be computed from the transaction trytes.
- Returns
Transaction
object.
Example usage:
from iota import Transaction txn =\ Transaction.from_tryte_string( b'GYPRVHBEZOOFXSHQBLCYW9ICTCISLHDBNMMVYD9JJHQMPQCTIQAQTJNNNJ9IDXLRCC' b'OYOXYPCLR9PBEY9ORZIEPPDNTI9CQWYZUOTAVBXPSBOFEQAPFLWXSWUIUSJMSJIIIZ' b'WIKIRH9GCOEVZFKNXEVCUCIIWZQCQEUVRZOCMEL9AMGXJNMLJCIA9UWGRPPHCEOPTS' b'VPKPPPCMQXYBHMSODTWUOABPKWFFFQJHCBVYXLHEWPD9YUDFTGNCYAKQKVEZYRBQRB' b'XIAUX9SVEDUKGMTWQIYXRGSWYRK9SRONVGTW9YGHSZRIXWGPCCUCDRMAXBPDFVHSRY' b'WHGB9DQSQFQKSNICGPIPTRZINYRXQAFSWSEWIFRMSBMGTNYPRWFSOIIWWT9IDSELM9' b'JUOOWFNCCSHUSMGNROBFJX9JQ9XT9PKEGQYQAWAFPRVRRVQPUQBHLSNTEFCDKBWRCD' b'X9EYOBB9KPMTLNNQLADBDLZPRVBCKVCYQEOLARJYAGTBFR9QLPKZBOYWZQOVKCVYRG' b'YI9ZEFIQRKYXLJBZJDBJDJVQZCGYQMROVHNDBLGNLQODPUXFNTADDVYNZJUVPGB9LV' b'PJIYLAPBOEHPMRWUIAJXVQOEM9ROEYUOTNLXVVQEYRQWDTQGDLEYFIYNDPRAIXOZEB' b'CS9P99AZTQQLKEILEVXMSHBIDHLXKUOMMNFKPYHONKEYDCHMUNTTNRYVMMEYHPGASP' b'ZXASKRUPWQSHDMU9VPS99ZZ9SJJYFUJFFMFORBYDILBXCAVJDPDFHTTTIYOVGLRDYR' b'TKHXJORJVYRPTDH9ZCPZ9ZADXZFRSFPIQKWLBRNTWJHXTOAUOL9FVGTUMMPYGYICJD' b'XMOESEVDJWLMCVTJLPIEKBE9JTHDQWV9MRMEWFLPWGJFLUXI9BXPSVWCMUWLZSEWHB' b'DZKXOLYNOZAPOYLQVZAQMOHGTTQEUAOVKVRRGAHNGPUEKHFVPVCOYSJAWHZU9DRROH' b'BETBAFTATVAUGOEGCAYUXACLSSHHVYDHMDGJP9AUCLWLNTFEVGQGHQXSKEMVOVSKQE' b'EWHWZUDTYOBGCURRZSJZLFVQQAAYQO9TRLFFN9HTDQXBSPPJYXMNGLLBHOMNVXNOWE' b'IDMJVCLLDFHBDONQJCJVLBLCSMDOUQCKKCQJMGTSTHBXPXAMLMSXRIPUBMBAWBFNLH' b'LUJTRJLDERLZFUBUSMF999XNHLEEXEENQJNOFFPNPQ9PQICHSATPLZVMVIWLRTKYPI' b'XNFGYWOJSQDAXGFHKZPFLPXQEHCYEAGTIWIJEZTAVLNUMAFWGGLXMBNUQTOFCNLJTC' b'DMWVVZGVBSEBCPFSM99FLOIDTCLUGPSEDLOKZUAEVBLWNMODGZBWOVQT9DPFOTSKRA' b'BQAVOQ9RXWBMAKFYNDCZOJGTCIDMQSQQSODKDXTPFLNOKSIZEOY9HFUTLQRXQMEPGO' b'XQGLLPNSXAUCYPGZMNWMQWSWCKAQYKXJTWINSGPPZG9HLDLEAWUWEVCTVRCBDFOXKU' b'ROXH9HXXAXVPEJFRSLOGRVGYZASTEBAQNXJJROCYRTDPYFUIQJVDHAKEG9YACV9HCP' b'JUEUKOYFNWDXCCJBIFQKYOXGRDHVTHEQUMHO999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999999999999999999999999999999999999' b'999999999999RKWEEVD99A99999999A99999999NFDPEEZCWVYLKZGSLCQNOFUSENI' b'XRHWWTZFBXMPSQHEDFWZULBZFEOMNLRNIDQKDNNIELAOXOVMYEI9PGTKORV9IKTJZQ' b'UBQAWTKBKZ9NEZHBFIMCLV9TTNJNQZUIJDFPTTCTKBJRHAITVSKUCUEMD9M9SQJ999' b'999TKORV9IKTJZQUBQAWTKBKZ9NEZHBFIMCLV9TTNJNQZUIJDFPTTCTKBJRHAITVSK' b'UCUEMD9M9SQJ999999999999999999999999999999999999999999999999999999' b'999999999999999999999999999999999' )
get_bundle_essence_trytes¶
-
Transaction.
get_bundle_essence_trytes
() → iota.types.TryteString¶ Returns the values needed for calculating bundle hash. The bundle hash is the hash of the bundle essence, which is itself the hash of the following fields of transactions in the bundle:
address
,value
,legacy_tag
,current_index
,last_index
,and
timestamp
.
The transaction’s
signature_message_fragment
field contains the signature generated by signing the bundle hash with the address’s private key.- Returns
TryteString
object.
ProposedTransaction¶
-
class
iota.
ProposedTransaction
(address: iota.types.Address, value: int, tag: Optional[iota.types.Tag] = None, message: Optional[iota.types.TryteString] = None, timestamp: Optional[int] = None)¶ A transaction that has not yet been attached to the Tangle.
Proposed transactions are created locally. Note that for creation, only a small subset of the
Transaction
attributes is needed.Provide to
Iota.send_transfer()
to attach to tangle and publish/store.Note
In order to follow naming convention of other libs, you may use the name
Transfer
interchangeably withProposedTransaction
. See https://github.com/iotaledger/iota.py/issues/72 for more info.- Parameters
address (Address) – Address associated with the transaction.
value (int) – Transaction value.
tag (Optional[Tag]) – Optional classification tag applied to this transaction.
message (Optional[TryteString]) – Message to be included in
transaction.Transaction.signature_or_message_fragment
field of the transaction. Should not be longer thantransaction.Fragment.LEN
.timestamp (Optional[int]) – Timestamp of transaction creation. If not supplied, the library will generate it.
- Returns
iota.ProposedTransaction
object.
Example usage:
txn=\ ProposedTransaction( address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999XE9IVG' b'EFNDOCQCMERGUATCIEGGOHPHGFIAQEZGNHQ9W99CH' ), message = TryteString.from_unicode('thx fur cheezburgers'), tag = Tag(b'KITTENS'), value = 42, )
as_tryte_string¶
-
ProposedTransaction.
as_tryte_string
() → iota.types.TryteString¶ Returns a TryteString representation of the transaction.
- Returns
TryteString
object.- Raises
RuntimeError – if the transaction doesn’t have a bundle hash field, meaning that the bundle containing the transaction hasn’t been finalized yet.
Bundle Types¶
As with transactions, PyOTA defines two different types to represent bundles:
Bundle
for bundles that have already been broadcast to the Tangle. Generally, you will never need to createBundle
objects; the API will build them for you, as the result of various API methods.
ProposedBundle
for bundles that have been created locally and have not been broadcast yet.
Bundle¶
-
class
iota.
Bundle
(transactions: Optional[Iterable[iota.transaction.base.Transaction]] = None)¶ A collection of transactions, treated as an atomic unit when attached to the Tangle.
Note: unlike a block in a blockchain, bundles are not first-class citizens in IOTA; only transactions get stored in the Tangle.
Instead, Bundles must be inferred by following linked transactions with the same bundle hash.
- Parameters
transactions (Optional[Iterable[Transaction]]) – Transactions in the bundle. Note that transactions will be sorted into ascending order based on their
current_index
.- Returns
Bundle
object.
References:
-
property
hash
¶ Returns the hash of the bundle.
This value is determined by inspecting the bundle’s tail transaction, so in a few edge cases, it may be incorrect.
- Returns
BundleHash
object, orIf the bundle has no transactions, this method returns
None
.
-
property
is_confirmed
¶ Returns whether this bundle has been confirmed by neighbor nodes.
This attribute must be set manually.
- Returns
bool
References:
-
property
tail_transaction
¶ Returns the tail transaction of the bundle.
- Returns
-
transactions
: List[Transaction] = None¶ List of
Transaction
objects that are in the bundle.
as_json_compatible¶
-
Bundle.
as_json_compatible
() → List[dict]¶ Returns a JSON-compatible representation of the object.
- Returns
List[dict]
. Thedict
list elements contain individual transactions as inTransaction.as_json_compatible()
.
References:
iota.json.JsonEncoder
.
as_tryte_strings¶
-
Bundle.
as_tryte_strings
(head_to_tail: bool = False) → List[iota.transaction.types.TransactionTrytes]¶ Returns TryteString representations of the transactions in this bundle.
- Parameters
head_to_tail (bool) –
Determines the order of the transactions:
True
: head txn first, tail txn last.False
(default): tail txn first, head txn last.
Note that the order is reversed by default, as this is the way bundles are typically broadcast to the Tangle.
- Returns
List[TransactionTrytes]
from_tryte_strings¶
-
classmethod
Bundle.
from_tryte_strings
(trytes: Iterable[iota.types.TryteString]) → B¶ Creates a Bundle object from a list of tryte values.
Note, that this is effectively calling
Transaction.from_tryte_string()
on the iterbale elements and constructing the bundle from the created transactions.- Parameters
trytes (Iterable[TryteString]) – List of raw transaction trytes.
- Returns
Bundle
object.
Example usage:
from iota import Bundle bundle = Bundle.from_tryte_strings([ b'GYPRVHBEZOOFXSHQBLCYW9ICTCISLHDBNMMVYD9JJHQMPQCTIQAQTJNNNJ9IDXLRCC...', b'OYOXYPCLR9PBEY9ORZIEPPDNTI9CQWYZUOTAVBXPSBOFEQAPFLWXSWUIUSJMSJIIIZ...', # etc. ])
get_messages¶
-
Bundle.
get_messages
(errors: str = 'drop') → List[str]¶ Attempts to decipher encoded messages from the transactions in the bundle.
- Parameters
errors (str) –
How to handle trytes that can’t be converted, or bytes that can’t be decoded using UTF-8:
- ’drop’
Drop the trytes from the result.
- ’strict’
Raise an exception.
- ’replace’
Replace with a placeholder character.
- ’ignore’
Omit the invalid tryte/byte sequence.
- Returns
List[str]
ProposedBundle¶
Note
This section contains information about how PyOTA works “under the hood”.
The Iota.prepare_transfer()
API method encapsulates this
functionality for you; it is not necessary to understand how
ProposedBundle
works in order to use PyOTA.
-
class
iota.
ProposedBundle
(transactions: Optional[Iterable[iota.transaction.creation.ProposedTransaction]] = None, inputs: Optional[Iterable[iota.types.Address]] = None, change_address: Optional[iota.types.Address] = None)¶ A collection of proposed transactions, to be treated as an atomic unit when attached to the Tangle.
- Parameters
transactions (Optional[Iterable[ProposedTransaction]]) – Proposed transactions that should be put into the proposed bundle.
inputs (Optional[Iterable[Address]]) –
Addresses that hold iotas to fund outgoing transactions in the bundle. If provided, the library will create and sign withdrawing transactions from these addresses.
See
Iota.get_inputs()
for more info.change_address (Optional[Address]) – Due to the signatures scheme of IOTA, you can only spend once from an address. Therefore the library will always deduct the full available amount from an input address. The unused tokens will be sent to
change_address
if provided, or to a newly-generated and unused address if not.
- Returns
-
property
balance
¶ Returns the bundle balance. In order for a bundle to be valid, its balance must be 0:
A positive balance means that there aren’t enough inputs to cover the spent amount; add more inputs using
add_inputs()
.A negative balance means that there are unspent inputs; use
send_unspent_inputs_to()
to send the unspent inputs to a “change” address.
- Returns
bool
-
property
tag
¶ Determines the most relevant tag for the bundle.
- Returns
transaction.Tag
ProposedBundle
provides a convenient interface for creating new
bundles, listed in the order that they should be invoked:
add_transaction¶
-
ProposedBundle.
add_transaction
(transaction: iota.transaction.creation.ProposedTransaction) → None¶ Adds a transaction to the bundle.
If the transaction message is too long, it will be split automatically into multiple transactions.
- Parameters
transaction (ProposedTransaction) – The transaction to be added.
- Raises
RuntimeError – if bundle is already finalized
ValueError – if trying to add a spending transaction. Use
add_inputs()
instead.
add_inputs¶
-
ProposedBundle.
add_inputs
(inputs: Iterable[iota.types.Address]) → None¶ Specifies inputs that can be used to fund transactions that spend iotas.
The
ProposedBundle
will use these to create the necessary input transactions.Note that each input may require multiple transactions, in order to hold the entire signature.
- Parameters
inputs (Iterable[Address]) –
Addresses to use as the inputs for this bundle.
Important
Must have
balance
andkey_index
attributes! UseIota.get_inputs()
to prepare inputs.- Raises
RuntimeError – if bundle is already finalized.
ValueError –
if input address has no
balance
.if input address has no
key_index
.
send_unspent_inputs_to¶
-
ProposedBundle.
send_unspent_inputs_to
(address: iota.types.Address) → None¶ Specifies the address that will receive unspent iotas.
The
ProposedBundle
will use this to create the necessary change transaction, if necessary.If the bundle has no unspent inputs, this method does nothing.
- Parameters
address (Address) – Address to send unspent inputs to.
- Raises
RuntimeError – if bundle is already finalized.
add_signature_or_message¶
-
ProposedBundle.
add_signature_or_message
(fragments: Iterable[iota.transaction.types.Fragment], start_index: Optional[int] = 0) → None¶ Adds signature/message fragments to transactions in the bundle starting at start_index. If a transaction already has a fragment, it will be overwritten.
- Parameters
fragments (Iterable[Fragment]) – List of fragments to add. Use [Fragment(…),Fragment(…),…] to create this argument. Fragment() accepts any TryteString compatible type, or types that can be converted to TryteStrings (bytearray, unicode string, etc.). If the payload is less than
FRAGMENT_LENGTH
, it will pad it with 9s.start_index (int) – Index of transaction in bundle from where addition shoudl start.
- Raises
RuntimeError – if bundle is already finalized.
ValueError –
if empty list is provided for
fragments
if wrong
start_index
is provided.if
fragments
is too long and does’t fit into the bundle.
TypeError –
if
fragments
is not anIterable
if
fragments
contains other types thanFragment
.
finalize¶
-
ProposedBundle.
finalize
() → None¶ Finalizes the bundle, preparing it to be attached to the Tangle.
This operation includes checking if the bundle has zero balance, generating the bundle hash and updating the transactions with it, furthermore to initialize signature/message fragment fields.
Once this method is invoked, no new transactions may be added to the bundle.
- Raises
RuntimeError – if bundle is already finalized.
ValueError –
if bundle has no transactions.
if bundle has unspent inputs (there is no
change_address
attribute specified.)if inputs are insufficient to cover bundle spend.
sign_inputs¶
-
ProposedBundle.
sign_inputs
(key_generator: iota.crypto.signing.KeyGenerator) → None¶ Sign inputs in a finalized bundle.
Generates the necessary cryptographic signatures to authorize spending the inputs.
Note
You do not need to invoke this method if the bundle does not contain any transactions that spend iotas.
- Parameters
key_generator (KeyGenerator) – Generator to create private keys for signing.
- Raises
RuntimeError – if bundle is not yet finalized.
ValueError –
if the input transaction specifies an address that doesn’t have
key_index
attribute defined.if the input transaction specifies an address that doesn’t have
security_level
attribute defined.
sign_input_at¶
-
ProposedBundle.
sign_input_at
(start_index: int, private_key: iota.crypto.types.PrivateKey) → None¶ Signs the input at the specified index.
- Parameters
start_index (int) –
The index of the first input transaction.
If necessary, the resulting signature will be split across multiple transactions automatically (i.e., if an input has
security_level=2
, you still only need to callsign_input_at()
once).private_key (PrivateKey) –
The private key that will be used to generate the signature.
Important
Be sure that the private key was generated using the correct seed, or the resulting signature will be invalid!
- Raises
RuntimeError – if bundle is not yet finalized.
as_json_compatible¶
-
ProposedBundle.
as_json_compatible
() → List[dict]¶ Returns a JSON-compatible representation of the object.
- Returns
List[dict]
. Thedict
list elements contain individual transactions as inProposedTransaction.as_json_compatible()
.
References:
iota.json.JsonEncoder
.
Example usage¶
from iota import Address, ProposedBundle, ProposedTransaction
from iota.crypto.signing import KeyGenerator
bundle = ProposedBundle()
bundle.add_transaction(ProposedTransaction(...))
bundle.add_transaction(ProposedTransaction(...))
bundle.add_transaction(ProposedTransaction(...))
bundle.add_inputs([
Address(
address =
b'TESTVALUE9DONTUSEINPRODUCTION99999HAA9UA'
b'MHCGKEUGYFUBIARAXBFASGLCHCBEVGTBDCSAEBTBM',
balance = 86,
key_index = 0,
),
])
bundle.send_unspent_inputs_to(
Address(
b'TESTVALUE9DONTUSEINPRODUCTION99999D99HEA'
b'M9XADCPFJDFANCIHR9OBDHTAGGE9TGCI9EO9ZCRBN'
),
)
bundle.finalize()
bundle.sign_inputs(KeyGenerator(b'SEED9GOES9HERE'))
Once the ProposedBundle
has been finalized (and inputs signed, if
necessary), invoke its ProposedBundle.as_tryte_strings()
method to
generate the raw trytes that should be included in an
Iota.attach_to_tangle()
API request.