transaction.py 24.9 KB
Newer Older
1
import re
2
from typing import TypeVar, List, Any, Type, Optional, Dict, Union
3 4

import pypeg2
5 6

from duniterpy.grammars.output import Condition
7
from .block_uid import BlockUID
inso's avatar
inso committed
8
from .document import Document, MalformedDocumentError
9
from ..constants import PUBKEY_REGEX, TRANSACTION_HASH_REGEX, BLOCK_ID_REGEX, BLOCK_UID_REGEX
inso's avatar
inso committed
10 11 12
from ..grammars import output


13
def reduce_base(amount: int, base: int) -> tuple:
inso's avatar
inso committed
14 15
    """
    Compute the reduced base of the given parameters
16 17 18 19

    :param amount: the amount value
    :param base: current base value

inso's avatar
inso committed
20 21 22 23 24 25 26
    :return: tuple containing computed (amount, base)
    """
    if amount == 0:
        return 0, 0

    next_amount = amount
    next_base = base
27 28
    next_amount_is_integer = True
    while next_amount_is_integer:
inso's avatar
inso committed
29 30
        amount = next_amount
        base = next_base
31 32 33 34 35 36
        if next_amount % 10 == 0:
            next_amount = int(next_amount / 10)
            next_base += 1
        else:
            next_amount_is_integer = False

inso's avatar
inso committed
37 38 39
    return int(amount), int(base)


40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
# required to type hint cls in classmethod
InputSourceType = TypeVar('InputSourceType', bound='InputSource')


class InputSource:
    """
    A Transaction INPUT

.. note:: Compact :
    INDEX:SOURCE:FINGERPRINT:AMOUNT

    """
    re_inline = re.compile(
        "(?:(?:(D):({pubkey_regex}):({block_id_regex}))|(?:(T):({transaction_hash_regex}):([0-9]+)))\n"
        .format(pubkey_regex=PUBKEY_REGEX,
                block_id_regex=BLOCK_ID_REGEX,
                transaction_hash_regex=TRANSACTION_HASH_REGEX))
    re_inline_v3 = re.compile(
58 59
        "([0-9]+):([0-9]):(?:(?:(D):({pubkey_regex}):({block_id_regex}))|(?:(T):({transaction_hash_regex}):\
([0-9]+)))"
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        .format(pubkey_regex=PUBKEY_REGEX,
                block_id_regex=BLOCK_ID_REGEX,
                transaction_hash_regex=TRANSACTION_HASH_REGEX))

    def __init__(self, amount: int, base: int, source: str, origin_id: str, index: int) -> None:
        """
        An input source can come from a dividend or a transaction.

        :param amount: amount of the input
        :param base: base of the input
        :param source: D if dividend, T if transaction
        :param origin_id: a Public key if a dividend, a tx hash if a transaction
        :param index: a block id if a dividend, an tx index if a transaction
        :return:
        """
        self.amount = amount
        self.base = base
        self.source = source
        self.origin_id = origin_id
        self.index = index

81 82 83 84 85 86
    def __eq__(self, other: Any) -> bool:
        """
        Check InputSource instances equality
        """
        if not isinstance(other, InputSource):
            return NotImplemented
87 88 89 90 91
        return self.amount == other.amount and \
            self.base == other.base and \
            self.source == other.source and \
            self.origin_id == other.origin_id and \
            self.index == other.index
92 93 94 95

    def __hash__(self) -> int:
        return hash((self.amount, self.base, self.source, self.origin_id, self.index))

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    @classmethod
    def from_inline(cls: Type[InputSourceType], tx_version: int, inline: str) -> InputSourceType:
        """
        Return Transaction instance from inline string format

        :param tx_version: Version number of the document
        :param inline: Inline string format
        :return:
        """
        if tx_version == 2:
            data = InputSource.re_inline.match(inline)
            if data is None:
                raise MalformedDocumentError("Inline input")
            source_offset = 0
            amount = 0
            base = 0
        else:
            data = InputSource.re_inline_v3.match(inline)
            if data is None:
                raise MalformedDocumentError("Inline input")
            source_offset = 2
            amount = int(data.group(1))
            base = int(data.group(2))
        if data.group(1 + source_offset):
            source = data.group(1 + source_offset)
            origin_id = data.group(2 + source_offset)
            index = int(data.group(3 + source_offset))
        else:
            source = data.group(4 + source_offset)
            origin_id = data.group(5 + source_offset)
            index = int(data.group(6 + source_offset))

        return cls(amount, base, source, origin_id, index)

    def inline(self, tx_version: int) -> str:
        """
        Return an inline string format of the document

        :param tx_version: Version number of the document
        :return:
        """
        if tx_version == 2:
            return "{0}:{1}:{2}".format(self.source,
                                        self.origin_id,
                                        self.index)
        else:
            return "{0}:{1}:{2}:{3}:{4}".format(self.amount,
                                                self.base,
                                                self.source,
                                                self.origin_id,
                                                self.index)


# required to type hint cls in classmethod
OutputSourceType = TypeVar('OutputSourceType', bound='OutputSource')


class OutputSource:
    """
    A Transaction OUTPUT
    """
157
    re_inline = re.compile("([0-9]+):([0-9]):(.*)")
158

159
    def __init__(self, amount: int, base: int, condition: str) -> None:
160 161 162 163 164
        """
        Init OutputSource instance

        :param amount: Amount of the output
        :param base: Base number
165
        :param condition: Condition expression
166 167 168
        """
        self.amount = amount
        self.base = base
169
        self.condition = self.condition_from_text(condition)
170

171 172 173 174 175 176
    def __eq__(self, other: Any) -> bool:
        """
        Check OutputSource instances equality
        """
        if not isinstance(other, OutputSource):
            return NotImplemented
177 178 179
        return self.amount == other.amount and \
            self.base == other.base and \
            self.condition == other.condition
180 181 182 183

    def __hash__(self) -> int:
        return hash((self.amount, self.base, self.condition))

184 185 186 187 188 189 190 191 192 193 194 195 196
    @classmethod
    def from_inline(cls: Type[OutputSourceType], inline: str) -> OutputSourceType:
        """
        Return OutputSource instance from inline string format

        :param inline: Inline string format
        :return:
        """
        data = OutputSource.re_inline.match(inline)
        if data is None:
            raise MalformedDocumentError("Inline output")
        amount = int(data.group(1))
        base = int(data.group(2))
197 198 199
        condition_text = data.group(3)

        return cls(amount, base, condition_text)
200 201 202

    def inline(self) -> str:
        """
203
        Return an inline string format of the output source
204 205 206

        :return:
        """
207 208 209
        return "{0}:{1}:{2}".format(self.amount, self.base,
                                    pypeg2.compose(self.condition, output.Condition))

210 211 212 213 214 215 216 217
    def inline_condition(self) -> str:
        """
        Return an inline string format of the output source’s condition

        :return:
        """
        return pypeg2.compose(self.condition, output.Condition)

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
    @staticmethod
    def condition_from_text(text) -> Condition:
        """
        Return a Condition instance with PEG grammar from text

        :param text: PEG parsable string
        :return:
        """
        try:
            condition = pypeg2.parse(text, output.Condition)
        except SyntaxError:
            # Invalid conditions are possible, see https://github.com/duniter/duniter/issues/1156
            # In such a case, they are store as empty PEG grammar object and considered unlockable
            condition = Condition(text)
        return condition
233 234 235 236 237 238 239 240 241 242


# required to type hint cls in classmethod
SIGParameterType = TypeVar('SIGParameterType', bound='SIGParameter')


class SIGParameter:
    """
    A Transaction UNLOCK SIG parameter
    """
243
    re_sig = re.compile("SIG\\(([0-9]+)\\)")
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284

    def __init__(self, index: int) -> None:
        """
        Init SIGParameter instance

        :param index: Index in list
        """
        self.index = index

    @classmethod
    def from_parameter(cls: Type[SIGParameterType], parameter: str) -> Optional[SIGParameterType]:
        """
        Return a SIGParameter instance from an index parameter

        :param parameter: Index parameter

        :return:
        """
        sig = SIGParameter.re_sig.match(parameter)
        if sig:
            return cls(int(sig.group(1)))

        return None

    def __str__(self):
        """
        Return a string representation of the SIGParameter instance

        :return:
        """
        return "SIG({0})".format(self.index)


# required to type hint cls in classmethod
XHXParameterType = TypeVar('XHXParameterType', bound='XHXParameter')


class XHXParameter:
    """
    A Transaction UNLOCK XHX parameter
    """
285
    re_xhx = re.compile("XHX\\(([0-9]+)\\)")
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

    def __init__(self, integer: int) -> None:
        """
        Init XHXParameter instance

        :param integer: XHX number
        """
        self.integer = integer

    @classmethod
    def from_parameter(cls: Type[XHXParameterType], parameter: str) -> Optional[XHXParameterType]:
        """
        Return a XHXParameter instance from an index parameter

        :param parameter: Index parameter

        :return:
        """
        xhx = XHXParameter.re_xhx.match(parameter)
        if xhx:
            return cls(int(xhx.group(1)))

        return None

    def compute(self):
        pass

    def __str__(self):
        """
        Return a string representation of the XHXParameter instance

        :return:
        """
        return "XHX({0})".format(self.integer)


# required to type hint cls in classmethod
UnlockParameterType = TypeVar('UnlockParameterType', bound='UnlockParameter')


class UnlockParameter:

    @classmethod
    def from_parameter(cls: Type[UnlockParameterType], parameter: str) -> Optional[Union[SIGParameter, XHXParameter]]:
        """
        Return UnlockParameter instance from parameter string

        :param parameter: Parameter string
        :return:
        """

        sig_param = SIGParameter.from_parameter(parameter)
        if sig_param:
            return sig_param
        else:
            xhx_param = XHXParameter.from_parameter(parameter)
            if xhx_param:
                return xhx_param

        return None

    def compute(self):
        pass


# required to type hint cls in classmethod
UnlockType = TypeVar('UnlockType', bound='Unlock')


class Unlock:
    """
    A Transaction UNLOCK
    """
359
    re_inline = re.compile("([0-9]+):((?:SIG\\([0-9]+\\)|XHX\\([0-9]+\\)|\\s)+)\n")
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404

    def __init__(self, index: int, parameters: List[Union[SIGParameter, XHXParameter]]) -> None:
        """
        Init Unlock instance

        :param index: Index number
        :param parameters: List of UnlockParameter instances
        """
        self.index = index
        self.parameters = parameters

    @classmethod
    def from_inline(cls: Type[UnlockType], inline: str) -> UnlockType:
        """
        Return an Unlock instance from inline string format

        :param inline: Inline string format

        :return:
        """
        data = Unlock.re_inline.match(inline)
        if data is None:
            raise MalformedDocumentError("Inline input")
        index = int(data.group(1))
        parameters_str = data.group(2).split(' ')
        parameters = []
        for p in parameters_str:
            param = UnlockParameter.from_parameter(p)
            if param:
                parameters.append(param)
        return cls(index, parameters)

    def inline(self) -> str:
        """
        Return inline string format of the instance

        :return:
        """
        return "{0}:{1}".format(self.index, ' '.join([str(p) for p in self.parameters]))


# required to type hint cls in classmethod
TransactionType = TypeVar('TransactionType', bound='Transaction')


inso's avatar
inso committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
class Transaction(Document):
    """
.. note:: A transaction document is specified by the following format :

    | Document format :
    | Version: VERSION
    | Type: Transaction
    | Currency: CURRENCY_NAME
    | Issuers:
    | PUBLIC_KEY
    | ...
    | Inputs:
    | INDEX:SOURCE:NUMBER:FINGERPRINT:AMOUNT
    | ...
    | Outputs:
    | PUBLIC_KEY:AMOUNT
    | ...
    | Comment: COMMENT
    | ...
    |
    |
    | Compact format :
    | TX:VERSION:NB_ISSUERS:NB_INPUTS:NB_OUTPUTS:HAS_COMMENT
    | PUBLIC_KEY:INDEX
    | ...
    | INDEX:SOURCE:FINGERPRINT:AMOUNT
    | ...
    | PUBLIC_KEY:AMOUNT
    | ...
    | COMMENT
    | SIGNATURE
    | ...

    """

    re_type = re.compile("Type: (Transaction)\n")
441
    re_header = re.compile("TX:([0-9]+):([0-9]+):([0-9]+):([0-9]+):([0-9]+):([01]):([0-9]+)\n")
442 443
    re_compact_blockstamp = re.compile("({block_uid_regex})\n".format(block_uid_regex=BLOCK_UID_REGEX))
    re_blockstamp = re.compile("Blockstamp: ({block_uid_regex})\n".format(block_uid_regex=BLOCK_UID_REGEX))
inso's avatar
inso committed
444 445 446 447 448 449 450
    re_locktime = re.compile("Locktime: ([0-9]+)\n")
    re_issuers = re.compile("Issuers:\n")
    re_inputs = re.compile("Inputs:\n")
    re_unlocks = re.compile("Unlocks:\n")
    re_outputs = re.compile("Outputs:\n")
    re_compact_comment = re.compile("([^\n]+)\n")
    re_comment = re.compile("Comment: ([^\n]*)\n")
451
    re_pubkey = re.compile("({pubkey_regex})\n".format(pubkey_regex=PUBKEY_REGEX))
inso's avatar
inso committed
452 453

    fields_parsers = {**Document.fields_parsers, **{
454 455 456 457 458 459 460 461 462 463 464 465
        "Type": re_type,
        "Blockstamp": re_blockstamp,
        "CompactBlockstamp": re_compact_blockstamp,
        "Locktime": re_locktime,
        "TX": re_header,
        "Issuers": re_issuers,
        "Inputs": re_inputs,
        "Unlocks": re_unlocks,
        "Outputs": re_outputs,
        "Comment": re_comment,
        "Compact comment": re_compact_comment,
        "Pubkey": re_pubkey
inso's avatar
inso committed
466
    }
467
                      }
inso's avatar
inso committed
468

469 470 471
    def __init__(self, version: int, currency: str, blockstamp: Optional[BlockUID], locktime: int, issuers: List[str],
                 inputs: List[InputSource], unlocks: List[Unlock], outputs: List[OutputSource],
                 comment: str, signatures: List[str]) -> None:
inso's avatar
inso committed
472
        """
473 474 475 476 477 478 479 480 481 482 483 484
        Init Transaction instance

        :param version: Version number of the document
        :param currency: Name of the currency
        :param blockstamp: BlockUID timestamp of the block
        :param locktime: Lock time in seconds
        :param issuers: List of issuers public key
        :param inputs: List of InputSource instances
        :param unlocks: List of Unlock instances
        :param outputs: List of OutputSource instances
        :param comment: Comment field
        :param signatures: List of signatures
inso's avatar
inso committed
485 486
        """
        super().__init__(version, currency, signatures)
inso's avatar
inso committed
487
        self.blockstamp = blockstamp
inso's avatar
inso committed
488 489 490 491 492 493 494
        self.locktime = locktime
        self.issuers = issuers
        self.inputs = inputs
        self.unlocks = unlocks
        self.outputs = outputs
        self.comment = comment

inso's avatar
inso committed
495
    @classmethod
496
    def from_bma_history(cls: Type[TransactionType], currency: str, tx_data: Dict) -> TransactionType:
inso's avatar
inso committed
497
        """
498 499 500 501 502 503
        Get the transaction instance from json

        :param currency: the currency of the tx
        :param tx_data: json data of the transaction

        :return:
inso's avatar
inso committed
504 505 506 507 508 509
        """
        tx_data = tx_data.copy()
        tx_data["currency"] = currency
        for data_list in ('issuers', 'outputs', 'inputs', 'unlocks', 'signatures'):
            tx_data['multiline_{0}'.format(data_list)] = '\n'.join(tx_data[data_list])
        if tx_data["version"] >= 3:
510
            signed_raw = """Version: {version}
inso's avatar
inso committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
Type: Transaction
Currency: {currency}
Blockstamp: {blockstamp}
Locktime: {locktime}
Issuers:
{multiline_issuers}
Inputs:
{multiline_inputs}
Unlocks:
{multiline_unlocks}
Outputs:
{multiline_outputs}
Comment: {comment}
{multiline_signatures}
""".format(**tx_data)
        else:
            signed_raw = """Version: {version}
Type: Transaction
Currency: {currency}
Locktime: {locktime}
Issuers:
{multiline_issuers}
Inputs:
{multiline_inputs}
Unlocks:
{multiline_unlocks}
Outputs:
{multiline_outputs}
Comment: {comment}
{multiline_signatures}
""".format(**tx_data)
542
        return cls.from_signed_raw(signed_raw)
inso's avatar
inso committed
543

inso's avatar
inso committed
544
    @classmethod
545 546 547 548 549 550 551 552
    def from_compact(cls: Type[TransactionType], currency: str, compact: str) -> TransactionType:
        """
        Return Transaction instance from compact string format

        :param currency: Name of the currency
        :param compact: Compact format string
        :return:
        """
inso's avatar
inso committed
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        lines = compact.splitlines(True)
        n = 0

        header_data = Transaction.re_header.match(lines[n])
        if header_data is None:
            raise MalformedDocumentError("Compact TX header")
        version = int(header_data.group(1))
        issuers_num = int(header_data.group(2))
        inputs_num = int(header_data.group(3))
        unlocks_num = int(header_data.group(4))
        outputs_num = int(header_data.group(5))
        has_comment = int(header_data.group(6))
        locktime = int(header_data.group(7))
        n += 1

568
        blockstamp = None  # type: Optional[BlockUID]
inso's avatar
inso committed
569 570 571 572
        if version >= 3:
            blockstamp = BlockUID.from_str(Transaction.parse_field("CompactBlockstamp", lines[n]))
            n += 1

inso's avatar
inso committed
573 574 575 576 577 578 579 580 581 582 583
        issuers = []
        inputs = []
        unlocks = []
        outputs = []
        signatures = []
        for i in range(0, issuers_num):
            issuer = Transaction.parse_field("Pubkey", lines[n])
            issuers.append(issuer)
            n += 1

        for i in range(0, inputs_num):
inso's avatar
inso committed
584
            input_source = InputSource.from_inline(version, lines[n])
inso's avatar
inso committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
            inputs.append(input_source)
            n += 1

        for i in range(0, unlocks_num):
            unlock = Unlock.from_inline(lines[n])
            unlocks.append(unlock)
            n += 1

        for i in range(0, outputs_num):
            output_source = OutputSource.from_inline(lines[n])
            outputs.append(output_source)
            n += 1

        comment = ""
        if has_comment == 1:
600 601 602
            data = Transaction.re_compact_comment.match(lines[n])
            if data:
                comment = data.group(1)
inso's avatar
inso committed
603 604 605 606 607
                n += 1
            else:
                raise MalformedDocumentError("Compact TX Comment")

        while n < len(lines):
608 609 610
            data = Transaction.re_signature.match(lines[n])
            if data:
                signatures.append(data.group(1))
inso's avatar
inso committed
611 612 613 614
                n += 1
            else:
                raise MalformedDocumentError("Compact TX Signatures")

inso's avatar
inso committed
615
        return cls(version, currency, blockstamp, locktime, issuers, inputs, unlocks, outputs, comment, signatures)
inso's avatar
inso committed
616 617

    @classmethod
618 619 620 621 622 623 624 625
    def from_signed_raw(cls: Type[TransactionType], raw: str) -> TransactionType:
        """
        Return a Transaction instance from a raw string format

        :param raw: Raw string format

        :return:
        """
inso's avatar
inso committed
626 627 628 629 630 631 632 633 634 635 636 637
        lines = raw.splitlines(True)
        n = 0

        version = int(Transaction.parse_field("Version", lines[n]))
        n += 1

        Transaction.parse_field("Type", lines[n])
        n += 1

        currency = Transaction.parse_field("Currency", lines[n])
        n += 1

638
        blockstamp = None  # type: Optional[BlockUID]
inso's avatar
inso committed
639 640 641 642
        if version >= 3:
            blockstamp = BlockUID.from_str(Transaction.parse_field("Blockstamp", lines[n]))
            n += 1

inso's avatar
inso committed
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
        locktime = Transaction.parse_field("Locktime", lines[n])
        n += 1

        issuers = []
        inputs = []
        unlocks = []
        outputs = []
        signatures = []

        if Transaction.re_issuers.match(lines[n]):
            n += 1
            while Transaction.re_inputs.match(lines[n]) is None:
                issuer = Transaction.parse_field("Pubkey", lines[n])
                issuers.append(issuer)
                n += 1

        if Transaction.re_inputs.match(lines[n]):
            n += 1
            while Transaction.re_unlocks.match(lines[n]) is None:
inso's avatar
inso committed
662
                input_source = InputSource.from_inline(version, lines[n])
inso's avatar
inso committed
663 664 665 666 667 668 669 670 671 672 673 674 675
                inputs.append(input_source)
                n += 1

        if Transaction.re_unlocks.match(lines[n]):
            n += 1
            while Transaction.re_outputs.match(lines[n]) is None:
                unlock = Unlock.from_inline(lines[n])
                unlocks.append(unlock)
                n += 1

        if Transaction.re_outputs.match(lines[n]) is not None:
            n += 1
            while not Transaction.re_comment.match(lines[n]):
676 677
                _output = OutputSource.from_inline(lines[n])
                outputs.append(_output)
inso's avatar
inso committed
678 679 680 681 682 683 684 685 686 687 688
                n += 1

        comment = Transaction.parse_field("Comment", lines[n])
        n += 1

        if Transaction.re_signature.match(lines[n]) is not None:
            while n < len(lines):
                sign = Transaction.parse_field("Signature", lines[n])
                signatures.append(sign)
                n += 1

inso's avatar
inso committed
689
        return cls(version, currency, blockstamp, locktime, issuers, inputs, unlocks, outputs,
inso's avatar
inso committed
690 691
                   comment, signatures)

692 693 694 695 696 697
    def raw(self) -> str:
        """
        Return raw string format from the instance

        :return:
        """
inso's avatar
inso committed
698 699 700 701
        doc = """Version: {0}
Type: Transaction
Currency: {1}
""".format(self.version,
inso's avatar
inso committed
702 703 704 705
           self.currency)

        if self.version >= 3:
            doc += "Blockstamp: {0}\n".format(self.blockstamp)
inso's avatar
inso committed
706

inso's avatar
inso committed
707 708 709
        doc += "Locktime: {0}\n".format(self.locktime)

        doc += "Issuers:\n"
inso's avatar
inso committed
710 711 712 713 714
        for p in self.issuers:
            doc += "{0}\n".format(p)

        doc += "Inputs:\n"
        for i in self.inputs:
inso's avatar
inso committed
715
            doc += "{0}\n".format(i.inline(self.version))
inso's avatar
inso committed
716 717 718 719 720 721 722 723 724 725 726 727 728 729

        doc += "Unlocks:\n"
        for u in self.unlocks:
            doc += "{0}\n".format(u.inline())

        doc += "Outputs:\n"
        for o in self.outputs:
            doc += "{0}\n".format(o.inline())

        doc += "Comment: "
        doc += "{0}\n".format(self.comment)

        return doc

730
    def compact(self) -> str:
inso's avatar
inso committed
731
        """
732 733 734
        Return a transaction in its compact format from the instance

        :return:
inso's avatar
inso committed
735 736 737 738 739 740 741 742 743 744 745
        """
        """TX:VERSION:NB_ISSUERS:NB_INPUTS:NB_UNLOCKS:NB_OUTPUTS:HAS_COMMENT:LOCKTIME
PUBLIC_KEY:INDEX
...
INDEX:SOURCE:FINGERPRINT:AMOUNT
...
PUBLIC_KEY:AMOUNT
...
COMMENT
"""
        doc = "TX:{0}:{1}:{2}:{3}:{4}:{5}:{6}\n".format(self.version,
746 747 748 749 750 751
                                                        len(self.issuers),
                                                        len(self.inputs),
                                                        len(self.unlocks),
                                                        len(self.outputs),
                                                        '1' if self.comment != "" else '0',
                                                        self.locktime)
inso's avatar
inso committed
752 753 754
        if self.version >= 3:
            doc += "{0}\n".format(self.blockstamp)

inso's avatar
inso committed
755 756 757
        for pubkey in self.issuers:
            doc += "{0}\n".format(pubkey)
        for i in self.inputs:
inso's avatar
inso committed
758
            doc += "{0}\n".format(i.inline(self.version))
inso's avatar
inso committed
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
        for u in self.unlocks:
            doc += "{0}\n".format(u.inline())
        for o in self.outputs:
            doc += "{0}\n".format(o.inline())
        if self.comment != "":
            doc += "{0}\n".format(self.comment)
        for s in self.signatures:
            doc += "{0}\n".format(s)

        return doc


class SimpleTransaction(Transaction):
    """
    As transaction class, but for only one issuer.
    ...
    """
776

777 778 779
    def __init__(self, version: int, currency: str, blockstamp: BlockUID, locktime: int, issuer: str,
                 single_input: InputSource, unlocks: List[Unlock], outputs: List[OutputSource], comment: str,
                 signature: str) -> None:
inso's avatar
inso committed
780
        """
781 782
        Init instance

783 784 785 786 787 788 789 790 791 792
        :param version: Version number of the document
        :param currency: Name of the currency
        :param blockstamp: BlockUID timestamp
        :param locktime: Lock time in seconds
        :param issuer: Issuer public key
        :param single_input: InputSource instance
        :param unlocks: List of Unlock instances
        :param outputs: List of OutputSource instances
        :param comment: Comment field
        :param signature: Signature
inso's avatar
inso committed
793
        """
794 795
        super().__init__(version, currency, blockstamp, locktime, [issuer], [single_input], unlocks,
                         outputs, comment, [signature])
inso's avatar
inso committed
796 797

    @staticmethod
798
    def is_simple(tx: Transaction) -> bool:
inso's avatar
inso committed
799 800 801 802 803 804
        """
        Filter a transaction and checks if it is a basic one
        A simple transaction is a tx which has only one issuer
        and two outputs maximum. The unlocks must be done with
        simple "SIG" functions, and the outputs must be simple
        SIG conditions.
805

806
        :param tx: the transaction to check
807

inso's avatar
inso committed
808 809 810 811 812 813 814 815 816 817 818
        :return: True if a simple transaction
        """
        simple = True
        if len(tx.issuers) != 1:
            simple = False
        for unlock in tx.unlocks:
            if len(unlock.parameters) != 1:
                simple = False
            elif type(unlock.parameters[0]) is not SIGParameter:
                simple = False
        for o in tx.outputs:
819
            # if right condition is not None...
820
            if getattr(o.condition, 'right', None):
inso's avatar
inso committed
821
                simple = False
822 823 824 825
                # if left is not SIG...
            elif type(o.condition.left) is not output.SIG:
                simple = False

inso's avatar
inso committed
826
        return simple