Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python binding: rename block types #1766

Merged
merged 9 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions bindings/python/examples/client/06_simple_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
TaggedDataPayload(
utf8_to_hex("tag"),
utf8_to_hex("data")))[0]
signed_block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(signed_block)
block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(block)

print(f'Empty block sent: {os.environ["EXPLORER_URL"]}/block/{block_id}')
8 changes: 4 additions & 4 deletions bindings/python/examples/client/08_data_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
from dataclasses import asdict
from dotenv import load_dotenv
from iota_sdk import BasicBlock, Bip44, CoinType, Client, utf8_to_hex, hex_to_utf8, TaggedDataPayload, MnemonicSecretManager, SecretManager
from iota_sdk import BasicBlockBody, Bip44, CoinType, Client, utf8_to_hex, hex_to_utf8, TaggedDataPayload, MnemonicSecretManager, SecretManager

load_dotenv()

Expand All @@ -27,14 +27,14 @@
TaggedDataPayload(
utf8_to_hex("tag"),
utf8_to_hex("data")))[0]
signed_block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(signed_block)
block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(block)

print(f'Data block sent: {os.environ["EXPLORER_URL"]}/block/{block_id}')

block = client.get_block(block_id).block

if isinstance(block, BasicBlock):
if isinstance(block, BasicBlockBody):
print(f'Block data: {json.dumps(asdict(block), indent=4)}')

payload = block.payload
Expand Down
4 changes: 2 additions & 2 deletions bindings/python/examples/client/post_raw_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@
TaggedDataPayload(
utf8_to_hex("tag"),
utf8_to_hex("data")))[0]
signed_block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(signed_block)
block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(block)
blockBytes = client.get_block_raw(block_id)

# Post raw block
Expand Down
10 changes: 5 additions & 5 deletions bindings/python/examples/client/submit_and_read_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
# Make sure you have first installed it with `pip install iota_sdk`
import os
from dotenv import load_dotenv
from iota_sdk import BasicBlock, Bip44, Client, CoinType, hex_to_utf8, utf8_to_hex, TaggedDataPayload, MnemonicSecretManager, SecretManager
from iota_sdk import BasicBlockBody, Bip44, Client, CoinType, hex_to_utf8, utf8_to_hex, TaggedDataPayload, MnemonicSecretManager, SecretManager

load_dotenv()

Expand Down Expand Up @@ -70,14 +70,14 @@
TaggedDataPayload(
utf8_to_hex("tag"),
utf8_to_hex("data")))
signed_block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(signed_block)
block = secret_manager.sign_block(unsigned_block, chain)
block_id = client.post_block(block)

print('\nThe block ID for your submitted block is:')
print(f' {block_id}')

print('\nMetadata for your submitted block is:')
print(f' {signed_block}')
print(f' {block}')

########################################################
# Step 3: Use the block ID to read the payload back
Expand All @@ -92,7 +92,7 @@

# Get the whole block
block = client.get_block(block_id).block
if isinstance(block, BasicBlock):
if isinstance(block, BasicBlockBody):
payload_out = block.payload
tag_hex_out = block.payload.tag
message_hex_out = block.payload.data
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@
from .prefix_hex import *
from .types.address import *
from .types.balance import *
from .types.block.basic import *
from .types.block.block import *
from .types.block.body.basic import *
from .types.block.body.type import *
from .types.block.body.validation import *
from .types.block.metadata import *
from .types.block.signed_block import *
from .types.block.validation import *
from .types.block_builder_options import *
from .types.block_issuer_key import *
from .types.burn import *
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/client/_high_level_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from typing import List, Optional
from dataclasses import dataclass
from abc import ABCMeta, abstractmethod
from iota_sdk.types.block.signed_block import SignedBlock
from iota_sdk.types.block.block import Block
from iota_sdk.types.common import CoinType, HexStr, json
from iota_sdk.types.output_metadata import OutputWithMetadata
from iota_sdk.types.output_id import OutputId
Expand Down Expand Up @@ -111,7 +111,7 @@ def get_outputs_ignore_errors(
})
return [OutputWithMetadata.from_dict(o) for o in outputs]

def find_blocks(self, block_ids: List[HexStr]) -> List[SignedBlock]:
def find_blocks(self, block_ids: List[HexStr]) -> List[Block]:
"""Find all blocks by provided block IDs.

Args:
Expand All @@ -123,7 +123,7 @@ def find_blocks(self, block_ids: List[HexStr]) -> List[SignedBlock]:
blocks = self._call_method('findBlocks', {
'blockIds': block_ids
})
return [SignedBlock.from_dict(block) for block in blocks]
return [Block.from_dict(block) for block in blocks]

def find_inputs(self, addresses: List[str], amount: int):
"""Function to find inputs from addresses for a provided amount(useful for offline signing).
Expand Down
12 changes: 6 additions & 6 deletions bindings/python/iota_sdk/client/_node_core_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from abc import ABCMeta, abstractmethod
from dacite import from_dict

from iota_sdk.types.block.signed_block import SignedBlock
from iota_sdk.types.block.block import Block
from iota_sdk.types.block.metadata import BlockMetadata, BlockWithMetadata
from iota_sdk.types.common import HexStr
from iota_sdk.types.node_info import NodeInfo, NodeInfoWrapper
Expand Down Expand Up @@ -75,7 +75,7 @@ def get_tips(self) -> List[HexStr]:
"""
return self._call_method('getTips')

def post_block(self, block: SignedBlock) -> HexStr:
def post_block(self, block: Block) -> HexStr:
"""Post a block.

Args:
Expand All @@ -88,10 +88,10 @@ def post_block(self, block: SignedBlock) -> HexStr:
'block': block.__dict__
})

def get_block(self, block_id: HexStr) -> SignedBlock:
def get_block(self, block_id: HexStr) -> Block:
"""Get the block corresponding to the given block id.
"""
return SignedBlock.from_dict(self._call_method('getBlock', {
return Block.from_dict(self._call_method('getBlock', {
'blockId': block_id
}))

Expand Down Expand Up @@ -152,13 +152,13 @@ def get_output_metadata(
'outputId': output_id_str
}))

def get_included_block(self, transaction_id: HexStr) -> SignedBlock:
def get_included_block(self, transaction_id: HexStr) -> Block:
"""Returns the included block of the given transaction.

Returns:
The included block.
"""
return SignedBlock.from_dict(self._call_method('getIncludedBlock', {
return Block.from_dict(self._call_method('getIncludedBlock', {
'transactionId': transaction_id
}))

Expand Down
2 changes: 1 addition & 1 deletion bindings/python/iota_sdk/client/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def _call_method(self, name, data=None):
"""

# pylint: disable=redefined-builtin
def hex_to_bech32(self, hex: HexStr, bech32_hrp: str) -> str:
def hex_to_bech32(self, hex_str: HexStr, bech32_hrp: str) -> str:
"""Transforms a hex encoded address to a bech32 encoded address.
"""
return self._call_method('hexToBech32', {
Expand Down
2 changes: 1 addition & 1 deletion bindings/python/iota_sdk/client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from iota_sdk.client._node_indexer_api import NodeIndexerAPI
from iota_sdk.client._high_level_api import HighLevelAPI
from iota_sdk.client._utils import ClientUtils
from iota_sdk.types.block.signed_block import UnsignedBlock
from iota_sdk.types.block.block import UnsignedBlock
from iota_sdk.types.common import HexStr, Node
from iota_sdk.types.feature import Feature
from iota_sdk.types.network_info import NetworkInfo
Expand Down
6 changes: 3 additions & 3 deletions bindings/python/iota_sdk/secret_manager/secret_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import humps

from iota_sdk.external import create_secret_manager, call_secret_manager_method
from iota_sdk.types.block.signed_block import SignedBlock, UnsignedBlock
from iota_sdk.types.block.block import Block, UnsignedBlock
from iota_sdk.types.common import HexStr
from iota_sdk.types.signature import Ed25519Signature, Bip44
from iota_sdk.types.transaction_data import PreparedTransactionData
Expand Down Expand Up @@ -280,14 +280,14 @@ def sign_transaction(
}))

def sign_block(
self, unsigned_block: UnsignedBlock, chain: Bip44) -> SignedBlock:
self, unsigned_block: UnsignedBlock, chain: Bip44) -> Block:
"""Sign a block.

Args:
unsigned_block: The unsigned block data.
chain: The Bip44 chain to use.
"""
return from_dict(SignedBlock, self._call_method('signBlock', {
return from_dict(Block, self._call_method('signBlock', {
'unsignedBlock': unsigned_block.to_dict(),
'chain': chain.to_dict()
}))
Expand Down
77 changes: 70 additions & 7 deletions bindings/python/iota_sdk/types/block/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,78 @@
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations
from enum import IntEnum
from dataclasses import dataclass, field
from typing import TypeAlias, Union
from dataclasses_json import config
from iota_sdk.utils import Utils
from iota_sdk.types.common import HexStr, json, SlotIndex
from iota_sdk.types.node_info import ProtocolParameters
from iota_sdk.types.signature import Signature
from iota_sdk.types.block.body.basic import BasicBlockBody
from iota_sdk.types.block.body.validation import ValidationBlockBody


class BlockType(IntEnum):
"""Block types.
@json
@dataclass
class Block:
"""A block that can hold either a `BasicBlockBody` or a `ValidationBlockBody`.
Shared data is stored alongside such a block in the header fields.

Attributes:
Basic (0): A Basic Block.
Validation (1): A Validation Block.
protocol_version: Protocol version of the network to which this block belongs.
network_id: The identifier of the network to which this block belongs.
issuing_time: The time at which the block was issued. It is a Unix timestamp in nanoseconds.
slot_commitment_id: The identifier of the slot to which this block commits.
latest_finalized_slot: The slot index of the latest finalized slot.
issuer_id: The identifier of the account that issued this block.
body: Holds either a `BasicBlockBody` or a `ValidationBlockBody`.
signature: The Block signature.
"""
Basic = 0
Validation = 1
protocol_version: int
network_id: int = field(metadata=config(
encoder=str
))
issuing_time: int = field(metadata=config(
encoder=str
))
slot_commitment_id: HexStr
latest_finalized_slot: SlotIndex
issuer_id: HexStr
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved
body: BlockBody
signature: Signature

def id(self, params: ProtocolParameters) -> HexStr:
"""Returns the block ID as a hexadecimal string.
"""
return Utils.block_id(self, params)


@json
@dataclass
class UnsignedBlock:
"""An unsigned block type that can hold either a `BasicBlock` or a `ValidationBlock`.
Shared data is stored alongside such a block in the header fields.

Attributes:
protocol_version: Protocol version of the network to which this block belongs.
network_id: The identifier of the network to which this block belongs.
issuing_time: The time at which the block was issued. It is a Unix timestamp in nanoseconds.
slot_commitment_id: The identifier of the slot to which this block commits.
latest_finalized_slot: The slot index of the latest finalized slot.
issuer_id: The identifier of the account that issued this block.
block: Holds either a `BasicBlock` or a `ValidationBlock`.
"""
protocol_version: int
network_id: int = field(metadata=config(
encoder=str
))
issuing_time: int = field(metadata=config(
encoder=str
))
slot_commitment_id: HexStr
latest_finalized_slot: SlotIndex
issuer_id: HexStr
body: BlockBody


BlockBody: TypeAlias = Union[BasicBlockBody, ValidationBlockBody]
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@
from dataclasses import dataclass, field
from typing import List, Optional
from dataclasses_json import config
from iota_sdk.types.block.block import BlockType
from iota_sdk.types.block.body.type import BlockBodyType
from iota_sdk.types.common import HexStr, json
from iota_sdk.types.payload import Payload


@json
@dataclass
class BasicBlock:
"""A `BasicBlock` is the most common type of block used to issue various kinds of payloads such as transactions
class BasicBlockBody:
"""A Basic Block Body is the most common type of block body used to issue various kinds of payloads such as transactions
at the cost of burning Mana.

Attributes:
Expand All @@ -31,5 +31,5 @@ class BasicBlock:
shallow_like_parents: Optional[List[HexStr]] = None
payload: Optional[Payload] = None
type: int = field(
default_factory=lambda: int(BlockType.Basic),
default_factory=lambda: int(BlockBodyType.Basic),
init=False)
16 changes: 16 additions & 0 deletions bindings/python/iota_sdk/types/block/body/type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Copyright 2023 IOTA Stiftung
# SPDX-License-Identifier: Apache-2.0

from __future__ import annotations
from enum import IntEnum


class BlockBodyType(IntEnum):
"""Block Body types.

Attributes:
Basic (0): A Basic Block Body.
Validation (1): A Validation Block Body.
"""
Basic = 0
Validation = 1
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional
from iota_sdk.types.block.block import BlockType
from iota_sdk.types.block.body.type import BlockBodyType
from iota_sdk.types.common import HexStr, json


@json
@dataclass
class ValidationBlock:
"""A Validation Block is a special type of block used by validators to secure the network. It is recognized by the
class ValidationBlockBody:
"""A Validation Block Body is a special type of block body used by validators to secure the network. It is recognized by the
Congestion Control of the IOTA 2.0 protocol and can be issued without burning Mana within the constraints of the
allowed validator throughput. It is allowed to reference more parent blocks than a normal Basic Block.

Expand All @@ -28,5 +28,5 @@ class ValidationBlock:
weak_parents: Optional[List[HexStr]] = None
shallow_like_parents: Optional[List[HexStr]] = None
type: int = field(
default_factory=lambda: int(BlockType.Validation),
default_factory=lambda: int(BlockBodyType.Validation),
init=False)
5 changes: 2 additions & 3 deletions bindings/python/iota_sdk/types/block/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
from dataclasses import dataclass
from typing import Optional
from iota_sdk.types.common import HexStr, json
# TODO rename change to Block
from iota_sdk.types.block.signed_block import SignedBlock
from iota_sdk.types.block.block import Block


@json
Expand Down Expand Up @@ -196,5 +195,5 @@ class BlockWithMetadata:
block: The block.
metadata: The block metadata.
"""
block: SignedBlock
block: Block
metadata: BlockMetadata
Loading
Loading