コード例 #1
0
  def test_pass_all_parameters(self):
    """
    The request contains valid values for all parameters.
    """
    request = {
      'bundles': [
        TransactionHash(self.trytes1),
        TransactionHash(self.trytes2),
      ],

      'addresses': [
        Address(self.trytes1),
        Address(self.trytes2),
      ],

      'tags': [
        Tag(self.trytes1),
        Tag(self.trytes3),
      ],

      'approvees': [
        TransactionHash(self.trytes1),
        TransactionHash(self.trytes3),
      ],
    }

    filter_ = self._filter(request)

    self.assertFilterPasses(filter_)
    self.assertDictEqual(filter_.cleaned_data, request)
コード例 #2
0
    def test_pass_tags_only(self):
        """
    The request only includes tags.
    """
        # print("type(Tag(self.trytes1)): ", type(Tag(self.trytes1)))
        # # <class 'iota.types.Tag'>
        # print('Tag(self.trytes1): ', Tag(self.trytes1))
        # # RBTC9D9DCDQAEASBYBCCKBFA999
        request = {
            'tags': [
                Tag(self.trytes1),
                Tag(self.trytes3),
            ],
        }

        filter_ = self._filter(request)
        # print('filter_.cleaned_data: ', filter_.cleaned_data)
        # # {'tags': ['RBTC9D9DCDQAEASBYBCCKBFA999', '999999999999999999999999999']}

        self.assertFilterPasses(filter_)
        self.assertDictEqual(
            filter_.cleaned_data,
            {
                'tags': [
                    text_type(Tag(self.trytes1)),
                    text_type(Tag(self.trytes3)),
                ],

                # Null criteria are not included in the request.
                # https://github.com/iotaledger/iota.lib.py/issues/96
                # 'addresses':  [],
                # 'approvees':  [],
                # 'bundles':    [],
            },
        )
コード例 #3
0
    def test_pass_all_parameters(self):
        """
    The request contains valid values for all parameters.
    """
        # Raw trytes are extracted to match the IRI's JSON protocol.
        request = {
            'bundles': [
                text_type(BundleHash(self.trytes1)),
                text_type(BundleHash(self.trytes2)),
            ],
            'addresses': [
                text_type(Address(self.trytes1)),
                text_type(Address(self.trytes2)),
            ],
            'tags': [
                text_type(Tag(self.trytes1)),
                text_type(Tag(self.trytes3)),
            ],
            'approvees': [
                text_type(TransactionHash(self.trytes1)),
                text_type(TransactionHash(self.trytes3)),
            ],
        }

        filter_ = self._filter(request)

        self.assertFilterPasses(filter_)
        self.assertDictEqual(filter_.cleaned_data, request)
コード例 #4
0
  def test_pass_tags_only(self):
    """
    The request only includes tags.
    """
    request = {
      'tags': [
        Tag(self.trytes1),
        Tag(self.trytes3),
      ],
    }

    filter_ = self._filter(request)

    self.assertFilterPasses(filter_)
    self.assertDictEqual(
      filter_.cleaned_data,

      {
        'tags': [
          text_type(Tag(self.trytes1)),
          text_type(Tag(self.trytes3)),
        ],

        'addresses':  [],
        'approvees':  [],
        'bundles':    [],
      },
    )
コード例 #5
0
    def test_pass_tags_only(self):
        """
    The request only includes tags.
    """
        request = {
            'tags': [
                Tag(self.trytes1),
                Tag(self.trytes3),
            ],
        }

        filter_ = self._filter(request)

        self.assertFilterPasses(filter_)
        self.assertDictEqual(
            filter_.cleaned_data,
            {
                'tags': [
                    text_type(Tag(self.trytes1)),
                    text_type(Tag(self.trytes3)),
                ],

                # Null criteria are not included in the request.
                # https://github.com/iotaledger/iota.lib.py/issues/96
                # 'addresses':  [],
                # 'approvees':  [],
                # 'bundles':    [],
            },
        )
コード例 #6
0
ファイル: forms.py プロジェクト: wusyong/pyota-flask
 def validate_search(self, input):
     if not Tag(input.data):
         if not Hash(input.data):
             if not Address(input.data):
                 raise ValidationError('Please enter an address, transaction hash, bundle or tag.')
             else:
                 input.data = Address(input.data)
         else:
             input.data = Hash(input.data)
     else:
         input.data = Tag(input.data)
コード例 #7
0
  def test_pass_compatible_types(self):
    """
    The request contains values that can be converted to the expected
    types.
    """
    filter_ = self._filter({
      'bundles': [
        self.trytes1.encode('ascii'),
        TransactionHash(self.trytes2),
      ],

      'addresses': [
        self.trytes1.encode('ascii'),
        Address(self.trytes2),
      ],

      'tags': [
        self.trytes1.encode('ascii'),
        Tag(self.trytes3),
      ],

      'approvees': [
        self.trytes1.encode('ascii'),
        TransactionHash(self.trytes3),
      ],
    })

    self.assertFilterPasses(filter_)
    self.assertDictEqual(
      filter_.cleaned_data,

      {
        # Raw trytes are extracted to match the IRI's JSON protocol.
        'bundles': [
          text_type(TransactionHash(self.trytes1)),
          text_type(TransactionHash(self.trytes2)),
        ],

        'addresses': [
          text_type(Address(self.trytes1)),
          text_type(Address(self.trytes2)),
        ],

        'tags': [
          text_type(Tag(self.trytes1)),
          text_type(Tag(self.trytes3)),
        ],

        'approvees': [
          text_type(TransactionHash(self.trytes1)),
          text_type(TransactionHash(self.trytes3)),
        ],
      },
    )
コード例 #8
0
    def test_pass_compatible_types(self):
        """
    The request contains values that can be converted to the expected
    types.
    """
        filter_ = self._filter({
            'bundles': [
                self.trytes1.encode('ascii'),
                TransactionHash(self.trytes2),
            ],
            'addresses': [
                self.trytes1.encode('ascii'),
                Address(self.trytes2),
            ],
            'tags': [
                self.trytes1.encode('ascii'),
                Tag(self.trytes3),
            ],
            'approvees': [
                self.trytes1.encode('ascii'),
                TransactionHash(self.trytes3),
            ],
        })
        print_var_type_n_val(
            var001=filter_,
            pointer="#WXCVBFGrtrer12349999")  #WXCVBFGrtrer12349999
        # Value:
        # # FindTransactionsRequestFilter(FilterChain(Type(Mapping, allow_subclass=True) | FilterMapper(addresses=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | AddressNoChecksum() | Unicode(encoding='ascii')))), approvees=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | Trytes() | Unicode(encoding='ascii')))), bundles=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | Trytes() | Unicode(encoding='ascii')))), tags=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | Trytes() | Unicode(encoding='ascii')))))))

        # Type: <class 'filters.handlers.FilterRunner'>
        self.assertFilterPasses(filter_)
        # to_find: where is the command above is being created
        self.assertDictEqual(
            filter_.cleaned_data,
            {
                # Raw trytes are extracted to match the IRI's JSON protocol.
                'bundles': [
                    text_type(TransactionHash(self.trytes1)),
                    text_type(TransactionHash(self.trytes2)),
                ],
                'addresses': [
                    text_type(Address(self.trytes1)),
                    text_type(Address(self.trytes2)),
                ],
                'tags': [
                    text_type(Tag(self.trytes1)),
                    text_type(Tag(self.trytes3)),
                ],
                'approvees': [
                    text_type(TransactionHash(self.trytes1)),
                    text_type(TransactionHash(self.trytes3)),
                ],
            },
        )
コード例 #9
0
  def test_pass_compatible_types(self):
    """
    The request contains values that can be converted to the expected
    types.
    """
    filter_ = self._filter({
      'bundles': [
        binary_type(self.trytes1),
        bytearray(self.trytes2),
      ],

      'addresses': [
        binary_type(self.trytes1),
        bytearray(self.trytes2),
      ],

      'tags': [
        binary_type(self.trytes1),
        bytearray(self.trytes3),
      ],

      'approvees': [
        binary_type(self.trytes1),
        bytearray(self.trytes3),
      ],
    })

    self.assertFilterPasses(filter_)
    self.assertDictEqual(
      filter_.cleaned_data,

      {
        'bundles': [
          TransactionHash(self.trytes1),
          TransactionHash(self.trytes2),
        ],

        'addresses': [
          Address(self.trytes1),
          Address(self.trytes2),
        ],

        'tags': [
          Tag(self.trytes1),
          Tag(self.trytes3),
        ],

        'approvees': [
          TransactionHash(self.trytes1),
          TransactionHash(self.trytes3),
        ],
      },
    )
コード例 #10
0
ファイル: tangle.py プロジェクト: davidleitw/isu-credential
def write_data_to_tangle(data):
    # Iota instance
    api = Iota(NODE_URL, SEED)

    # Txn description
    txn = ProposedTransaction(
        address = Address(receiver_address),
        message = TryteString.from_string(json.dumps(data)),
        tag = Tag(txn_tag),
        value = value,
        )

    # Send transaction
    prepared_transferes = []
    bundle = ""
    prepared_transferes.append(txn)
    try:
        bundle = api.send_transfer(
            depth = DEPTH,
            transfers = prepared_transferes,
            min_weight_magnitude = MIN_WEIGHT_MAGNITUDE
        )
    except Exception as e:
        print(e)
        return e

    print(bundle['bundle'].hash)
    return {"status":200, "bundle":bundle['bundle'].hash}
コード例 #11
0
def main():
    api = Iota("http://localhost:14265")

    # For more information, see :py:meth:`Iota.send_transfer`.
    ti = time.time()
    a = api.send_transfer(
        depth=3,
        transfers=[
            ProposedTransaction(
                # Recipient of the transfer.
                address=Address(
                    "RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999"
                ),
                value=0,

                # Optional tag to attach to the transfer.
                tag=Tag(b'KITTEHS'),

                # Optional message to include with the transfer.
                message=TryteString.from_unicode('thx fur cheezburgers'),
            ),
        ],
        min_weight_magnitude=1)
    k = 0
    for k in a["bundle"]:
        print(k)
コード例 #12
0
def add_txn_to_queue(request_data):
    request_command = json.loads(request_data)
    node_url = request_command['node_url']
    address = request_command['address']
    tag = request_command['tag']
    messages = request_command['messages']
    values = request_command['values']

    bundle_hash = ""
    prepared_transferes = []
    api = Iota(node_url, SEED)

    txn = \
        ProposedTransaction(
            address = Address(address),
            message = TryteString.from_string(messages),
            tag = Tag(tag),
            value = int(values),
    )
    prepared_transferes.append(txn)
    try:
        bundle_hash = api.send_transfer(
            depth = 7,
            transfers = prepared_transferes,
            min_weight_magnitude = 14
        )
    except Exception as e:
        print(e)
        return 0

    print(bundle_hash['bundle'].hash)
    append_log(bundle_hash['bundle'].hash, LOG_HISTORY_TXN)

    return 0
コード例 #13
0
 def pay(self, data):
     try:
         json_data = data['json_data']
         json_string = json.dumps(json_data)
         trytes = TryteString.from_string(json_string)
         # Send Transfer
         sent_transfer = self.api.send_transfer(
             depth=3,
             transfers=[
                 ProposedTransaction(
                     address=Address(data['to_address']),
                     value=data['amount'],
                     tag=Tag(data['tag']),
                     message=trytes,
                 ),
             ])
         bo = sent_transfer['bundle']
         return {
             'status': 200,
             'transaction_hash': bo.as_json_compatible()[0]['hash_'],
             'message': 'Successfully Sent!'
         }
     except Exception as pe:
         # print('pe:', pe)
         return {
             'status': 400,
             'error': '',
             # 'balance': str(pe.context['total_balance']),
             'message': str(pe).split('(')[0]
         }
コード例 #14
0
def transfer(address, tag, message, value):
    recipient_address = address
    sender_message = message
    sender_tag = tag

    prepared_transferes = []
    api = Iota(URL_NODE, SEED)

    sender_tag = bytes(sender_tag)
    transfer_value = int(value)

    txn = \
        ProposedTransaction(
            address = Address(
                recipient_address
        ),

        message = TryteString.from_string(sender_message),
        tag = Tag(sender_tag),
        value = transfer_value,
    )

    prepared_transferes.append(txn)

    dict_raw_trytes_tx = api.prepare_transfer(prepared_transferes)
    len_tx = len(dict_raw_trytes_tx['trytes'])
    for index in range(len_tx):
        print str(dict_raw_trytes_tx['trytes'][index])

    return True
コード例 #15
0
    def test_single_transaction(self):
        """
    Getting a bundle that contains a single transaction.
    """
        transaction = \
            Transaction(
                current_index=0,
                last_index=0,
                tag=Tag(b''),
                timestamp=1484960990,
                value=0,
                attachment_timestamp=1484960990,
                attachment_timestamp_lower_bound=12,
                attachment_timestamp_upper_bound=0,

                # These values are not relevant for 0-value transactions.
                nonce=Nonce(b''),
                signature_message_fragment=Fragment(b''),

                # This value is computed automatically, so it has to be real.
                hash_=TransactionHash(
                    b'XPJIYZWPF9LBCYZPNBFARDRCSUGJGF9TWZT9K9PX'
                    b'VYDFPZOZBGXUCKLTJEUCFBEKQQ9VCSQVQDMMJQAY9',
                ),

                address=Address(
                    b'TESTVALUE9DONTUSEINPRODUCTION99999OCSGVF'
                    b'IBQA99KGTCPCZ9NHR9VGLGADDDIEGGPCGBDEDDTBC',
                ),

                bundle_hash=BundleHash(
                    b'TESTVALUE9DONTUSEINPRODUCTION99999DIOAZD'
                    b'M9AIUHXGVGBC9EMGI9SBVBAIXCBFJ9EELCPDRAD9U',
                ),

                branch_transaction_hash=TransactionHash(
                    b'TESTVALUE9DONTUSEINPRODUCTION99999BBCEDI'
                    b'ZHUDWBYDJEXHHAKDOCKEKDFIMB9AMCLFW9NBDEOFV',
                ),

                trunk_transaction_hash=TransactionHash(
                    b'TESTVALUE9DONTUSEINPRODUCTION999999ARAYA'
                    b'MHCB9DCFEIWEWDLBCDN9LCCBQBKGDDAECFIAAGDAS',
                ),
            )

        self.adapter.seed_response('getTrytes', {
            'trytes': [transaction.as_tryte_string()],
        })

        response = self.command(transaction=transaction.hash)

        bundle = response['bundles'][0]  # type: Bundle
        self.assertEqual(len(bundle), 1)

        self.maxDiff = None
        self.assertDictEqual(
            bundle[0].as_json_compatible(),
            transaction.as_json_compatible(),
        )
コード例 #16
0
ファイル: trashCash.py プロジェクト: TertiusN/trashCash
def send_message(address, depth, message, tag, uri, value):
    # Ensure seed is not displayed in cleartext.
    seed = iota_seed
    # Create the API instance.
    api = Iota(uri, seed)

    print('Starting transfer please wait...\n')
    # For more information, see :py:meth:`Iota.send_transfer`.
    bundle = api.send_transfer(
        depth=depth,
        # One or more :py:class:`ProposedTransaction` objects to add to the
        # bundle.
        transfers=[
            ProposedTransaction(
                # Recipient of the transfer.
                address=Address(address),

                # Amount of IOTA to transfer.
                # By default this is a zero value transfer.
                value=value,

                # Optional tag to attach to the transfer.
                tag=Tag(tag),

                # Optional message to include with the transfer.
                message=TryteString.from_string(message),
            ),
        ],
    )

    tx_hash = bundle['bundle'].transactions[0].hash
    return tx_hash
コード例 #17
0
    def sendToAddress(self, message, address, depth, tag, value):

        api = Iota("http://iota.av.it.pt:14265")
        # Sample Data
        # address = b'RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999RQXIUOZMD'
        # depth = 3
        # tag = b'IOTAPASS'
        # value = 0

        # For more information, see :py:meth:`Iota.send_transfer`.
        try:
            api.send_transfer(
                depth=depth,
                # One or more :py:class:`ProposedTransaction` objects to add to the
                # bundle.
                transfers=[
                    ProposedTransaction(
                        # Recipient of the transfer.
                        address=Address(address),

                        # Amount of IOTA to transfer.
                        # By default this is a zero value transfer.
                        value=value,

                        # Optional tag to attach to the transfer.
                        tag=Tag(tag),

                        # Optional message to include with the transfer.
                        message=TryteString.from_string(message),
                    ),
                ],
            )
            return True
        except:
            return False
コード例 #18
0
def main():
    # Ensure seed is not displayed in cleartext.
    seed = 'SEED99999999999999999999999999999999999999999999999999999999999999999999999999999'
    # Create the API instance.
    api = Iota("http://localhost:14265", seed)
    t1 = time.time()
    print('Starting transfer.')
    # For more information, see :py:meth:`Iota.send_transfer`.
    api.send_transfer(
        depth=3,
        # One or more :py:class:`ProposedTransaction` objects to add to the
        # bundle.
        transfers=[
            ProposedTransaction(
                # Recipient of the transfer.
                address=Address(
                    'RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999'
                ),

                # Amount of IOTA to transfer.
                # By default this is a zero value transfer.
                value=42,

                # Optional tag to attach to the transfer.
                tag=Tag(b'EXAMPLE'),

                # Optional message to include with the transfer.
                message=TryteString.from_string('Hello World!'),
            ),
        ],
        min_weight_magnitude=9,
        security_level=2)
    print('Transfer complete.', time.time() - t1)
コード例 #19
0
ファイル: iota_handler.py プロジェクト: dvaruas/iota-mqtt
def tangle_and_verify(message_id, userdata, message_data):
    if not userdata or not message_id:
        return

    recv_addr = userdata.get('address_to_send', '').encode()
    iota_obj = userdata.get('iota_obj', None)
    depth_value = userdata.get('depth', 3)
    verify_server = userdata.get('verify_server', None)

    try:
        txn_1 = ProposedTransaction(address=Address(recv_addr,),
                                    value=0,
                                    tag=Tag(TryteString.from_unicode(message_id)),
                                    message=TryteString.from_unicode(message_data))
        _transactions = [txn_1, ]
        iota_obj.send_transfer(depth=depth_value, transfers=_transactions)
        print("\n .. Saved Message with ID %s succesfully to the Tangle \n" %(message_id,))
    except Exception:
        print("\n .. Could not save to Tangle -- Message ID : {0}, " \
              "Data : {1} \n".format(message_id, message_data))
        return

    try:
        msg_to_send = "{id}/".format(id=message_id)
        verify_server.sendall(msg_to_send.encode('utf-8'))
    except Exception:
        print("Something went wrong! Couldn't send data for Msg ID = %s to our " \
              "verify server" %(message_id,))
コード例 #20
0
ファイル: milestones.py プロジェクト: sripad/iri
def issue_milestone(address, api, index, *reference_transaction):
    txn1 = ProposedTransaction(address=Address(address), value=0)

    txn2 = ProposedTransaction(address=Address(address), value=0)

    bundle = ProposedBundle()
    bundle.add_transaction(txn1)
    bundle.add_transaction(txn2)

    bundle[0]._legacy_tag = Tag(converter.int_to_trytestring(index, 9))

    bundle_logic.finalize(bundle)

    tips = api.get_transactions_to_approve(depth=3)
    trunk = tips['trunkTransaction']
    if reference_transaction:
        branch = reference_transaction[0]
    else:
        branch = tips['branchTransaction']

    bundle_trytes = bundle.as_tryte_strings()
    milestone = api.attach_to_tangle(trunk, branch, bundle_trytes, 9)
    api.broadcast_and_store(milestone['trytes'])

    return milestone
コード例 #21
0
def main():
    # Ensure seed is not displayed in cleartext.
    #seed = get_seed()
    # Create the API instance.
    while(1):
    	api = Iota("http://localhost:14265")

    	#if not seed:
    	#    print('A random seed has been generated. Press return to see it.')
    	#    output_seed(api.seed)

    	#print('Starting transfer.')
    	# For more information, see :py:meth:`Iota.send_transfer`.
    	api.send_transfer(
            depth=3,
            # One or more :py:class:`ProposedTransaction` objects to add to the
            # bundle.
            transfers=[
                ProposedTransaction(
                    # Recipient of the transfer.
                    address=Address("RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999"),

                    # Amount of IOTA to transfer.
                    # By default this is a zero value transfer.
                    value=0,

                    # Optional tag to attach to the transfer.
                    tag=Tag(b'KITTEHS'),

                    # Optional message to include with the transfer.
                    message=TryteString.from_unicode('thx fur cheezburgers'),
                ),
            ],
            min_weight_magnitude=1
        )
コード例 #22
0
ファイル: send_transfer.py プロジェクト: watertim/iota.py
def main(address, depth, message, tag, uri, value):
    # Ensure seed is not displayed in cleartext.
    seed = get_seed()
    # Create the API instance.
    api = Iota(uri, seed)

    if not seed:
        print('A random seed has been generated. Press return to see it.')
        output_seed(api.seed)

    print('Starting transfer.')
    # For more information, see :py:meth:`Iota.send_transfer`.
    api.send_transfer(
        depth=depth,
        # One or more :py:class:`ProposedTransaction` objects to add to the
        # bundle.
        transfers=[
            ProposedTransaction(
                # Recipient of the transfer.
                address=Address(address),

                # Amount of IOTA to transfer.
                # By default this is a zero value transfer.
                value=value,

                # Optional tag to attach to the transfer.
                tag=Tag(tag),

                # Optional message to include with the transfer.
                message=TryteString.from_string(message),
            ),
        ],
    )
    print('Transfer complete.')
コード例 #23
0
 def test_init_error_too_long(self):
     """
 Attempting to create a tag longer than 27 trytes.
 """
     with self.assertRaises(ValueError):
         # 28 chars = no va.
         Tag(b'COLOREDCOINS9999999999999999')
コード例 #24
0
ファイル: sendTX.py プロジェクト: NelsonPython/Air_MacClean
def sendTX(msg):
    '''
    PURPOSE:  send transaction to the Tangle

    INPUT:
        address from a seed different than the one in this script

    OUTPUT:
        TX to devnet
    '''
    seed = 'SEED99999999999999999999999999999999999999999999999999999999999999999999999999999'
    address = 'ADDRESS9FROM9DIFFERENT9SEED999999999999999999999999999999999999999999999999999999'
    api = Iota('https://nodes.devnet.iota.org:443', seed)
    tx = ProposedTransaction(address=Address(address),
                             message=TryteString.from_unicode(msg),
                             tag=Tag('YOURTAG'),
                             value=0)
    try:
        tx = api.prepare_transfer(transfers=[tx])
    except Exception as e:
        print("Check prepare_transfer ", e)
        raise
    try:
        result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9)
    except:
        print("Check send_trytes")
コード例 #25
0
    def __init__(self, address, value, tag=None, message=None, timestamp=None):
        # type: (Address, int, Optional[Tag], Optional[TryteString], Optional[int]) -> None
        if not timestamp:
            timestamp = get_current_timestamp()

        super(ProposedTransaction, self).__init__(
            address=address,
            tag=Tag(b'') if tag is None else tag,
            timestamp=timestamp,
            value=value,

            # These values will be populated when the bundle is finalized.
            bundle_hash=None,
            current_index=None,
            hash_=None,
            last_index=None,
            signature_message_fragment=None,

            # These values start out empty; they will be populated when the
            # node does PoW.
            branch_transaction_hash=TransactionHash(b''),
            nonce=Hash(b''),
            trunk_transaction_hash=TransactionHash(b''),
        )

        self.message = TryteString(b'') if message is None else message
コード例 #26
0
    def test_init_automatic_pad(self):
        """
    Tags are automatically padded to 27 trytes.
    """
        tag = Tag(b'COLOREDCOINS')

        self.assertEqual(binary_type(tag), b'COLOREDCOINS999999999999999')
コード例 #27
0
    def from_tryte_string(cls, trytes):
        # type: (TrytesCompatible) -> Transaction
        """
    Creates a Transaction object from a sequence of trytes.
    """
        tryte_string = TransactionTrytes(trytes)

        hash_ = [0] * HASH_LENGTH  # type: MutableSequence[int]

        sponge = Curl()
        sponge.absorb(tryte_string.as_trits())
        sponge.squeeze(hash_)

        return cls(
            hash_=TransactionHash.from_trits(hash_),
            signature_message_fragment=Fragment(tryte_string[0:2187]),
            address=Address(tryte_string[2187:2268]),
            value=int_from_trits(tryte_string[2268:2295].as_trits()),
            tag=Tag(tryte_string[2295:2322]),
            timestamp=int_from_trits(tryte_string[2322:2331].as_trits()),
            current_index=int_from_trits(tryte_string[2331:2340].as_trits()),
            last_index=int_from_trits(tryte_string[2340:2349].as_trits()),
            bundle_hash=BundleHash(tryte_string[2349:2430]),
            trunk_transaction_hash=TransactionHash(tryte_string[2430:2511]),
            branch_transaction_hash=TransactionHash(tryte_string[2511:2592]),
            nonce=Hash(tryte_string[2592:2673]),
        )
コード例 #28
0
  def test_init_from_tryte_string_error_wrong_subclass(self):
    """
    Initializing a TryteString from a conflicting subclass instance.

    This restriction does not apply when initializing a TryteString
    instance; only subclasses.
    """
    tag = Tag(b'RBTC9D9DCDQAEASBYBCCKBFA')

    with self.assertRaises(TypeError):
      # When initializing a subclassed TryteString, you have to use the
      # same type (or a generic TryteString).
      Address(tag)

    # If you are 110% confident that you know what you are doing, you
    # can force the conversion by casting as a generic TryteString
    # first.
    addy = Address(TryteString(tag))

    self.assertEqual(
      binary_type(addy),

      b'RBTC9D9DCDQAEASBYBCCKBFA9999999999999999'
      b'99999999999999999999999999999999999999999',
    )
コード例 #29
0
def prepare_transaction_arguments(arg_list):
    for key in arg_list:
        if key == 'address':
            arg_list[key] = Address(arg_list[key])
        elif key == 'tag':
            arg_list[key] = Tag(arg_list[key])
        elif key == 'message':
            arg_list[key] = TryteString.from_unicode(arg_list[key])
コード例 #30
0
    def test_anchor_building_blocks(self):
        message = 'Some data proof to lock on the chain'
        self.mock_adapter.seed_response('send_transfer',
                                        response={'message': 'test'})

        address = Address('JUST9A9MOCK9ADDRESS99999999')
        tag = Tag('JUST9A9MOCK9TAG99999999')
        test_client.anchor_building_block(self.api, address, tag, message)
コード例 #31
0
ファイル: creation_test.py プロジェクト: grendias/iota.lib.py
  def test_add_transaction_long_message(self):
    """
    Adding a transaction to a bundle, with a message so long that it
    has to be split into multiple transactions.
    """
    # noinspection SpellCheckingInspection
    address = Address(
      b'TESTVALUE9DONTUSEINPRODUCTION99999N9GIUF'
      b'HCFIUGLBSCKELC9IYENFPHCEWHIDCHCGGEH9OFZBN'
    )

    tag = Tag.from_string('H2G2')

    self.bundle.add_transaction(ProposedTransaction(
      address = address,
      tag     = tag,

      message = TryteString.from_string(
        '''
"Good morning," said Deep Thought at last.
"Er... Good morning, O Deep Thought," said Loonquawl nervously.
  "Do you have... er, that is..."
"... an answer for you?" interrupted Deep Thought majestically. "Yes. I have."
The two men shivered with expectancy. Their waiting had not been in vain.
"There really is one?" breathed Phouchg.
"There really is one," confirmed Deep Thought.
"To Everything? To the great Question of Life, the Universe and Everything?"
"Yes."
Both of the men had been trained for this moment; their lives had been a
  preparation for it; they had been selected at birth as those who would
  witness the answer; but even so they found themselves gasping and squirming
  like excited children.
"And you're ready to give it to us?" urged Loonquawl.
"I am."
"Now?"
"Now," said Deep Thought.
They both licked their dry lips.
"Though I don't think," added Deep Thought, "that you're going to like it."
"Doesn't matter," said Phouchg. "We must know it! Now!"
"Now?" enquired Deep Thought.
"Yes! Now!"
"All right," said the computer and settled into silence again.
  The two men fidgeted. The tension was unbearable.
"You're really not going to like it," observed Deep Thought.
"Tell us!"
"All right," said Deep Thought. "The Answer to the Great Question..."
"Yes?"
"Of Life, the Universe and Everything..." said Deep Thought.
"Yes??"
"Is..."
"Yes?!"
"Forty-two," said Deep Thought, with infinite majesty and calm.
        '''
      ),

      # Now you know....
      # Eh, who am I kidding?  You probably knew before I did (:
      value = 42,
    ))

    # Because the message is too long to fit into a single fragment,
    # the transaction is split into two parts.
    self.assertEqual(len(self.bundle), 2)

    txn1 = self.bundle[0]
    self.assertEqual(txn1.address, address)
    self.assertEqual(txn1.tag, tag)
    self.assertEqual(txn1.value, 42)

    txn2 = self.bundle[1]
    self.assertEqual(txn2.address, address)
    self.assertEqual(txn2.tag, tag)
    # Supplementary transactions are assigned zero IOTA value.
    self.assertEqual(txn2.value, 0)