mirror of
https://github.com/planetmint/planetmint.git
synced 2025-11-24 06:25:45 +00:00
fixed linting errors
Signed-off-by: Jürgen Eckel <juergen@riddleandcode.com>
This commit is contained in:
parent
a35f705865
commit
ea05872927
@ -25,30 +25,30 @@ class Output(object):
|
|||||||
owners before a Transaction was confirmed.
|
owners before a Transaction was confirmed.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
MAX_AMOUNT = 9 * 10 ** 18
|
MAX_AMOUNT = 9 * 10**18
|
||||||
|
|
||||||
def __init__(self, fulfillment, public_keys=None, amount=1):
|
def __init__(self, fulfillment, public_keys=None, amount=1):
|
||||||
"""Create an instance of a :class:`~.Output`.
|
"""Create an instance of a :class:`~.Output`.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
fulfillment (:class:`cryptoconditions.Fulfillment`): A
|
fulfillment (:class:`cryptoconditions.Fulfillment`): A
|
||||||
Fulfillment to extract a Condition from.
|
Fulfillment to extract a Condition from.
|
||||||
public_keys (:obj:`list` of :obj:`str`, optional): A list of
|
public_keys (:obj:`list` of :obj:`str`, optional): A list of
|
||||||
owners before a Transaction was confirmed.
|
owners before a Transaction was confirmed.
|
||||||
amount (int): The amount of Assets to be locked with this
|
amount (int): The amount of Assets to be locked with this
|
||||||
Output.
|
Output.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: if `public_keys` is not instance of `list`.
|
TypeError: if `public_keys` is not instance of `list`.
|
||||||
"""
|
"""
|
||||||
if not isinstance(public_keys, list) and public_keys is not None:
|
if not isinstance(public_keys, list) and public_keys is not None:
|
||||||
raise TypeError('`public_keys` must be a list instance or None')
|
raise TypeError("`public_keys` must be a list instance or None")
|
||||||
if not isinstance(amount, int):
|
if not isinstance(amount, int):
|
||||||
raise TypeError('`amount` must be an int')
|
raise TypeError("`amount` must be an int")
|
||||||
if amount < 1:
|
if amount < 1:
|
||||||
raise AmountError('`amount` must be greater than 0')
|
raise AmountError("`amount` must be greater than 0")
|
||||||
if amount > self.MAX_AMOUNT:
|
if amount > self.MAX_AMOUNT:
|
||||||
raise AmountError('`amount` must be <= %s' % self.MAX_AMOUNT)
|
raise AmountError("`amount` must be <= %s" % self.MAX_AMOUNT)
|
||||||
|
|
||||||
self.fulfillment = fulfillment
|
self.fulfillment = fulfillment
|
||||||
self.amount = amount
|
self.amount = amount
|
||||||
@ -61,31 +61,31 @@ class Output(object):
|
|||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
"""Transforms the object to a Python dictionary.
|
"""Transforms the object to a Python dictionary.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
A dictionary serialization of the Input the Output was
|
A dictionary serialization of the Input the Output was
|
||||||
derived from is always provided.
|
derived from is always provided.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict: The Output as an alternative serialization format.
|
dict: The Output as an alternative serialization format.
|
||||||
"""
|
"""
|
||||||
# TODO FOR CC: It must be able to recognize a hashlock condition
|
# TODO FOR CC: It must be able to recognize a hashlock condition
|
||||||
# and fulfillment!
|
# and fulfillment!
|
||||||
condition = {}
|
condition = {}
|
||||||
try:
|
try:
|
||||||
# TODO verify if a script is returned in case of zenroom fulfillments
|
# TODO verify if a script is returned in case of zenroom fulfillments
|
||||||
condition['details'] = _fulfillment_to_details(self.fulfillment)
|
condition["details"] = _fulfillment_to_details(self.fulfillment)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
try:
|
try:
|
||||||
condition['uri'] = self.fulfillment.condition_uri
|
condition["uri"] = self.fulfillment.condition_uri
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
condition['uri'] = self.fulfillment
|
condition["uri"] = self.fulfillment
|
||||||
|
|
||||||
output = {
|
output = {
|
||||||
'public_keys': self.public_keys,
|
"public_keys": self.public_keys,
|
||||||
'condition': condition,
|
"condition": condition,
|
||||||
'amount': str(self.amount),
|
"amount": str(self.amount),
|
||||||
}
|
}
|
||||||
return output
|
return output
|
||||||
|
|
||||||
@ -93,69 +93,65 @@ class Output(object):
|
|||||||
def generate(cls, public_keys, amount):
|
def generate(cls, public_keys, amount):
|
||||||
"""Generates a Output from a specifically formed tuple or list.
|
"""Generates a Output from a specifically formed tuple or list.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
If a ThresholdCondition has to be generated where the threshold
|
If a ThresholdCondition has to be generated where the threshold
|
||||||
is always the number of subconditions it is split between, a
|
is always the number of subconditions it is split between, a
|
||||||
list of the following structure is sufficient:
|
list of the following structure is sufficient:
|
||||||
|
|
||||||
[(address|condition)*, [(address|condition)*, ...], ...]
|
[(address|condition)*, [(address|condition)*, ...], ...]
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
public_keys (:obj:`list` of :obj:`str`): The public key of
|
public_keys (:obj:`list` of :obj:`str`): The public key of
|
||||||
the users that should be able to fulfill the Condition
|
the users that should be able to fulfill the Condition
|
||||||
that is being created.
|
that is being created.
|
||||||
amount (:obj:`int`): The amount locked by the Output.
|
amount (:obj:`int`): The amount locked by the Output.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
An Output that can be used in a Transaction.
|
An Output that can be used in a Transaction.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
TypeError: If `public_keys` is not an instance of `list`.
|
TypeError: If `public_keys` is not an instance of `list`.
|
||||||
ValueError: If `public_keys` is an empty list.
|
ValueError: If `public_keys` is an empty list.
|
||||||
"""
|
"""
|
||||||
threshold = len(public_keys)
|
threshold = len(public_keys)
|
||||||
if not isinstance(amount, int):
|
if not isinstance(amount, int):
|
||||||
raise TypeError('`amount` must be a int')
|
raise TypeError("`amount` must be a int")
|
||||||
if amount < 1:
|
if amount < 1:
|
||||||
raise AmountError('`amount` needs to be greater than zero')
|
raise AmountError("`amount` needs to be greater than zero")
|
||||||
if not isinstance(public_keys, list):
|
if not isinstance(public_keys, list):
|
||||||
raise TypeError('`public_keys` must be an instance of list')
|
raise TypeError("`public_keys` must be an instance of list")
|
||||||
if len(public_keys) == 0:
|
if len(public_keys) == 0:
|
||||||
raise ValueError('`public_keys` needs to contain at least one'
|
raise ValueError("`public_keys` needs to contain at least one" "owner")
|
||||||
'owner')
|
|
||||||
elif len(public_keys) == 1 and not isinstance(public_keys[0], list):
|
elif len(public_keys) == 1 and not isinstance(public_keys[0], list):
|
||||||
if isinstance(public_keys[0], Fulfillment):
|
if isinstance(public_keys[0], Fulfillment):
|
||||||
ffill = public_keys[0]
|
ffill = public_keys[0]
|
||||||
elif isinstance( public_keys[0], ZenroomSha256):
|
elif isinstance(public_keys[0], ZenroomSha256):
|
||||||
ffill = ZenroomSha256(
|
ffill = ZenroomSha256(public_key=base58.b58decode(public_keys[0]))
|
||||||
public_key=base58.b58decode(public_keys[0]))
|
|
||||||
else:
|
else:
|
||||||
ffill = Ed25519Sha256(
|
ffill = Ed25519Sha256(public_key=base58.b58decode(public_keys[0]))
|
||||||
public_key=base58.b58decode(public_keys[0]))
|
|
||||||
return cls(ffill, public_keys, amount=amount)
|
return cls(ffill, public_keys, amount=amount)
|
||||||
else:
|
else:
|
||||||
initial_cond = ThresholdSha256(threshold=threshold)
|
initial_cond = ThresholdSha256(threshold=threshold)
|
||||||
threshold_cond = reduce(cls._gen_condition, public_keys,
|
threshold_cond = reduce(cls._gen_condition, public_keys, initial_cond)
|
||||||
initial_cond)
|
|
||||||
return cls(threshold_cond, public_keys, amount=amount)
|
return cls(threshold_cond, public_keys, amount=amount)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _gen_condition(cls, initial, new_public_keys):
|
def _gen_condition(cls, initial, new_public_keys):
|
||||||
"""Generates ThresholdSha256 conditions from a list of new owners.
|
"""Generates ThresholdSha256 conditions from a list of new owners.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
This method is intended only to be used with a reduce function.
|
This method is intended only to be used with a reduce function.
|
||||||
For a description on how to use this method, see
|
For a description on how to use this method, see
|
||||||
:meth:`~.Output.generate`.
|
:meth:`~.Output.generate`.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
initial (:class:`cryptoconditions.ThresholdSha256`):
|
initial (:class:`cryptoconditions.ThresholdSha256`):
|
||||||
A Condition representing the overall root.
|
A Condition representing the overall root.
|
||||||
new_public_keys (:obj:`list` of :obj:`str`|str): A list of new
|
new_public_keys (:obj:`list` of :obj:`str`|str): A list of new
|
||||||
owners or a single new owner.
|
owners or a single new owner.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:class:`cryptoconditions.ThresholdSha256`:
|
:class:`cryptoconditions.ThresholdSha256`:
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
threshold = len(new_public_keys)
|
threshold = len(new_public_keys)
|
||||||
@ -166,7 +162,7 @@ class Output(object):
|
|||||||
ffill = ThresholdSha256(threshold=threshold)
|
ffill = ThresholdSha256(threshold=threshold)
|
||||||
reduce(cls._gen_condition, new_public_keys, ffill)
|
reduce(cls._gen_condition, new_public_keys, ffill)
|
||||||
elif isinstance(new_public_keys, list) and len(new_public_keys) <= 1:
|
elif isinstance(new_public_keys, list) and len(new_public_keys) <= 1:
|
||||||
raise ValueError('Sublist cannot contain single owner')
|
raise ValueError("Sublist cannot contain single owner")
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
new_public_keys = new_public_keys.pop()
|
new_public_keys = new_public_keys.pop()
|
||||||
@ -181,8 +177,7 @@ class Output(object):
|
|||||||
if isinstance(new_public_keys, Fulfillment):
|
if isinstance(new_public_keys, Fulfillment):
|
||||||
ffill = new_public_keys
|
ffill = new_public_keys
|
||||||
else:
|
else:
|
||||||
ffill = Ed25519Sha256(
|
ffill = Ed25519Sha256(public_key=base58.b58decode(new_public_keys))
|
||||||
public_key=base58.b58decode(new_public_keys))
|
|
||||||
initial.add_subfulfillment(ffill)
|
initial.add_subfulfillment(ffill)
|
||||||
return initial
|
return initial
|
||||||
|
|
||||||
@ -190,25 +185,25 @@ class Output(object):
|
|||||||
def from_dict(cls, data):
|
def from_dict(cls, data):
|
||||||
"""Transforms a Python dictionary to an Output object.
|
"""Transforms a Python dictionary to an Output object.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
To pass a serialization cycle multiple times, a
|
To pass a serialization cycle multiple times, a
|
||||||
Cryptoconditions Fulfillment needs to be present in the
|
Cryptoconditions Fulfillment needs to be present in the
|
||||||
passed-in dictionary, as Condition URIs are not serializable
|
passed-in dictionary, as Condition URIs are not serializable
|
||||||
anymore.
|
anymore.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data (dict): The dict to be transformed.
|
data (dict): The dict to be transformed.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:class:`~planetmint.transactions.common.transaction.Output`
|
:class:`~planetmint.transactions.common.transaction.Output`
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
fulfillment = _fulfillment_from_details(data['condition']['details'])
|
fulfillment = _fulfillment_from_details(data["condition"]["details"])
|
||||||
except KeyError:
|
except KeyError:
|
||||||
# NOTE: Hashlock condition case
|
# NOTE: Hashlock condition case
|
||||||
fulfillment = data['condition']['uri']
|
fulfillment = data["condition"]["uri"]
|
||||||
try:
|
try:
|
||||||
amount = int(data['amount'])
|
amount = int(data["amount"])
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise AmountError('Invalid amount: %s' % data['amount'])
|
raise AmountError("Invalid amount: %s" % data["amount"])
|
||||||
return cls(fulfillment, data['public_keys'], amount)
|
return cls(fulfillment, data["public_keys"], amount)
|
||||||
|
|||||||
@ -18,8 +18,8 @@ import rapidjson
|
|||||||
|
|
||||||
import base58
|
import base58
|
||||||
from cryptoconditions import Fulfillment, ThresholdSha256, Ed25519Sha256, ZenroomSha256
|
from cryptoconditions import Fulfillment, ThresholdSha256, Ed25519Sha256, ZenroomSha256
|
||||||
from cryptoconditions.exceptions import (
|
from cryptoconditions.exceptions import ParsingError, ASN1DecodeError, ASN1EncodeError
|
||||||
ParsingError, ASN1DecodeError, ASN1EncodeError)
|
|
||||||
try:
|
try:
|
||||||
from hashlib import sha3_256
|
from hashlib import sha3_256
|
||||||
except ImportError:
|
except ImportError:
|
||||||
@ -27,8 +27,14 @@ except ImportError:
|
|||||||
|
|
||||||
from planetmint.transactions.common.crypto import PrivateKey, hash_data
|
from planetmint.transactions.common.crypto import PrivateKey, hash_data
|
||||||
from planetmint.transactions.common.exceptions import (
|
from planetmint.transactions.common.exceptions import (
|
||||||
KeypairMismatchException, InputDoesNotExist, DoubleSpend,
|
KeypairMismatchException,
|
||||||
InvalidHash, InvalidSignature, AmountError, AssetIdMismatch)
|
InputDoesNotExist,
|
||||||
|
DoubleSpend,
|
||||||
|
InvalidHash,
|
||||||
|
InvalidSignature,
|
||||||
|
AmountError,
|
||||||
|
AssetIdMismatch,
|
||||||
|
)
|
||||||
from planetmint.transactions.common.utils import serialize
|
from planetmint.transactions.common.utils import serialize
|
||||||
from .memoize import memoize_from_dict, memoize_to_dict
|
from .memoize import memoize_from_dict, memoize_to_dict
|
||||||
from .input import Input
|
from .input import Input
|
||||||
@ -36,92 +42,113 @@ from .output import Output
|
|||||||
from .transaction_link import TransactionLink
|
from .transaction_link import TransactionLink
|
||||||
|
|
||||||
UnspentOutput = namedtuple(
|
UnspentOutput = namedtuple(
|
||||||
'UnspentOutput', (
|
"UnspentOutput",
|
||||||
|
(
|
||||||
# TODO 'utxo_hash': sha3_256(f'{txid}{output_index}'.encode())
|
# TODO 'utxo_hash': sha3_256(f'{txid}{output_index}'.encode())
|
||||||
# 'utxo_hash', # noqa
|
# 'utxo_hash', # noqa
|
||||||
'transaction_id',
|
"transaction_id",
|
||||||
'output_index',
|
"output_index",
|
||||||
'amount',
|
"amount",
|
||||||
'asset_id',
|
"asset_id",
|
||||||
'condition_uri',
|
"condition_uri",
|
||||||
)
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class Transaction(object):
|
class Transaction(object):
|
||||||
"""A Transaction is used to create and transfer assets.
|
"""A Transaction is used to create and transfer assets.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
For adding Inputs and Outputs, this class provides methods
|
For adding Inputs and Outputs, this class provides methods
|
||||||
to do so.
|
to do so.
|
||||||
|
|
||||||
Attributes:
|
Attributes:
|
||||||
operation (str): Defines the operation of the Transaction.
|
operation (str): Defines the operation of the Transaction.
|
||||||
inputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
inputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
||||||
transaction.Input`, optional): Define the assets to
|
transaction.Input`, optional): Define the assets to
|
||||||
spend.
|
spend.
|
||||||
outputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
outputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
||||||
transaction.Output`, optional): Define the assets to lock.
|
transaction.Output`, optional): Define the assets to lock.
|
||||||
asset (dict): Asset payload for this Transaction. ``CREATE``
|
asset (dict): Asset payload for this Transaction. ``CREATE``
|
||||||
Transactions require a dict with a ``data``
|
Transactions require a dict with a ``data``
|
||||||
property while ``TRANSFER`` Transactions require a dict with a
|
property while ``TRANSFER`` Transactions require a dict with a
|
||||||
``id`` property.
|
``id`` property.
|
||||||
metadata (dict):
|
metadata (dict):
|
||||||
Metadata to be stored along with the Transaction.
|
Metadata to be stored along with the Transaction.
|
||||||
version (string): Defines the version number of a Transaction.
|
version (string): Defines the version number of a Transaction.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
CREATE = 'CREATE'
|
CREATE = "CREATE"
|
||||||
TRANSFER = 'TRANSFER'
|
TRANSFER = "TRANSFER"
|
||||||
ALLOWED_OPERATIONS = (CREATE, TRANSFER)
|
ALLOWED_OPERATIONS = (CREATE, TRANSFER)
|
||||||
VERSION = '2.0'
|
VERSION = "2.0"
|
||||||
|
|
||||||
def __init__(self, operation, asset, inputs=None, outputs=None,
|
def __init__(
|
||||||
metadata=None, version=None, hash_id=None, tx_dict=None):
|
self,
|
||||||
|
operation,
|
||||||
|
asset,
|
||||||
|
inputs=None,
|
||||||
|
outputs=None,
|
||||||
|
metadata=None,
|
||||||
|
version=None,
|
||||||
|
hash_id=None,
|
||||||
|
tx_dict=None,
|
||||||
|
):
|
||||||
"""The constructor allows to create a customizable Transaction.
|
"""The constructor allows to create a customizable Transaction.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
When no `version` is provided, one is being
|
When no `version` is provided, one is being
|
||||||
generated by this method.
|
generated by this method.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
operation (str): Defines the operation of the Transaction.
|
operation (str): Defines the operation of the Transaction.
|
||||||
asset (dict): Asset payload for this Transaction.
|
asset (dict): Asset payload for this Transaction.
|
||||||
inputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
inputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
||||||
transaction.Input`, optional): Define the assets to
|
transaction.Input`, optional): Define the assets to
|
||||||
outputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
outputs (:obj:`list` of :class:`~planetmint.transactions.common.
|
||||||
transaction.Output`, optional): Define the assets to
|
transaction.Output`, optional): Define the assets to
|
||||||
lock.
|
lock.
|
||||||
metadata (dict): Metadata to be stored along with the
|
metadata (dict): Metadata to be stored along with the
|
||||||
Transaction.
|
Transaction.
|
||||||
version (string): Defines the version number of a Transaction.
|
version (string): Defines the version number of a Transaction.
|
||||||
hash_id (string): Hash id of the transaction.
|
hash_id (string): Hash id of the transaction.
|
||||||
"""
|
"""
|
||||||
if operation not in self.ALLOWED_OPERATIONS:
|
if operation not in self.ALLOWED_OPERATIONS:
|
||||||
allowed_ops = ', '.join(self.__class__.ALLOWED_OPERATIONS)
|
allowed_ops = ", ".join(self.__class__.ALLOWED_OPERATIONS)
|
||||||
raise ValueError('`operation` must be one of {}'
|
raise ValueError("`operation` must be one of {}".format(allowed_ops))
|
||||||
.format(allowed_ops))
|
|
||||||
|
|
||||||
# Asset payloads for 'CREATE' operations must be None or
|
# Asset payloads for 'CREATE' operations must be None or
|
||||||
# dicts holding a `data` property. Asset payloads for 'TRANSFER'
|
# dicts holding a `data` property. Asset payloads for 'TRANSFER'
|
||||||
# operations must be dicts holding an `id` property.
|
# operations must be dicts holding an `id` property.
|
||||||
if (operation == self.CREATE and
|
if (
|
||||||
asset is not None and not (isinstance(asset, dict) and 'data' in asset)):
|
operation == self.CREATE
|
||||||
raise TypeError(('`asset` must be None or a dict holding a `data` '
|
and asset is not None
|
||||||
" property instance for '{}' Transactions".format(operation)))
|
and not (isinstance(asset, dict) and "data" in asset)
|
||||||
elif (operation == self.TRANSFER and
|
):
|
||||||
not (isinstance(asset, dict) and 'id' in asset)):
|
raise TypeError(
|
||||||
raise TypeError(('`asset` must be a dict holding an `id` property '
|
(
|
||||||
'for \'TRANSFER\' Transactions'))
|
"`asset` must be None or a dict holding a `data` "
|
||||||
|
" property instance for '{}' Transactions".format(operation)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
elif operation == self.TRANSFER and not (
|
||||||
|
isinstance(asset, dict) and "id" in asset
|
||||||
|
):
|
||||||
|
raise TypeError(
|
||||||
|
(
|
||||||
|
"`asset` must be a dict holding an `id` property "
|
||||||
|
"for 'TRANSFER' Transactions"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
if outputs and not isinstance(outputs, list):
|
if outputs and not isinstance(outputs, list):
|
||||||
raise TypeError('`outputs` must be a list instance or None')
|
raise TypeError("`outputs` must be a list instance or None")
|
||||||
|
|
||||||
if inputs and not isinstance(inputs, list):
|
if inputs and not isinstance(inputs, list):
|
||||||
raise TypeError('`inputs` must be a list instance or None')
|
raise TypeError("`inputs` must be a list instance or None")
|
||||||
|
|
||||||
if metadata is not None and not isinstance(metadata, dict):
|
if metadata is not None and not isinstance(metadata, dict):
|
||||||
raise TypeError('`metadata` must be a dict or None')
|
raise TypeError("`metadata` must be a dict or None")
|
||||||
|
|
||||||
self.version = version if version is not None else self.VERSION
|
self.version = version if version is not None else self.VERSION
|
||||||
self.operation = operation
|
self.operation = operation
|
||||||
@ -141,14 +168,17 @@ class Transaction(object):
|
|||||||
if self.operation == self.CREATE:
|
if self.operation == self.CREATE:
|
||||||
self._asset_id = self._id
|
self._asset_id = self._id
|
||||||
elif self.operation == self.TRANSFER:
|
elif self.operation == self.TRANSFER:
|
||||||
self._asset_id = self.asset['id']
|
self._asset_id = self.asset["id"]
|
||||||
return (UnspentOutput(
|
return (
|
||||||
transaction_id=self._id,
|
UnspentOutput(
|
||||||
output_index=output_index,
|
transaction_id=self._id,
|
||||||
amount=output.amount,
|
output_index=output_index,
|
||||||
asset_id=self._asset_id,
|
amount=output.amount,
|
||||||
condition_uri=output.fulfillment.condition_uri,
|
asset_id=self._asset_id,
|
||||||
) for output_index, output in enumerate(self.outputs))
|
condition_uri=output.fulfillment.condition_uri,
|
||||||
|
)
|
||||||
|
for output_index, output in enumerate(self.outputs)
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def spent_outputs(self):
|
def spent_outputs(self):
|
||||||
@ -156,10 +186,7 @@ class Transaction(object):
|
|||||||
is represented as a dictionary containing a transaction id and
|
is represented as a dictionary containing a transaction id and
|
||||||
output index.
|
output index.
|
||||||
"""
|
"""
|
||||||
return (
|
return (input_.fulfills.to_dict() for input_ in self.inputs if input_.fulfills)
|
||||||
input_.fulfills.to_dict()
|
|
||||||
for input_ in self.inputs if input_.fulfills
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def serialized(self):
|
def serialized(self):
|
||||||
@ -178,81 +205,83 @@ class Transaction(object):
|
|||||||
def to_inputs(self, indices=None):
|
def to_inputs(self, indices=None):
|
||||||
"""Converts a Transaction's outputs to spendable inputs.
|
"""Converts a Transaction's outputs to spendable inputs.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
Takes the Transaction's outputs and derives inputs
|
Takes the Transaction's outputs and derives inputs
|
||||||
from that can then be passed into `Transaction.transfer` as
|
from that can then be passed into `Transaction.transfer` as
|
||||||
`inputs`.
|
`inputs`.
|
||||||
A list of integers can be passed to `indices` that
|
A list of integers can be passed to `indices` that
|
||||||
defines which outputs should be returned as inputs.
|
defines which outputs should be returned as inputs.
|
||||||
If no `indices` are passed (empty list or None) all
|
If no `indices` are passed (empty list or None) all
|
||||||
outputs of the Transaction are returned.
|
outputs of the Transaction are returned.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
indices (:obj:`list` of int): Defines which
|
indices (:obj:`list` of int): Defines which
|
||||||
outputs should be returned as inputs.
|
outputs should be returned as inputs.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:obj:`list` of :class:`~planetmint.transactions.common.transaction.
|
:obj:`list` of :class:`~planetmint.transactions.common.transaction.
|
||||||
Input`
|
Input`
|
||||||
"""
|
"""
|
||||||
# NOTE: If no indices are passed, we just assume to take all outputs
|
# NOTE: If no indices are passed, we just assume to take all outputs
|
||||||
# as inputs.
|
# as inputs.
|
||||||
indices = indices or range(len(self.outputs))
|
indices = indices or range(len(self.outputs))
|
||||||
return [
|
return [
|
||||||
Input(self.outputs[idx].fulfillment,
|
Input(
|
||||||
self.outputs[idx].public_keys,
|
self.outputs[idx].fulfillment,
|
||||||
TransactionLink(self.id, idx))
|
self.outputs[idx].public_keys,
|
||||||
|
TransactionLink(self.id, idx),
|
||||||
|
)
|
||||||
for idx in indices
|
for idx in indices
|
||||||
]
|
]
|
||||||
|
|
||||||
def add_input(self, input_):
|
def add_input(self, input_):
|
||||||
"""Adds an input to a Transaction's list of inputs.
|
"""Adds an input to a Transaction's list of inputs.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_ (:class:`~planetmint.transactions.common.transaction.
|
input_ (:class:`~planetmint.transactions.common.transaction.
|
||||||
Input`): An Input to be added to the Transaction.
|
Input`): An Input to be added to the Transaction.
|
||||||
"""
|
"""
|
||||||
if not isinstance(input_, Input):
|
if not isinstance(input_, Input):
|
||||||
raise TypeError('`input_` must be a Input instance')
|
raise TypeError("`input_` must be a Input instance")
|
||||||
self.inputs.append(input_)
|
self.inputs.append(input_)
|
||||||
|
|
||||||
def add_output(self, output):
|
def add_output(self, output):
|
||||||
"""Adds an output to a Transaction's list of outputs.
|
"""Adds an output to a Transaction's list of outputs.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
output (:class:`~planetmint.transactions.common.transaction.
|
output (:class:`~planetmint.transactions.common.transaction.
|
||||||
Output`): An Output to be added to the
|
Output`): An Output to be added to the
|
||||||
Transaction.
|
Transaction.
|
||||||
"""
|
"""
|
||||||
if not isinstance(output, Output):
|
if not isinstance(output, Output):
|
||||||
raise TypeError('`output` must be an Output instance or None')
|
raise TypeError("`output` must be an Output instance or None")
|
||||||
self.outputs.append(output)
|
self.outputs.append(output)
|
||||||
|
|
||||||
def sign(self, private_keys):
|
def sign(self, private_keys):
|
||||||
"""Fulfills a previous Transaction's Output by signing Inputs.
|
"""Fulfills a previous Transaction's Output by signing Inputs.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
This method works only for the following Cryptoconditions
|
This method works only for the following Cryptoconditions
|
||||||
currently:
|
currently:
|
||||||
- Ed25519Fulfillment
|
- Ed25519Fulfillment
|
||||||
- ThresholdSha256
|
- ThresholdSha256
|
||||||
- ZenroomSha256
|
- ZenroomSha256
|
||||||
Furthermore, note that all keys required to fully sign the
|
Furthermore, note that all keys required to fully sign the
|
||||||
Transaction have to be passed to this method. A subset of all
|
Transaction have to be passed to this method. A subset of all
|
||||||
will cause this method to fail.
|
will cause this method to fail.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
private_keys (:obj:`list` of :obj:`str`): A complete list of
|
private_keys (:obj:`list` of :obj:`str`): A complete list of
|
||||||
all private keys needed to sign all Fulfillments of this
|
all private keys needed to sign all Fulfillments of this
|
||||||
Transaction.
|
Transaction.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:class:`~planetmint.transactions.common.transaction.Transaction`
|
:class:`~planetmint.transactions.common.transaction.Transaction`
|
||||||
"""
|
"""
|
||||||
# TODO: Singing should be possible with at least one of all private
|
# TODO: Singing should be possible with at least one of all private
|
||||||
# keys supplied to this method.
|
# keys supplied to this method.
|
||||||
if private_keys is None or not isinstance(private_keys, list):
|
if private_keys is None or not isinstance(private_keys, list):
|
||||||
raise TypeError('`private_keys` must be a list instance')
|
raise TypeError("`private_keys` must be a list instance")
|
||||||
|
|
||||||
# NOTE: Generate public keys from private keys and match them in a
|
# NOTE: Generate public keys from private keys and match them in a
|
||||||
# dictionary:
|
# dictionary:
|
||||||
@ -269,8 +298,10 @@ class Transaction(object):
|
|||||||
# to decode to convert the bytestring into a python str
|
# to decode to convert the bytestring into a python str
|
||||||
return public_key.decode()
|
return public_key.decode()
|
||||||
|
|
||||||
key_pairs = {gen_public_key(PrivateKey(private_key)):
|
key_pairs = {
|
||||||
PrivateKey(private_key) for private_key in private_keys}
|
gen_public_key(PrivateKey(private_key)): PrivateKey(private_key)
|
||||||
|
for private_key in private_keys
|
||||||
|
}
|
||||||
|
|
||||||
tx_dict = self.to_dict()
|
tx_dict = self.to_dict()
|
||||||
tx_dict = Transaction._remove_signatures(tx_dict)
|
tx_dict = Transaction._remove_signatures(tx_dict)
|
||||||
@ -286,41 +317,39 @@ class Transaction(object):
|
|||||||
def _sign_input(cls, input_, message, key_pairs):
|
def _sign_input(cls, input_, message, key_pairs):
|
||||||
"""Signs a single Input.
|
"""Signs a single Input.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
This method works only for the following Cryptoconditions
|
This method works only for the following Cryptoconditions
|
||||||
currently:
|
currently:
|
||||||
- Ed25519Fulfillment
|
- Ed25519Fulfillment
|
||||||
- ThresholdSha256.
|
- ThresholdSha256.
|
||||||
- ZenroomSha256
|
- ZenroomSha256
|
||||||
Args:
|
Args:
|
||||||
input_ (:class:`~planetmint.transactions.common.transaction.
|
input_ (:class:`~planetmint.transactions.common.transaction.
|
||||||
Input`) The Input to be signed.
|
Input`) The Input to be signed.
|
||||||
message (str): The message to be signed
|
message (str): The message to be signed
|
||||||
key_pairs (dict): The keys to sign the Transaction with.
|
key_pairs (dict): The keys to sign the Transaction with.
|
||||||
"""
|
"""
|
||||||
if isinstance(input_.fulfillment, Ed25519Sha256):
|
if isinstance(input_.fulfillment, Ed25519Sha256):
|
||||||
return cls._sign_simple_signature_fulfillment(input_, message,
|
return cls._sign_simple_signature_fulfillment(input_, message, key_pairs)
|
||||||
key_pairs)
|
|
||||||
elif isinstance(input_.fulfillment, ThresholdSha256):
|
elif isinstance(input_.fulfillment, ThresholdSha256):
|
||||||
return cls._sign_threshold_signature_fulfillment(input_, message,
|
return cls._sign_threshold_signature_fulfillment(input_, message, key_pairs)
|
||||||
key_pairs)
|
|
||||||
elif isinstance(input_.fulfillment, ZenroomSha256):
|
elif isinstance(input_.fulfillment, ZenroomSha256):
|
||||||
return cls._sign_threshold_signature_fulfillment(input_, message,
|
return cls._sign_threshold_signature_fulfillment(input_, message, key_pairs)
|
||||||
key_pairs)
|
|
||||||
else:
|
else:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
'Fulfillment couldn\'t be matched to '
|
"Fulfillment couldn't be matched to "
|
||||||
'Cryptocondition fulfillment type.')
|
"Cryptocondition fulfillment type."
|
||||||
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _sign_zenroom_fulfillment(cls, input_, message, key_pairs):
|
def _sign_zenroom_fulfillment(cls, input_, message, key_pairs):
|
||||||
"""Signs a Zenroomful.
|
"""Signs a Zenroomful.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_ (:class:`~planetmint.transactions.common.transaction.
|
input_ (:class:`~planetmint.transactions.common.transaction.
|
||||||
Input`) The input to be signed.
|
Input`) The input to be signed.
|
||||||
message (str): The message to be signed
|
message (str): The message to be signed
|
||||||
key_pairs (dict): The keys to sign the Transaction with.
|
key_pairs (dict): The keys to sign the Transaction with.
|
||||||
"""
|
"""
|
||||||
# NOTE: To eliminate the dangers of accidentally signing a condition by
|
# NOTE: To eliminate the dangers of accidentally signing a condition by
|
||||||
# reference, we remove the reference of input_ here
|
# reference, we remove the reference of input_ here
|
||||||
@ -330,29 +359,32 @@ class Transaction(object):
|
|||||||
public_key = input_.owners_before[0]
|
public_key = input_.owners_before[0]
|
||||||
message = sha3_256(message.encode())
|
message = sha3_256(message.encode())
|
||||||
if input_.fulfills:
|
if input_.fulfills:
|
||||||
message.update('{}{}'.format(
|
message.update(
|
||||||
input_.fulfills.txid, input_.fulfills.output).encode())
|
"{}{}".format(input_.fulfills.txid, input_.fulfills.output).encode()
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# cryptoconditions makes no assumptions of the encoding of the
|
# cryptoconditions makes no assumptions of the encoding of the
|
||||||
# message to sign or verify. It only accepts bytestrings
|
# message to sign or verify. It only accepts bytestrings
|
||||||
input_.fulfillment.sign(
|
input_.fulfillment.sign(
|
||||||
message.digest(), base58.b58decode(key_pairs[public_key].encode()))
|
message.digest(), base58.b58decode(key_pairs[public_key].encode())
|
||||||
|
)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise KeypairMismatchException('Public key {} is not a pair to '
|
raise KeypairMismatchException(
|
||||||
'any of the private keys'
|
"Public key {} is not a pair to "
|
||||||
.format(public_key))
|
"any of the private keys".format(public_key)
|
||||||
|
)
|
||||||
return input_
|
return input_
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
|
def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
|
||||||
"""Signs a Ed25519Fulfillment.
|
"""Signs a Ed25519Fulfillment.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_ (:class:`~planetmint.transactions.common.transaction.
|
input_ (:class:`~planetmint.transactions.common.transaction.
|
||||||
Input`) The input to be signed.
|
Input`) The input to be signed.
|
||||||
message (str): The message to be signed
|
message (str): The message to be signed
|
||||||
key_pairs (dict): The keys to sign the Transaction with.
|
key_pairs (dict): The keys to sign the Transaction with.
|
||||||
"""
|
"""
|
||||||
# NOTE: To eliminate the dangers of accidentally signing a condition by
|
# NOTE: To eliminate the dangers of accidentally signing a condition by
|
||||||
# reference, we remove the reference of input_ here
|
# reference, we remove the reference of input_ here
|
||||||
@ -362,35 +394,39 @@ class Transaction(object):
|
|||||||
public_key = input_.owners_before[0]
|
public_key = input_.owners_before[0]
|
||||||
message = sha3_256(message.encode())
|
message = sha3_256(message.encode())
|
||||||
if input_.fulfills:
|
if input_.fulfills:
|
||||||
message.update('{}{}'.format(
|
message.update(
|
||||||
input_.fulfills.txid, input_.fulfills.output).encode())
|
"{}{}".format(input_.fulfills.txid, input_.fulfills.output).encode()
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# cryptoconditions makes no assumptions of the encoding of the
|
# cryptoconditions makes no assumptions of the encoding of the
|
||||||
# message to sign or verify. It only accepts bytestrings
|
# message to sign or verify. It only accepts bytestrings
|
||||||
input_.fulfillment.sign(
|
input_.fulfillment.sign(
|
||||||
message.digest(), base58.b58decode(key_pairs[public_key].encode()))
|
message.digest(), base58.b58decode(key_pairs[public_key].encode())
|
||||||
|
)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise KeypairMismatchException('Public key {} is not a pair to '
|
raise KeypairMismatchException(
|
||||||
'any of the private keys'
|
"Public key {} is not a pair to "
|
||||||
.format(public_key))
|
"any of the private keys".format(public_key)
|
||||||
|
)
|
||||||
return input_
|
return input_
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):
|
def _sign_threshold_signature_fulfillment(cls, input_, message, key_pairs):
|
||||||
"""Signs a ThresholdSha256.
|
"""Signs a ThresholdSha256.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_ (:class:`~planetmint.transactions.common.transaction.
|
input_ (:class:`~planetmint.transactions.common.transaction.
|
||||||
Input`) The Input to be signed.
|
Input`) The Input to be signed.
|
||||||
message (str): The message to be signed
|
message (str): The message to be signed
|
||||||
key_pairs (dict): The keys to sign the Transaction with.
|
key_pairs (dict): The keys to sign the Transaction with.
|
||||||
"""
|
"""
|
||||||
input_ = deepcopy(input_)
|
input_ = deepcopy(input_)
|
||||||
message = sha3_256(message.encode())
|
message = sha3_256(message.encode())
|
||||||
if input_.fulfills:
|
if input_.fulfills:
|
||||||
message.update('{}{}'.format(
|
message.update(
|
||||||
input_.fulfills.txid, input_.fulfills.output).encode())
|
"{}{}".format(input_.fulfills.txid, input_.fulfills.output).encode()
|
||||||
|
)
|
||||||
|
|
||||||
for owner_before in set(input_.owners_before):
|
for owner_before in set(input_.owners_before):
|
||||||
# TODO: CC should throw a KeypairMismatchException, instead of
|
# TODO: CC should throw a KeypairMismatchException, instead of
|
||||||
@ -403,24 +439,24 @@ class Transaction(object):
|
|||||||
# TODO FOR CC: `get_subcondition` is singular. One would not
|
# TODO FOR CC: `get_subcondition` is singular. One would not
|
||||||
# expect to get a list back.
|
# expect to get a list back.
|
||||||
ccffill = input_.fulfillment
|
ccffill = input_.fulfillment
|
||||||
subffills = ccffill.get_subcondition_from_vk(
|
subffills = ccffill.get_subcondition_from_vk(base58.b58decode(owner_before))
|
||||||
base58.b58decode(owner_before))
|
|
||||||
if not subffills:
|
if not subffills:
|
||||||
raise KeypairMismatchException('Public key {} cannot be found '
|
raise KeypairMismatchException(
|
||||||
'in the fulfillment'
|
"Public key {} cannot be found "
|
||||||
.format(owner_before))
|
"in the fulfillment".format(owner_before)
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
private_key = key_pairs[owner_before]
|
private_key = key_pairs[owner_before]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise KeypairMismatchException('Public key {} is not a pair '
|
raise KeypairMismatchException(
|
||||||
'to any of the private keys'
|
"Public key {} is not a pair "
|
||||||
.format(owner_before))
|
"to any of the private keys".format(owner_before)
|
||||||
|
)
|
||||||
|
|
||||||
# cryptoconditions makes no assumptions of the encoding of the
|
# cryptoconditions makes no assumptions of the encoding of the
|
||||||
# message to sign or verify. It only accepts bytestrings
|
# message to sign or verify. It only accepts bytestrings
|
||||||
for subffill in subffills:
|
for subffill in subffills:
|
||||||
subffill.sign(
|
subffill.sign(message.digest(), base58.b58decode(private_key.encode()))
|
||||||
message.digest(), base58.b58decode(private_key.encode()))
|
|
||||||
return input_
|
return input_
|
||||||
|
|
||||||
def inputs_valid(self, outputs=None):
|
def inputs_valid(self, outputs=None):
|
||||||
@ -445,85 +481,85 @@ class Transaction(object):
|
|||||||
# to check for outputs, we're just submitting dummy
|
# to check for outputs, we're just submitting dummy
|
||||||
# values to the actual method. This simplifies it's logic
|
# values to the actual method. This simplifies it's logic
|
||||||
# greatly, as we do not have to check against `None` values.
|
# greatly, as we do not have to check against `None` values.
|
||||||
return self._inputs_valid(['dummyvalue'
|
return self._inputs_valid(["dummyvalue" for _ in self.inputs])
|
||||||
for _ in self.inputs])
|
|
||||||
elif self.operation == self.TRANSFER:
|
elif self.operation == self.TRANSFER:
|
||||||
return self._inputs_valid([output.fulfillment.condition_uri
|
return self._inputs_valid(
|
||||||
for output in outputs])
|
[output.fulfillment.condition_uri for output in outputs]
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
allowed_ops = ', '.join(self.__class__.ALLOWED_OPERATIONS)
|
allowed_ops = ", ".join(self.__class__.ALLOWED_OPERATIONS)
|
||||||
raise TypeError('`operation` must be one of {}'
|
raise TypeError("`operation` must be one of {}".format(allowed_ops))
|
||||||
.format(allowed_ops))
|
|
||||||
|
|
||||||
def _inputs_valid(self, output_condition_uris):
|
def _inputs_valid(self, output_condition_uris):
|
||||||
"""Validates an Input against a given set of Outputs.
|
"""Validates an Input against a given set of Outputs.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
The number of `output_condition_uris` must be equal to the
|
The number of `output_condition_uris` must be equal to the
|
||||||
number of Inputs a Transaction has.
|
number of Inputs a Transaction has.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
output_condition_uris (:obj:`list` of :obj:`str`): A list of
|
output_condition_uris (:obj:`list` of :obj:`str`): A list of
|
||||||
Outputs to check the Inputs against.
|
Outputs to check the Inputs against.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: If all Outputs are valid.
|
bool: If all Outputs are valid.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if len(self.inputs) != len(output_condition_uris):
|
if len(self.inputs) != len(output_condition_uris):
|
||||||
raise ValueError('Inputs and '
|
raise ValueError(
|
||||||
'output_condition_uris must have the same count')
|
"Inputs and " "output_condition_uris must have the same count"
|
||||||
|
)
|
||||||
|
|
||||||
tx_dict = self.tx_dict if self.tx_dict else self.to_dict()
|
tx_dict = self.tx_dict if self.tx_dict else self.to_dict()
|
||||||
tx_dict = Transaction._remove_signatures(tx_dict)
|
tx_dict = Transaction._remove_signatures(tx_dict)
|
||||||
tx_dict['id'] = None
|
tx_dict["id"] = None
|
||||||
tx_serialized = Transaction._to_str(tx_dict)
|
tx_serialized = Transaction._to_str(tx_dict)
|
||||||
|
|
||||||
def validate(i, output_condition_uri=None):
|
def validate(i, output_condition_uri=None):
|
||||||
"""Validate input against output condition URI"""
|
"""Validate input against output condition URI"""
|
||||||
return self._input_valid(self.inputs[i], self.operation,
|
return self._input_valid(
|
||||||
tx_serialized, output_condition_uri)
|
self.inputs[i], self.operation, tx_serialized, output_condition_uri
|
||||||
|
)
|
||||||
|
|
||||||
return all(validate(i, cond)
|
return all(validate(i, cond) for i, cond in enumerate(output_condition_uris))
|
||||||
for i, cond in enumerate(output_condition_uris))
|
|
||||||
|
|
||||||
@lru_cache(maxsize=16384)
|
@lru_cache(maxsize=16384)
|
||||||
def _input_valid(self, input_, operation, message, output_condition_uri=None):
|
def _input_valid(self, input_, operation, message, output_condition_uri=None):
|
||||||
"""Validates a single Input against a single Output.
|
"""Validates a single Input against a single Output.
|
||||||
|
|
||||||
Note:
|
Note:
|
||||||
In case of a `CREATE` Transaction, this method
|
In case of a `CREATE` Transaction, this method
|
||||||
does not validate against `output_condition_uri`.
|
does not validate against `output_condition_uri`.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
input_ (:class:`~planetmint.transactions.common.transaction.
|
input_ (:class:`~planetmint.transactions.common.transaction.
|
||||||
Input`) The Input to be signed.
|
Input`) The Input to be signed.
|
||||||
operation (str): The type of Transaction.
|
operation (str): The type of Transaction.
|
||||||
message (str): The fulfillment message.
|
message (str): The fulfillment message.
|
||||||
output_condition_uri (str, optional): An Output to check the
|
output_condition_uri (str, optional): An Output to check the
|
||||||
Input against.
|
Input against.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
bool: If the Input is valid.
|
bool: If the Input is valid.
|
||||||
"""
|
"""
|
||||||
ccffill = input_.fulfillment
|
ccffill = input_.fulfillment
|
||||||
try:
|
try:
|
||||||
parsed_ffill = Fulfillment.from_uri(ccffill.serialize_uri())
|
parsed_ffill = Fulfillment.from_uri(ccffill.serialize_uri())
|
||||||
except TypeError as e:
|
except TypeError as e:
|
||||||
print( f"Exception TypeError : {e}")
|
print(f"Exception TypeError : {e}")
|
||||||
return False;
|
return False
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
print( f"Exception ValueError : {e}")
|
print(f"Exception ValueError : {e}")
|
||||||
return False;
|
return False
|
||||||
except ParsingError as e:
|
except ParsingError as e:
|
||||||
print( f"Exception ParsingError : {e}")
|
print(f"Exception ParsingError : {e}")
|
||||||
return False;
|
return False
|
||||||
except ASN1DecodeError as e:
|
except ASN1DecodeError as e:
|
||||||
print( f"Exception ASN1DecodeError : {e}")
|
print(f"Exception ASN1DecodeError : {e}")
|
||||||
return False;
|
return False
|
||||||
except ASN1EncodeError as e:
|
except ASN1EncodeError as e:
|
||||||
print( f"Exception ASN1EncodeError : {e}")
|
print(f"Exception ASN1EncodeError : {e}")
|
||||||
return False;
|
return False
|
||||||
|
|
||||||
if operation == self.CREATE:
|
if operation == self.CREATE:
|
||||||
# NOTE: In the case of a `CREATE` transaction, the
|
# NOTE: In the case of a `CREATE` transaction, the
|
||||||
@ -533,13 +569,14 @@ class Transaction(object):
|
|||||||
output_valid = output_condition_uri == ccffill.condition_uri
|
output_valid = output_condition_uri == ccffill.condition_uri
|
||||||
|
|
||||||
ffill_valid = False
|
ffill_valid = False
|
||||||
if isinstance( parsed_ffill, ZenroomSha256 ):
|
if isinstance(parsed_ffill, ZenroomSha256):
|
||||||
ffill_valid = parsed_ffill.validate(message=message)
|
ffill_valid = parsed_ffill.validate(message=message)
|
||||||
else:
|
else:
|
||||||
message = sha3_256(message.encode())
|
message = sha3_256(message.encode())
|
||||||
if input_.fulfills:
|
if input_.fulfills:
|
||||||
message.update('{}{}'.format(
|
message.update(
|
||||||
input_.fulfills.txid, input_.fulfills.output).encode())
|
"{}{}".format(input_.fulfills.txid, input_.fulfills.output).encode()
|
||||||
|
)
|
||||||
|
|
||||||
# NOTE: We pass a timestamp to `.validate`, as in case of a timeout
|
# NOTE: We pass a timestamp to `.validate`, as in case of a timeout
|
||||||
# condition we'll have to validate against it
|
# condition we'll have to validate against it
|
||||||
@ -557,17 +594,17 @@ class Transaction(object):
|
|||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
"""Transforms the object to a Python dictionary.
|
"""Transforms the object to a Python dictionary.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict: The Transaction as an alternative serialization format.
|
dict: The Transaction as an alternative serialization format.
|
||||||
"""
|
"""
|
||||||
return {
|
return {
|
||||||
'inputs': [input_.to_dict() for input_ in self.inputs],
|
"inputs": [input_.to_dict() for input_ in self.inputs],
|
||||||
'outputs': [output.to_dict() for output in self.outputs],
|
"outputs": [output.to_dict() for output in self.outputs],
|
||||||
'operation': str(self.operation),
|
"operation": str(self.operation),
|
||||||
'metadata': self.metadata,
|
"metadata": self.metadata,
|
||||||
'asset': self.asset,
|
"asset": self.asset,
|
||||||
'version': self.version,
|
"version": self.version,
|
||||||
'id': self._id,
|
"id": self._id,
|
||||||
}
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -575,22 +612,22 @@ class Transaction(object):
|
|||||||
def _remove_signatures(tx_dict):
|
def _remove_signatures(tx_dict):
|
||||||
"""Takes a Transaction dictionary and removes all signatures.
|
"""Takes a Transaction dictionary and removes all signatures.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tx_dict (dict): The Transaction to remove all signatures from.
|
tx_dict (dict): The Transaction to remove all signatures from.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict
|
dict
|
||||||
|
|
||||||
"""
|
"""
|
||||||
# NOTE: We remove the reference since we need `tx_dict` only for the
|
# NOTE: We remove the reference since we need `tx_dict` only for the
|
||||||
# transaction's hash
|
# transaction's hash
|
||||||
tx_dict = deepcopy(tx_dict)
|
tx_dict = deepcopy(tx_dict)
|
||||||
for input_ in tx_dict['inputs']:
|
for input_ in tx_dict["inputs"]:
|
||||||
# NOTE: Not all Cryptoconditions return a `signature` key (e.g.
|
# NOTE: Not all Cryptoconditions return a `signature` key (e.g.
|
||||||
# ThresholdSha256), so setting it to `None` in any
|
# ThresholdSha256), so setting it to `None` in any
|
||||||
# case could yield incorrect signatures. This is why we only
|
# case could yield incorrect signatures. This is why we only
|
||||||
# set it to `None` if it's set in the dict.
|
# set it to `None` if it's set in the dict.
|
||||||
input_['fulfillment'] = None
|
input_["fulfillment"] = None
|
||||||
return tx_dict
|
return tx_dict
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@ -602,7 +639,7 @@ class Transaction(object):
|
|||||||
return self._id
|
return self._id
|
||||||
|
|
||||||
def to_hash(self):
|
def to_hash(self):
|
||||||
return self.to_dict()['id']
|
return self.to_dict()["id"]
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _to_str(value):
|
def _to_str(value):
|
||||||
@ -638,40 +675,47 @@ class Transaction(object):
|
|||||||
transactions = [transactions]
|
transactions = [transactions]
|
||||||
|
|
||||||
# create a set of the transactions' asset ids
|
# create a set of the transactions' asset ids
|
||||||
asset_ids = {tx.id if tx.operation == tx.CREATE
|
asset_ids = {
|
||||||
else tx.asset['id']
|
tx.id if tx.operation == tx.CREATE else tx.asset["id"]
|
||||||
for tx in transactions}
|
for tx in transactions
|
||||||
|
}
|
||||||
|
|
||||||
# check that all the transasctions have the same asset id
|
# check that all the transasctions have the same asset id
|
||||||
if len(asset_ids) > 1:
|
if len(asset_ids) > 1:
|
||||||
raise AssetIdMismatch(('All inputs of all transactions passed'
|
raise AssetIdMismatch(
|
||||||
' need to have the same asset id'))
|
(
|
||||||
|
"All inputs of all transactions passed"
|
||||||
|
" need to have the same asset id"
|
||||||
|
)
|
||||||
|
)
|
||||||
return asset_ids.pop()
|
return asset_ids.pop()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def validate_id(tx_body):
|
def validate_id(tx_body):
|
||||||
"""Validate the transaction ID of a transaction
|
"""Validate the transaction ID of a transaction
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tx_body (dict): The Transaction to be transformed.
|
tx_body (dict): The Transaction to be transformed.
|
||||||
"""
|
"""
|
||||||
# NOTE: Remove reference to avoid side effects
|
# NOTE: Remove reference to avoid side effects
|
||||||
# tx_body = deepcopy(tx_body)
|
# tx_body = deepcopy(tx_body)
|
||||||
tx_body = rapidjson.loads(rapidjson.dumps(tx_body))
|
tx_body = rapidjson.loads(rapidjson.dumps(tx_body))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
proposed_tx_id = tx_body['id']
|
proposed_tx_id = tx_body["id"]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise InvalidHash('No transaction id found!')
|
raise InvalidHash("No transaction id found!")
|
||||||
|
|
||||||
tx_body['id'] = None
|
tx_body["id"] = None
|
||||||
|
|
||||||
tx_body_serialized = Transaction._to_str(tx_body)
|
tx_body_serialized = Transaction._to_str(tx_body)
|
||||||
valid_tx_id = Transaction._to_hash(tx_body_serialized)
|
valid_tx_id = Transaction._to_hash(tx_body_serialized)
|
||||||
|
|
||||||
if proposed_tx_id != valid_tx_id:
|
if proposed_tx_id != valid_tx_id:
|
||||||
err_msg = ("The transaction's id '{}' isn't equal to "
|
err_msg = (
|
||||||
"the hash of its body, i.e. it's not valid.")
|
"The transaction's id '{}' isn't equal to "
|
||||||
|
"the hash of its body, i.e. it's not valid."
|
||||||
|
)
|
||||||
raise InvalidHash(err_msg.format(proposed_tx_id))
|
raise InvalidHash(err_msg.format(proposed_tx_id))
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@ -679,23 +723,35 @@ class Transaction(object):
|
|||||||
def from_dict(cls, tx, skip_schema_validation=True):
|
def from_dict(cls, tx, skip_schema_validation=True):
|
||||||
"""Transforms a Python dictionary to a Transaction object.
|
"""Transforms a Python dictionary to a Transaction object.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
tx_body (dict): The Transaction to be transformed.
|
tx_body (dict): The Transaction to be transformed.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:class:`~planetmint.transactions.common.transaction.Transaction`
|
:class:`~planetmint.transactions.common.transaction.Transaction`
|
||||||
"""
|
"""
|
||||||
operation = tx.get('operation', Transaction.CREATE) if isinstance(tx, dict) else Transaction.CREATE
|
operation = (
|
||||||
|
tx.get("operation", Transaction.CREATE)
|
||||||
|
if isinstance(tx, dict)
|
||||||
|
else Transaction.CREATE
|
||||||
|
)
|
||||||
cls = Transaction.resolve_class(operation)
|
cls = Transaction.resolve_class(operation)
|
||||||
|
|
||||||
if not skip_schema_validation:
|
if not skip_schema_validation:
|
||||||
cls.validate_id(tx)
|
cls.validate_id(tx)
|
||||||
cls.validate_schema(tx)
|
cls.validate_schema(tx)
|
||||||
|
|
||||||
inputs = [Input.from_dict(input_) for input_ in tx['inputs']]
|
inputs = [Input.from_dict(input_) for input_ in tx["inputs"]]
|
||||||
outputs = [Output.from_dict(output) for output in tx['outputs']]
|
outputs = [Output.from_dict(output) for output in tx["outputs"]]
|
||||||
return cls(tx['operation'], tx['asset'], inputs, outputs,
|
return cls(
|
||||||
tx['metadata'], tx['version'], hash_id=tx['id'], tx_dict=tx)
|
tx["operation"],
|
||||||
|
tx["asset"],
|
||||||
|
inputs,
|
||||||
|
outputs,
|
||||||
|
tx["metadata"],
|
||||||
|
tx["version"],
|
||||||
|
hash_id=tx["id"],
|
||||||
|
tx_dict=tx,
|
||||||
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_db(cls, planet, tx_dict_list):
|
def from_db(cls, planet, tx_dict_list):
|
||||||
@ -721,22 +777,22 @@ class Transaction(object):
|
|||||||
tx_map = {}
|
tx_map = {}
|
||||||
tx_ids = []
|
tx_ids = []
|
||||||
for tx in tx_dict_list:
|
for tx in tx_dict_list:
|
||||||
tx.update({'metadata': None})
|
tx.update({"metadata": None})
|
||||||
tx_map[tx['id']] = tx
|
tx_map[tx["id"]] = tx
|
||||||
tx_ids.append(tx['id'])
|
tx_ids.append(tx["id"])
|
||||||
|
|
||||||
assets = list(planet.get_assets(tx_ids))
|
assets = list(planet.get_assets(tx_ids))
|
||||||
for asset in assets:
|
for asset in assets:
|
||||||
if asset is not None:
|
if asset is not None:
|
||||||
tx = tx_map[asset['id']]
|
tx = tx_map[asset["id"]]
|
||||||
del asset['id']
|
del asset["id"]
|
||||||
tx['asset'] = asset
|
tx["asset"] = asset
|
||||||
|
|
||||||
tx_ids = list(tx_map.keys())
|
tx_ids = list(tx_map.keys())
|
||||||
metadata_list = list(planet.get_metadata(tx_ids))
|
metadata_list = list(planet.get_metadata(tx_ids))
|
||||||
for metadata in metadata_list:
|
for metadata in metadata_list:
|
||||||
tx = tx_map[metadata['id']]
|
tx = tx_map[metadata["id"]]
|
||||||
tx.update({'metadata': metadata.get('metadata')})
|
tx.update({"metadata": metadata.get("metadata")})
|
||||||
|
|
||||||
if return_list:
|
if return_list:
|
||||||
tx_list = []
|
tx_list = []
|
||||||
@ -777,14 +833,13 @@ class Transaction(object):
|
|||||||
input_tx = ctxn
|
input_tx = ctxn
|
||||||
|
|
||||||
if input_tx is None:
|
if input_tx is None:
|
||||||
raise InputDoesNotExist("input `{}` doesn't exist"
|
raise InputDoesNotExist("input `{}` doesn't exist".format(input_txid))
|
||||||
.format(input_txid))
|
|
||||||
|
|
||||||
spent = planet.get_spent(input_txid, input_.fulfills.output,
|
spent = planet.get_spent(
|
||||||
current_transactions)
|
input_txid, input_.fulfills.output, current_transactions
|
||||||
|
)
|
||||||
if spent:
|
if spent:
|
||||||
raise DoubleSpend('input `{}` was already spent'
|
raise DoubleSpend("input `{}` was already spent".format(input_txid))
|
||||||
.format(input_txid))
|
|
||||||
|
|
||||||
output = input_tx.outputs[input_.fulfills.output]
|
output = input_tx.outputs[input_.fulfills.output]
|
||||||
input_conditions.append(output)
|
input_conditions.append(output)
|
||||||
@ -797,21 +852,32 @@ class Transaction(object):
|
|||||||
|
|
||||||
# validate asset id
|
# validate asset id
|
||||||
asset_id = self.get_asset_id(input_txs)
|
asset_id = self.get_asset_id(input_txs)
|
||||||
if asset_id != self.asset['id']:
|
if asset_id != self.asset["id"]:
|
||||||
raise AssetIdMismatch(('The asset id of the input does not'
|
raise AssetIdMismatch(
|
||||||
' match the asset id of the'
|
(
|
||||||
' transaction'))
|
"The asset id of the input does not"
|
||||||
|
" match the asset id of the"
|
||||||
|
" transaction"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
input_amount = sum([input_condition.amount for input_condition in input_conditions])
|
input_amount = sum(
|
||||||
output_amount = sum([output_condition.amount for output_condition in self.outputs])
|
[input_condition.amount for input_condition in input_conditions]
|
||||||
|
)
|
||||||
|
output_amount = sum(
|
||||||
|
[output_condition.amount for output_condition in self.outputs]
|
||||||
|
)
|
||||||
|
|
||||||
if output_amount != input_amount:
|
if output_amount != input_amount:
|
||||||
raise AmountError(('The amount used in the inputs `{}`'
|
raise AmountError(
|
||||||
' needs to be same as the amount used'
|
(
|
||||||
' in the outputs `{}`')
|
"The amount used in the inputs `{}`"
|
||||||
.format(input_amount, output_amount))
|
" needs to be same as the amount used"
|
||||||
|
" in the outputs `{}`"
|
||||||
|
).format(input_amount, output_amount)
|
||||||
|
)
|
||||||
|
|
||||||
if not self.inputs_valid(input_conditions):
|
if not self.inputs_valid(input_conditions):
|
||||||
raise InvalidSignature('Transaction signature is invalid.')
|
raise InvalidSignature("Transaction signature is invalid.")
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|||||||
@ -10,17 +10,17 @@ import rapidjson
|
|||||||
|
|
||||||
import planetmint
|
import planetmint
|
||||||
from planetmint.transactions.common.exceptions import ValidationError
|
from planetmint.transactions.common.exceptions import ValidationError
|
||||||
from cryptoconditions import ThresholdSha256, Ed25519Sha256
|
from cryptoconditions import ThresholdSha256, Ed25519Sha256, ZenroomSha256
|
||||||
from planetmint.transactions.common.exceptions import ThresholdTooDeep
|
from planetmint.transactions.common.exceptions import ThresholdTooDeep
|
||||||
from cryptoconditions.exceptions import UnsupportedTypeError
|
from cryptoconditions.exceptions import UnsupportedTypeError
|
||||||
|
|
||||||
|
|
||||||
def gen_timestamp():
|
def gen_timestamp():
|
||||||
"""The Unix time, rounded to the nearest second.
|
"""The Unix time, rounded to the nearest second.
|
||||||
See https://en.wikipedia.org/wiki/Unix_time
|
See https://en.wikipedia.org/wiki/Unix_time
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: the Unix time
|
str: the Unix time
|
||||||
"""
|
"""
|
||||||
return str(round(time.time()))
|
return str(round(time.time()))
|
||||||
|
|
||||||
@ -28,34 +28,33 @@ def gen_timestamp():
|
|||||||
def serialize(data):
|
def serialize(data):
|
||||||
"""Serialize a dict into a JSON formatted string.
|
"""Serialize a dict into a JSON formatted string.
|
||||||
|
|
||||||
This function enforces rules like the separator and order of keys.
|
This function enforces rules like the separator and order of keys.
|
||||||
This ensures that all dicts are serialized in the same way.
|
This ensures that all dicts are serialized in the same way.
|
||||||
|
|
||||||
This is specially important for hashing data. We need to make sure that
|
This is specially important for hashing data. We need to make sure that
|
||||||
everyone serializes their data in the same way so that we do not have
|
everyone serializes their data in the same way so that we do not have
|
||||||
hash mismatches for the same structure due to serialization
|
hash mismatches for the same structure due to serialization
|
||||||
differences.
|
differences.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data (dict): dict to serialize
|
data (dict): dict to serialize
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
str: JSON formatted string
|
str: JSON formatted string
|
||||||
|
|
||||||
"""
|
"""
|
||||||
return rapidjson.dumps(data, skipkeys=False, ensure_ascii=False,
|
return rapidjson.dumps(data, skipkeys=False, ensure_ascii=False, sort_keys=True)
|
||||||
sort_keys=True)
|
|
||||||
|
|
||||||
|
|
||||||
def deserialize(data):
|
def deserialize(data):
|
||||||
"""Deserialize a JSON formatted string into a dict.
|
"""Deserialize a JSON formatted string into a dict.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
data (str): JSON formatted string.
|
data (str): JSON formatted string.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
dict: dict resulting from the serialization of a JSON formatted
|
dict: dict resulting from the serialization of a JSON formatted
|
||||||
string.
|
string.
|
||||||
"""
|
"""
|
||||||
return rapidjson.loads(data)
|
return rapidjson.loads(data)
|
||||||
|
|
||||||
@ -63,22 +62,22 @@ def deserialize(data):
|
|||||||
def validate_txn_obj(obj_name, obj, key, validation_fun):
|
def validate_txn_obj(obj_name, obj, key, validation_fun):
|
||||||
"""Validate value of `key` in `obj` using `validation_fun`.
|
"""Validate value of `key` in `obj` using `validation_fun`.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
obj_name (str): name for `obj` being validated.
|
obj_name (str): name for `obj` being validated.
|
||||||
obj (dict): dictionary object.
|
obj (dict): dictionary object.
|
||||||
key (str): key to be validated in `obj`.
|
key (str): key to be validated in `obj`.
|
||||||
validation_fun (function): function used to validate the value
|
validation_fun (function): function used to validate the value
|
||||||
of `key`.
|
of `key`.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
None: indicates validation successful
|
None: indicates validation successful
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: `validation_fun` will raise exception on failure
|
ValidationError: `validation_fun` will raise exception on failure
|
||||||
"""
|
"""
|
||||||
backend = planetmint.config['database']['backend']
|
backend = planetmint.config["database"]["backend"]
|
||||||
|
|
||||||
if backend == 'localmongodb':
|
if backend == "localmongodb":
|
||||||
data = obj.get(key, {})
|
data = obj.get(key, {})
|
||||||
if isinstance(data, dict):
|
if isinstance(data, dict):
|
||||||
validate_all_keys_in_obj(obj_name, data, validation_fun)
|
validate_all_keys_in_obj(obj_name, data, validation_fun)
|
||||||
@ -97,17 +96,17 @@ def validate_all_items_in_list(obj_name, data, validation_fun):
|
|||||||
def validate_all_keys_in_obj(obj_name, obj, validation_fun):
|
def validate_all_keys_in_obj(obj_name, obj, validation_fun):
|
||||||
"""Validate all (nested) keys in `obj` by using `validation_fun`.
|
"""Validate all (nested) keys in `obj` by using `validation_fun`.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
obj_name (str): name for `obj` being validated.
|
obj_name (str): name for `obj` being validated.
|
||||||
obj (dict): dictionary object.
|
obj (dict): dictionary object.
|
||||||
validation_fun (function): function used to validate the value
|
validation_fun (function): function used to validate the value
|
||||||
of `key`.
|
of `key`.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
None: indicates validation successful
|
None: indicates validation successful
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: `validation_fun` will raise this error on failure
|
ValidationError: `validation_fun` will raise this error on failure
|
||||||
"""
|
"""
|
||||||
for key, value in obj.items():
|
for key, value in obj.items():
|
||||||
validation_fun(obj_name, key)
|
validation_fun(obj_name, key)
|
||||||
@ -119,16 +118,16 @@ def validate_all_keys_in_obj(obj_name, obj, validation_fun):
|
|||||||
|
|
||||||
def validate_all_values_for_key_in_obj(obj, key, validation_fun):
|
def validate_all_values_for_key_in_obj(obj, key, validation_fun):
|
||||||
"""Validate value for all (nested) occurrence of `key` in `obj`
|
"""Validate value for all (nested) occurrence of `key` in `obj`
|
||||||
using `validation_fun`.
|
using `validation_fun`.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
obj (dict): dictionary object.
|
obj (dict): dictionary object.
|
||||||
key (str): key whose value is to be validated.
|
key (str): key whose value is to be validated.
|
||||||
validation_fun (function): function used to validate the value
|
validation_fun (function): function used to validate the value
|
||||||
of `key`.
|
of `key`.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: `validation_fun` will raise this error on failure
|
ValidationError: `validation_fun` will raise this error on failure
|
||||||
"""
|
"""
|
||||||
for vkey, value in obj.items():
|
for vkey, value in obj.items():
|
||||||
if vkey == key:
|
if vkey == key:
|
||||||
@ -150,22 +149,24 @@ def validate_all_values_for_key_in_list(input_list, key, validation_fun):
|
|||||||
def validate_key(obj_name, key):
|
def validate_key(obj_name, key):
|
||||||
"""Check if `key` contains ".", "$" or null characters.
|
"""Check if `key` contains ".", "$" or null characters.
|
||||||
|
|
||||||
https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
|
https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
obj_name (str): object name to use when raising exception
|
obj_name (str): object name to use when raising exception
|
||||||
key (str): key to validated
|
key (str): key to validated
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
None: validation successful
|
None: validation successful
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: will raise exception in case of regex match.
|
ValidationError: will raise exception in case of regex match.
|
||||||
"""
|
"""
|
||||||
if re.search(r'^[$]|\.|\x00', key):
|
if re.search(r"^[$]|\.|\x00", key):
|
||||||
error_str = ('Invalid key name "{}" in {} object. The '
|
error_str = (
|
||||||
'key name cannot contain characters '
|
'Invalid key name "{}" in {} object. The '
|
||||||
'".", "$" or null characters').format(key, obj_name)
|
"key name cannot contain characters "
|
||||||
|
'".", "$" or null characters'
|
||||||
|
).format(key, obj_name)
|
||||||
raise ValidationError(error_str)
|
raise ValidationError(error_str)
|
||||||
|
|
||||||
|
|
||||||
@ -176,27 +177,26 @@ def _fulfillment_to_details(fulfillment):
|
|||||||
fulfillment: Crypto-conditions Fulfillment object
|
fulfillment: Crypto-conditions Fulfillment object
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if fulfillment.type_name == 'ed25519-sha-256':
|
if fulfillment.type_name == "ed25519-sha-256":
|
||||||
return {
|
return {
|
||||||
'type': 'ed25519-sha-256',
|
"type": "ed25519-sha-256",
|
||||||
'public_key': base58.b58encode(fulfillment.public_key).decode(),
|
"public_key": base58.b58encode(fulfillment.public_key).decode(),
|
||||||
}
|
}
|
||||||
|
|
||||||
if fulfillment.type_name == 'threshold-sha-256':
|
if fulfillment.type_name == "threshold-sha-256":
|
||||||
subconditions = [
|
subconditions = [
|
||||||
_fulfillment_to_details(cond['body'])
|
_fulfillment_to_details(cond["body"]) for cond in fulfillment.subconditions
|
||||||
for cond in fulfillment.subconditions
|
|
||||||
]
|
]
|
||||||
return {
|
return {
|
||||||
'type': 'threshold-sha-256',
|
"type": "threshold-sha-256",
|
||||||
'threshold': fulfillment.threshold,
|
"threshold": fulfillment.threshold,
|
||||||
'subconditions': subconditions,
|
"subconditions": subconditions,
|
||||||
}
|
}
|
||||||
if fulfillment.type_name == 'zenroom-sha-256':
|
if fulfillment.type_name == "zenroom-sha-256":
|
||||||
return {
|
return {
|
||||||
'type': 'zenroom-sha-256',
|
"type": "zenroom-sha-256",
|
||||||
'public_key': base58.b58encode(fulfillment.public_key).decode(),
|
"public_key": base58.b58encode(fulfillment.public_key).decode(),
|
||||||
'script': base58.b58encode(fulfillment.script).decode(),
|
"script": base58.b58encode(fulfillment.script).decode(),
|
||||||
}
|
}
|
||||||
|
|
||||||
raise UnsupportedTypeError(fulfillment.type_name)
|
raise UnsupportedTypeError(fulfillment.type_name)
|
||||||
@ -211,20 +211,22 @@ def _fulfillment_from_details(data, _depth=0):
|
|||||||
if _depth == 100:
|
if _depth == 100:
|
||||||
raise ThresholdTooDeep()
|
raise ThresholdTooDeep()
|
||||||
|
|
||||||
if data['type'] == 'ed25519-sha-256':
|
if data["type"] == "ed25519-sha-256":
|
||||||
public_key = base58.b58decode(data['public_key'])
|
public_key = base58.b58decode(data["public_key"])
|
||||||
return Ed25519Sha256(public_key=public_key)
|
return Ed25519Sha256(public_key=public_key)
|
||||||
|
|
||||||
if data['type'] == 'threshold-sha-256':
|
if data["type"] == "threshold-sha-256":
|
||||||
threshold = ThresholdSha256(data['threshold'])
|
threshold = ThresholdSha256(data["threshold"])
|
||||||
for cond in data['subconditions']:
|
for cond in data["subconditions"]:
|
||||||
cond = _fulfillment_from_details(cond, _depth + 1)
|
cond = _fulfillment_from_details(cond, _depth + 1)
|
||||||
threshold.add_subfulfillment(cond)
|
threshold.add_subfulfillment(cond)
|
||||||
return threshold
|
return threshold
|
||||||
|
|
||||||
if data['type'] == 'zenroom-sha-256':
|
if data["type"] == "zenroom-sha-256":
|
||||||
public_key = base58.b58decode(data['public_key'])
|
public_key = base58.b58decode(data["public_key"])
|
||||||
script = base58.b58decode(data['script'])
|
script = base58.b58decode(data["script"])
|
||||||
zenroom = ZenroomSha256( script= script, data=None , keys= {public_key})
|
# zenroom = ZenroomSha256(script=script, data=None, keys={public_key})
|
||||||
|
# TODO: assign to zenroom and evaluate the outcome
|
||||||
raise UnsupportedTypeError(data.get('type'))
|
ZenroomSha256(script=script, data=None, keys={public_key})
|
||||||
|
|
||||||
|
raise UnsupportedTypeError(data.get("type"))
|
||||||
|
|||||||
@ -2,7 +2,6 @@ import pytest
|
|||||||
import json
|
import json
|
||||||
import base58
|
import base58
|
||||||
from hashlib import sha3_256
|
from hashlib import sha3_256
|
||||||
import cryptoconditions as cc
|
|
||||||
from cryptoconditions.types.ed25519 import Ed25519Sha256
|
from cryptoconditions.types.ed25519 import Ed25519Sha256
|
||||||
from cryptoconditions.types.zenroom import ZenroomSha256
|
from cryptoconditions.types.zenroom import ZenroomSha256
|
||||||
from planetmint.transactions.common.crypto import generate_key_pair
|
from planetmint.transactions.common.crypto import generate_key_pair
|
||||||
@ -13,17 +12,15 @@ CONDITION_SCRIPT = """
|
|||||||
Given that I have a 'string dictionary' named 'houses' inside 'asset'
|
Given that I have a 'string dictionary' named 'houses' inside 'asset'
|
||||||
When I create the signature of 'houses'
|
When I create the signature of 'houses'
|
||||||
Then print the 'signature'"""
|
Then print the 'signature'"""
|
||||||
|
|
||||||
FULFILL_SCRIPT = \
|
FULFILL_SCRIPT = """Scenario 'ecdh': Bob verifies the signature from Alice
|
||||||
"""Scenario 'ecdh': Bob verifies the signature from Alice
|
|
||||||
Given I have a 'ecdh public key' from 'Alice'
|
Given I have a 'ecdh public key' from 'Alice'
|
||||||
Given that I have a 'string dictionary' named 'houses' inside 'asset'
|
Given that I have a 'string dictionary' named 'houses' inside 'asset'
|
||||||
Given I have a 'signature' named 'signature' inside 'result'
|
Given I have a 'signature' named 'signature' inside 'result'
|
||||||
When I verify the 'houses' has a signature in 'signature' by 'Alice'
|
When I verify the 'houses' has a signature in 'signature' by 'Alice'
|
||||||
Then print the string 'ok'"""
|
Then print the string 'ok'"""
|
||||||
|
|
||||||
SK_TO_PK = \
|
SK_TO_PK = """Scenario 'ecdh': Create the keypair
|
||||||
"""Scenario 'ecdh': Create the keypair
|
|
||||||
Given that I am known as '{}'
|
Given that I am known as '{}'
|
||||||
Given I have the 'keyring'
|
Given I have the 'keyring'
|
||||||
When I create the ecdh public key
|
When I create the ecdh public key
|
||||||
@ -31,16 +28,13 @@ SK_TO_PK = \
|
|||||||
Then print my 'ecdh public key'
|
Then print my 'ecdh public key'
|
||||||
Then print my 'bitcoin address'"""
|
Then print my 'bitcoin address'"""
|
||||||
|
|
||||||
GENERATE_KEYPAIR = \
|
GENERATE_KEYPAIR = """Scenario 'ecdh': Create the keypair
|
||||||
"""Scenario 'ecdh': Create the keypair
|
|
||||||
Given that I am known as 'Pippo'
|
Given that I am known as 'Pippo'
|
||||||
When I create the ecdh key
|
When I create the ecdh key
|
||||||
When I create the bitcoin key
|
When I create the bitcoin key
|
||||||
Then print data"""
|
Then print data"""
|
||||||
|
|
||||||
ZENROOM_DATA = {
|
ZENROOM_DATA = {"also": "more data"}
|
||||||
'also': 'more data'
|
|
||||||
}
|
|
||||||
|
|
||||||
HOUSE_ASSETS = {
|
HOUSE_ASSETS = {
|
||||||
"data": {
|
"data": {
|
||||||
@ -52,292 +46,310 @@ HOUSE_ASSETS = {
|
|||||||
{
|
{
|
||||||
"name": "Draco",
|
"name": "Draco",
|
||||||
"team": "Slytherin",
|
"team": "Slytherin",
|
||||||
}
|
},
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
metadata = {
|
metadata = {"units": 300, "type": "KG"}
|
||||||
'units': 300,
|
|
||||||
'type': 'KG'
|
|
||||||
}
|
|
||||||
|
|
||||||
def test_manual_tx_crafting_ext():
|
def test_manual_tx_crafting_ext():
|
||||||
|
|
||||||
producer, buyer, reseller = generate_key_pair(), generate_key_pair(), generate_key_pair()
|
producer = generate_key_pair()
|
||||||
|
|
||||||
producer_ed25519 = Ed25519Sha256(public_key=base58.b58decode(producer.public_key))
|
producer_ed25519 = Ed25519Sha256(public_key=base58.b58decode(producer.public_key))
|
||||||
condition_uri = producer_ed25519.condition.serialize_uri()
|
condition_uri = producer_ed25519.condition.serialize_uri()
|
||||||
output = {
|
output = {
|
||||||
'amount': '3000',
|
"amount": "3000",
|
||||||
'condition': {
|
"condition": {
|
||||||
'details': {
|
"details": {"type": "ed25519-sha-256", "public_key": producer.public_key},
|
||||||
"type": "ed25519-sha-256",
|
"uri": condition_uri,
|
||||||
"public_key": producer.public_key
|
|
||||||
},
|
|
||||||
'uri': condition_uri,
|
|
||||||
|
|
||||||
},
|
},
|
||||||
'public_keys': [producer.public_key,],
|
"public_keys": [
|
||||||
|
producer.public_key,
|
||||||
|
],
|
||||||
}
|
}
|
||||||
input_ = {
|
input_ = {
|
||||||
'fulfillment': None,
|
"fulfillment": None,
|
||||||
'fulfills': None,
|
"fulfills": None,
|
||||||
'owners_before': [producer.public_key,]
|
"owners_before": [
|
||||||
|
producer.public_key,
|
||||||
|
],
|
||||||
}
|
}
|
||||||
version = '2.0'
|
version = "2.0"
|
||||||
|
|
||||||
prepared_token_tx = {
|
prepared_token_tx = {
|
||||||
'operation': 'CREATE',
|
"operation": "CREATE",
|
||||||
'asset': HOUSE_ASSETS,#rfid_token,
|
"asset": HOUSE_ASSETS, # rfid_token,
|
||||||
'metadata': metadata,
|
"metadata": metadata,
|
||||||
'outputs': [output,],
|
"outputs": [
|
||||||
'inputs': [input_,],
|
output,
|
||||||
'version': version,
|
],
|
||||||
'id': None,
|
"inputs": [
|
||||||
|
input_,
|
||||||
|
],
|
||||||
|
"version": version,
|
||||||
|
"id": None,
|
||||||
}
|
}
|
||||||
|
|
||||||
print( f"prepared: {prepared_token_tx}")
|
print(f"prepared: {prepared_token_tx}")
|
||||||
|
|
||||||
# Create sha3-256 of message to sign
|
|
||||||
message = json.dumps(
|
|
||||||
prepared_token_tx,
|
|
||||||
sort_keys=True,
|
|
||||||
separators=(',', ':'),
|
|
||||||
ensure_ascii=False,
|
|
||||||
)
|
|
||||||
message_hash = sha3_256(message.encode())
|
|
||||||
|
|
||||||
producer_ed25519.sign(message_hash.digest(), base58.b58decode(producer.private_key))
|
|
||||||
|
|
||||||
fulfillment_uri = producer_ed25519.serialize_uri()
|
|
||||||
|
|
||||||
prepared_token_tx['inputs'][0]['fulfillment'] = fulfillment_uri
|
|
||||||
|
|
||||||
json_str_tx = json.dumps(
|
|
||||||
prepared_token_tx,
|
|
||||||
sort_keys=True,
|
|
||||||
separators=(',', ':'),
|
|
||||||
ensure_ascii=False,
|
|
||||||
)
|
|
||||||
creation_txid = sha3_256(json_str_tx.encode()).hexdigest()
|
|
||||||
|
|
||||||
prepared_token_tx['id'] = creation_txid
|
|
||||||
|
|
||||||
print( f"signed: {prepared_token_tx}")
|
|
||||||
|
|
||||||
from planetmint.transactions.types.assets.create import Create
|
|
||||||
from planetmint.transactions.types.assets.transfer import Transfer
|
|
||||||
from planetmint.models import Transaction
|
|
||||||
from planetmint.transactions.common.exceptions import SchemaValidationError, ValidationError
|
|
||||||
from flask import current_app
|
|
||||||
from planetmint.transactions.common.transaction_mode_types import BROADCAST_TX_ASYNC
|
|
||||||
validated = None
|
|
||||||
try:
|
|
||||||
tx_obj = Transaction.from_dict(prepared_token_tx)
|
|
||||||
except SchemaValidationError as e:
|
|
||||||
assert()
|
|
||||||
except ValidationError as e:
|
|
||||||
print(e)
|
|
||||||
assert()
|
|
||||||
|
|
||||||
from planetmint.lib import Planetmint
|
|
||||||
planet = Planetmint()
|
|
||||||
validated = planet.validate_transaction(tx_obj)
|
|
||||||
print( f"\n\nVALIDATED =====: {validated}")
|
|
||||||
assert not validated == False
|
|
||||||
|
|
||||||
def test_manual_tx_crafting_ext_zenroom():
|
|
||||||
producer= generate_key_pair()
|
|
||||||
producer_ed25519 = Ed25519Sha256(public_key=base58.b58decode(producer.public_key))
|
|
||||||
condition_uri = producer_ed25519.condition.serialize_uri()
|
|
||||||
output = {
|
|
||||||
'amount': '3000',
|
|
||||||
'condition': {
|
|
||||||
'details': {
|
|
||||||
"type": "ed25519-sha-256",
|
|
||||||
"public_key": producer.public_key
|
|
||||||
},
|
|
||||||
'uri': condition_uri,
|
|
||||||
|
|
||||||
},
|
|
||||||
'public_keys': [producer.public_key,],
|
|
||||||
}
|
|
||||||
input_ = {
|
|
||||||
'fulfillment': None,
|
|
||||||
'fulfills': None,
|
|
||||||
'owners_before': [producer.public_key,]
|
|
||||||
}
|
|
||||||
version = '2.0'
|
|
||||||
prepared_token_tx = {
|
|
||||||
'operation': 'CREATE',
|
|
||||||
'asset': HOUSE_ASSETS,#rfid_token,
|
|
||||||
'metadata': metadata,
|
|
||||||
'outputs': [output,],
|
|
||||||
'inputs': [input_,],
|
|
||||||
'version': version,
|
|
||||||
'id': None,
|
|
||||||
}
|
|
||||||
|
|
||||||
print( f"prepared: {prepared_token_tx}")
|
|
||||||
|
|
||||||
# Create sha3-256 of message to sign
|
# Create sha3-256 of message to sign
|
||||||
message = json.dumps(
|
message = json.dumps(
|
||||||
prepared_token_tx,
|
prepared_token_tx,
|
||||||
sort_keys=True,
|
sort_keys=True,
|
||||||
separators=(',', ':'),
|
separators=(",", ":"),
|
||||||
ensure_ascii=False,
|
ensure_ascii=False,
|
||||||
)
|
)
|
||||||
message_hash = sha3_256(message.encode())
|
message_hash = sha3_256(message.encode())
|
||||||
|
|
||||||
producer_ed25519.sign(message_hash.digest(), base58.b58decode(producer.private_key))
|
producer_ed25519.sign(message_hash.digest(), base58.b58decode(producer.private_key))
|
||||||
|
|
||||||
fulfillment_uri = producer_ed25519.serialize_uri()
|
fulfillment_uri = producer_ed25519.serialize_uri()
|
||||||
|
|
||||||
prepared_token_tx['inputs'][0]['fulfillment'] = fulfillment_uri
|
prepared_token_tx["inputs"][0]["fulfillment"] = fulfillment_uri
|
||||||
|
|
||||||
json_str_tx = json.dumps(
|
json_str_tx = json.dumps(
|
||||||
prepared_token_tx,
|
prepared_token_tx,
|
||||||
sort_keys=True,
|
sort_keys=True,
|
||||||
separators=(',', ':'),
|
separators=(",", ":"),
|
||||||
ensure_ascii=False,
|
ensure_ascii=False,
|
||||||
)
|
)
|
||||||
creation_txid = sha3_256(json_str_tx.encode()).hexdigest()
|
creation_txid = sha3_256(json_str_tx.encode()).hexdigest()
|
||||||
|
|
||||||
prepared_token_tx['id'] = creation_txid
|
prepared_token_tx["id"] = creation_txid
|
||||||
|
|
||||||
print( f"signed: {prepared_token_tx}")
|
print(f"signed: {prepared_token_tx}")
|
||||||
|
|
||||||
from planetmint.transactions.types.assets.create import Create
|
|
||||||
from planetmint.transactions.types.assets.transfer import Transfer
|
|
||||||
from planetmint.models import Transaction
|
from planetmint.models import Transaction
|
||||||
from planetmint.transactions.common.exceptions import SchemaValidationError, ValidationError
|
from planetmint.transactions.common.exceptions import (
|
||||||
from flask import current_app
|
SchemaValidationError,
|
||||||
from planetmint.transactions.common.transaction_mode_types import BROADCAST_TX_ASYNC
|
ValidationError,
|
||||||
|
)
|
||||||
|
|
||||||
validated = None
|
validated = None
|
||||||
try:
|
try:
|
||||||
tx_obj = Transaction.from_dict(prepared_token_tx)
|
tx_obj = Transaction.from_dict(prepared_token_tx)
|
||||||
except SchemaValidationError as e:
|
except SchemaValidationError:
|
||||||
assert()
|
assert ()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
print(e)
|
print(e)
|
||||||
assert()
|
assert ()
|
||||||
|
|
||||||
from planetmint.lib import Planetmint
|
from planetmint.lib import Planetmint
|
||||||
|
|
||||||
planet = Planetmint()
|
planet = Planetmint()
|
||||||
validated = planet.validate_transaction(tx_obj)
|
validated = planet.validate_transaction(tx_obj)
|
||||||
print( f"\n\nVALIDATED =====: {validated}")
|
print(f"\n\nVALIDATED =====: {validated}")
|
||||||
assert not validated == False
|
assert validated == False is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_manual_tx_crafting_ext_zenroom():
|
||||||
|
producer = generate_key_pair()
|
||||||
|
producer_ed25519 = Ed25519Sha256(public_key=base58.b58decode(producer.public_key))
|
||||||
|
condition_uri = producer_ed25519.condition.serialize_uri()
|
||||||
|
output = {
|
||||||
|
"amount": "3000",
|
||||||
|
"condition": {
|
||||||
|
"details": {"type": "ed25519-sha-256", "public_key": producer.public_key},
|
||||||
|
"uri": condition_uri,
|
||||||
|
},
|
||||||
|
"public_keys": [
|
||||||
|
producer.public_key,
|
||||||
|
],
|
||||||
|
}
|
||||||
|
input_ = {
|
||||||
|
"fulfillment": None,
|
||||||
|
"fulfills": None,
|
||||||
|
"owners_before": [
|
||||||
|
producer.public_key,
|
||||||
|
],
|
||||||
|
}
|
||||||
|
version = "2.0"
|
||||||
|
prepared_token_tx = {
|
||||||
|
"operation": "CREATE",
|
||||||
|
"asset": HOUSE_ASSETS, # rfid_token,
|
||||||
|
"metadata": metadata,
|
||||||
|
"outputs": [
|
||||||
|
output,
|
||||||
|
],
|
||||||
|
"inputs": [
|
||||||
|
input_,
|
||||||
|
],
|
||||||
|
"version": version,
|
||||||
|
"id": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
print(f"prepared: {prepared_token_tx}")
|
||||||
|
|
||||||
|
# Create sha3-256 of message to sign
|
||||||
|
message = json.dumps(
|
||||||
|
prepared_token_tx,
|
||||||
|
sort_keys=True,
|
||||||
|
separators=(",", ":"),
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
message_hash = sha3_256(message.encode())
|
||||||
|
|
||||||
|
producer_ed25519.sign(message_hash.digest(), base58.b58decode(producer.private_key))
|
||||||
|
|
||||||
|
fulfillment_uri = producer_ed25519.serialize_uri()
|
||||||
|
|
||||||
|
prepared_token_tx["inputs"][0]["fulfillment"] = fulfillment_uri
|
||||||
|
|
||||||
|
json_str_tx = json.dumps(
|
||||||
|
prepared_token_tx,
|
||||||
|
sort_keys=True,
|
||||||
|
separators=(",", ":"),
|
||||||
|
ensure_ascii=False,
|
||||||
|
)
|
||||||
|
creation_txid = sha3_256(json_str_tx.encode()).hexdigest()
|
||||||
|
|
||||||
|
prepared_token_tx["id"] = creation_txid
|
||||||
|
|
||||||
|
print(f"signed: {prepared_token_tx}")
|
||||||
|
|
||||||
|
from planetmint.models import Transaction
|
||||||
|
from planetmint.transactions.common.exceptions import (
|
||||||
|
SchemaValidationError,
|
||||||
|
ValidationError,
|
||||||
|
)
|
||||||
|
|
||||||
|
validated = None
|
||||||
|
try:
|
||||||
|
tx_obj = Transaction.from_dict(prepared_token_tx)
|
||||||
|
except SchemaValidationError:
|
||||||
|
assert ()
|
||||||
|
except ValidationError as e:
|
||||||
|
print(e)
|
||||||
|
assert ()
|
||||||
|
|
||||||
|
from planetmint.lib import Planetmint
|
||||||
|
|
||||||
|
planet = Planetmint()
|
||||||
|
validated = planet.validate_transaction(tx_obj)
|
||||||
|
print(f"\n\nVALIDATED =====: {validated}")
|
||||||
|
assert validated == False is False
|
||||||
|
|
||||||
|
|
||||||
def test_zenroom_signing():
|
def test_zenroom_signing():
|
||||||
|
|
||||||
biolabs = generate_key_pair()
|
biolabs = generate_key_pair()
|
||||||
version = '2.0'
|
version = "2.0"
|
||||||
|
|
||||||
alice = json.loads(ZenroomSha256.run_zenroom(GENERATE_KEYPAIR).output)['keyring']
|
alice = json.loads(ZenroomSha256.run_zenroom(GENERATE_KEYPAIR).output)["keyring"]
|
||||||
bob = json.loads(ZenroomSha256.run_zenroom(GENERATE_KEYPAIR).output)['keyring']
|
bob = json.loads(ZenroomSha256.run_zenroom(GENERATE_KEYPAIR).output)["keyring"]
|
||||||
|
|
||||||
zen_public_keys = json.loads(ZenroomSha256.run_zenroom(SK_TO_PK.format('Alice'),
|
zen_public_keys = json.loads(
|
||||||
keys={'keyring': alice}).output)
|
ZenroomSha256.run_zenroom(
|
||||||
zen_public_keys.update(json.loads(ZenroomSha256.run_zenroom(SK_TO_PK.format('Bob'),
|
SK_TO_PK.format("Alice"), keys={"keyring": alice}
|
||||||
keys={'keyring': bob}).output))
|
).output
|
||||||
|
)
|
||||||
|
zen_public_keys.update(
|
||||||
|
json.loads(
|
||||||
|
ZenroomSha256.run_zenroom(
|
||||||
|
SK_TO_PK.format("Bob"), keys={"keyring": bob}
|
||||||
|
).output
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
zenroomscpt = ZenroomSha256(
|
||||||
|
script=FULFILL_SCRIPT, data=ZENROOM_DATA, keys=zen_public_keys
|
||||||
|
)
|
||||||
|
print(f"zenroom is: {zenroomscpt.script}")
|
||||||
|
|
||||||
|
|
||||||
zenroomscpt = ZenroomSha256(script=FULFILL_SCRIPT, data=ZENROOM_DATA, keys=zen_public_keys)
|
|
||||||
print(F'zenroom is: {zenroomscpt.script}')
|
|
||||||
|
|
||||||
# CRYPTO-CONDITIONS: generate the condition uri
|
# CRYPTO-CONDITIONS: generate the condition uri
|
||||||
condition_uri_zen = zenroomscpt.condition.serialize_uri()
|
condition_uri_zen = zenroomscpt.condition.serialize_uri()
|
||||||
print(F'\nzenroom condition URI: {condition_uri_zen}')
|
print(f"\nzenroom condition URI: {condition_uri_zen}")
|
||||||
|
|
||||||
# CRYPTO-CONDITIONS: construct an unsigned fulfillment dictionary
|
# CRYPTO-CONDITIONS: construct an unsigned fulfillment dictionary
|
||||||
unsigned_fulfillment_dict_zen = {
|
unsigned_fulfillment_dict_zen = {
|
||||||
'type': zenroomscpt.TYPE_NAME,
|
"type": zenroomscpt.TYPE_NAME,
|
||||||
'public_key': base58.b58encode(biolabs.public_key).decode(),
|
"public_key": base58.b58encode(biolabs.public_key).decode(),
|
||||||
}
|
}
|
||||||
output = {
|
output = {
|
||||||
'amount': '10',
|
"amount": "10",
|
||||||
'condition': {
|
"condition": {
|
||||||
'details': unsigned_fulfillment_dict_zen,
|
"details": unsigned_fulfillment_dict_zen,
|
||||||
'uri': condition_uri_zen,
|
"uri": condition_uri_zen,
|
||||||
|
|
||||||
},
|
},
|
||||||
'public_keys': [biolabs.public_key,],
|
"public_keys": [
|
||||||
|
biolabs.public_key,
|
||||||
|
],
|
||||||
}
|
}
|
||||||
input_ = {
|
input_ = {
|
||||||
'fulfillment': None,
|
"fulfillment": None,
|
||||||
'fulfills': None,
|
"fulfills": None,
|
||||||
'owners_before': [biolabs.public_key,]
|
"owners_before": [
|
||||||
|
biolabs.public_key,
|
||||||
|
],
|
||||||
}
|
}
|
||||||
token_creation_tx = {
|
token_creation_tx = {
|
||||||
'operation': 'CREATE',
|
"operation": "CREATE",
|
||||||
'asset': HOUSE_ASSETS,
|
"asset": HOUSE_ASSETS,
|
||||||
'metadata': None,
|
"metadata": None,
|
||||||
'outputs': [output,],
|
"outputs": [
|
||||||
'inputs': [input_,],
|
output,
|
||||||
'version': version,
|
],
|
||||||
'id': None,
|
"inputs": [
|
||||||
|
input_,
|
||||||
|
],
|
||||||
|
"version": version,
|
||||||
|
"id": None,
|
||||||
}
|
}
|
||||||
|
|
||||||
# JSON: serialize the transaction-without-id to a json formatted string
|
# JSON: serialize the transaction-without-id to a json formatted string
|
||||||
message = json.dumps(
|
message = json.dumps(
|
||||||
token_creation_tx,
|
token_creation_tx,
|
||||||
sort_keys=True,
|
sort_keys=True,
|
||||||
separators=(',', ':'),
|
separators=(",", ":"),
|
||||||
ensure_ascii=False,
|
ensure_ascii=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
# major workflow:
|
# major workflow:
|
||||||
# we store the fulfill script in the transaction/message (zenroom-sha)
|
# we store the fulfill script in the transaction/message (zenroom-sha)
|
||||||
# the condition script is used to fulfill the transaction and create the signature
|
# the condition script is used to fulfill the transaction and create the signature
|
||||||
#
|
#
|
||||||
# the server should ick the fulfill script and recreate the zenroom-sha and verify the signature
|
# the server should ick the fulfill script and recreate the zenroom-sha and verify the signature
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
message = zenroomscpt.sign(message, CONDITION_SCRIPT, alice)
|
message = zenroomscpt.sign(message, CONDITION_SCRIPT, alice)
|
||||||
assert(zenroomscpt.validate(message=message))
|
assert zenroomscpt.validate(message=message)
|
||||||
|
|
||||||
message = json.loads(message)
|
message = json.loads(message)
|
||||||
fulfillment_uri_zen = zenroomscpt.serialize_uri()
|
fulfillment_uri_zen = zenroomscpt.serialize_uri()
|
||||||
|
|
||||||
message['inputs'][0]['fulfillment'] = fulfillment_uri_zen
|
message["inputs"][0]["fulfillment"] = fulfillment_uri_zen
|
||||||
tx = message
|
tx = message
|
||||||
tx['id'] = None
|
tx["id"] = None
|
||||||
json_str_tx = json.dumps(
|
json_str_tx = json.dumps(tx, sort_keys=True, skipkeys=False, separators=(",", ":"))
|
||||||
tx,
|
|
||||||
sort_keys=True,
|
|
||||||
skipkeys=False,
|
|
||||||
separators=(',', ':')
|
|
||||||
)
|
|
||||||
# SHA3: hash the serialized id-less transaction to generate the id
|
# SHA3: hash the serialized id-less transaction to generate the id
|
||||||
shared_creation_txid = sha3_256(json_str_tx.encode()).hexdigest()
|
shared_creation_txid = sha3_256(json_str_tx.encode()).hexdigest()
|
||||||
message['id'] = shared_creation_txid
|
message["id"] = shared_creation_txid
|
||||||
|
|
||||||
|
|
||||||
from planetmint.transactions.types.assets.create import Create
|
|
||||||
from planetmint.transactions.types.assets.transfer import Transfer
|
|
||||||
from planetmint.models import Transaction
|
from planetmint.models import Transaction
|
||||||
from planetmint.transactions.common.exceptions import SchemaValidationError, ValidationError
|
from planetmint.transactions.common.exceptions import (
|
||||||
from flask import current_app
|
SchemaValidationError,
|
||||||
|
ValidationError,
|
||||||
|
)
|
||||||
from planetmint.transactions.common.transaction_mode_types import BROADCAST_TX_ASYNC
|
from planetmint.transactions.common.transaction_mode_types import BROADCAST_TX_ASYNC
|
||||||
|
|
||||||
validated = None
|
validated = None
|
||||||
try:
|
try:
|
||||||
tx_obj = Transaction.from_dict(message)
|
tx_obj = Transaction.from_dict(message)
|
||||||
except SchemaValidationError as e:
|
except SchemaValidationError:
|
||||||
assert()
|
assert ()
|
||||||
except ValidationError as e:
|
except ValidationError as e:
|
||||||
print(e)
|
print(e)
|
||||||
assert()
|
assert ()
|
||||||
|
|
||||||
from planetmint.lib import Planetmint
|
from planetmint.lib import Planetmint
|
||||||
|
|
||||||
planet = Planetmint()
|
planet = Planetmint()
|
||||||
validated = planet.validate_transaction(tx_obj)
|
validated = planet.validate_transaction(tx_obj)
|
||||||
|
|
||||||
mode = BROADCAST_TX_ASYNC
|
mode = BROADCAST_TX_ASYNC
|
||||||
status_code, message = planet.write_transaction(tx_obj, mode)
|
status_code, message = planet.write_transaction(tx_obj, mode)
|
||||||
print( f"\n\nstatus and result : {status_code} + {message}")
|
print(f"\n\nstatus and result : {status_code} + {message}")
|
||||||
print( f"VALIDATED : {validated}")
|
print(f"VALIDATED : {validated}")
|
||||||
|
assert (validated == False) is False
|
||||||
|
|
||||||
|
|||||||
2
tox.ini
2
tox.ini
@ -25,7 +25,7 @@ extras = None
|
|||||||
commands = flake8 planetmint tests
|
commands = flake8 planetmint tests
|
||||||
|
|
||||||
[flake8]
|
[flake8]
|
||||||
ignore = E126 E127 W504 E302 E126 E305
|
ignore = E126 E127 W504 E302 E126 E305 W503 E712 F401
|
||||||
|
|
||||||
[testenv:docsroot]
|
[testenv:docsroot]
|
||||||
basepython = {[base]basepython}
|
basepython = {[base]basepython}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user