Beispiel #1
0
def issue_a_milestone_with_reference(step, index):
    """
    This method issues a milestone with a given index and reference transaction. The input transaction pointer should
    always have the key "transactions", but may be a pointer to either a staticValue list stored in staticValues.py, or
    a responseList for "findTransactions".

    :param index: The index of the milestone you are issuing
    """
    node = world.config['nodeId']
    address = static.TEST_BLOWBALL_COO
    api = api_utils.prepare_api_call(node)

    reference_transaction = transactions.fetch_transaction_from_list(
        step.hashes, node)
    logger.info('Issuing milestone {}'.format(index))
    milestone = milestones.issue_milestone(address, api, index,
                                           reference_transaction)

    if 'latestMilestone' not in world.config:
        world.config['latestMilestone'] = {}

    milestone_hash = Transaction.from_tryte_string(milestone['trytes'][0]).hash
    milestone_hash2 = Transaction.from_tryte_string(
        milestone['trytes'][1]).hash
    world.config['latestMilestone'][node] = [milestone_hash, milestone_hash2]
Beispiel #2
0
def update_latest_milestone(config, node, milestone):
    if 'latestMilestone' not in config:
        config['latestMilestone'] = {}

    milestone_hash = Transaction.from_tryte_string(milestone['trytes'][0]).hash
    milestone_hash2 = Transaction.from_tryte_string(milestone['trytes'][1]).hash
    config['latestMilestone'][node] = [milestone_hash, milestone_hash2]
Beispiel #3
0
def track_bundle_loop(hash):
    all_tx = None
    try:
        all_tx = api.find_transactions(addresses=[Address(hash)])
        all_inclusion = api.get_latest_inclusion(all_tx['hashes'])
    except:
        return all_tx, 4
    tx_list = {
        key: val
        for key, val in all_inclusion['states'].items() if val == True
    }

    input = None
    ds = 0
    for tx_hash in tx_list:
        tx = Transaction.from_tryte_string(
            api.get_trytes([tx_hash])['trytes'][0])
        if tx.value < 0:
            input = tx
            ds += 1
            break

    if input is None:
        return hash, 1  #"Address hasn't used yet."
    elif ds > 1:
        return hash, 2  #"Address has been reused twice or more."

    while input.current_index != input.last_index:
        input = Transaction.from_tryte_string(
            api.get_trytes([input.trunk_transaction_hash])['trytes'][0])

    if input.signature_message_fragment != Fragment(b''):
        return input.address, 3  #"Track failed."

    return input.address, 0
Beispiel #4
0
    def get_transactions_from_address(self, address):
        """
        Gets transaction object from address sorted on timestamp (from latest
        to earliest).

        :param address:
           Address to fetch transaction from

        """
        transactions = self._api.find_transactions(addresses=[address])
        transaction_hashes = transactions['hashes']

        if not transaction_hashes:
            raise ValueError("No transactions on address")

        trytes = self._api.get_trytes(transaction_hashes)['trytes']

        trytes_and_hashes = list(zip(trytes, transaction_hashes))

        transactions = list(
            map(lambda pair: Transaction.from_tryte_string(pair[0], pair[1]),
                trytes_and_hashes))

        sorted_transactions = sorted(transactions,
                                     key=lambda t: t.timestamp,
                                     reverse=True)

        return sorted_transactions
Beispiel #5
0
    def test_one_timestamp_invalid(self):
        """
        Test invalid timestamp in one of the transactions.
        """
        # Note that self.trytes2 will have the original and
        # therefore invalid (too old) timestamp
        tx = Transaction.from_tryte_string(self.trytes1)
        tx.attachment_timestamp = get_current_ms()
        self.trytes1 = tx.as_tryte_string()

        self.adapter.seed_response('checkConsistency', {
            'state': True,
        })
        self.adapter.seed_response('getTrytes',
                                   {'trytes': [self.trytes1, self.trytes2]})

        # Here we don`t mock get_current_ms.
        # Tx 1 will have updated, passing timestamp.
        # Tx 2 has the old one, so should fail.
        response = self.command(tails=[self.hash1, self.hash2])

        self.assertDictEqual(
            response, {
                'promotable':
                False,
                'info': [
                    'Transaction {tx_hash} is above max depth.'.format(
                        tx_hash=self.hash2)
                ],
            })
Beispiel #6
0
def issue_multiple_transactions(step, num_transactions, node):
    transactions_to_store = []
    world.responses['evaluate_and_send'] = {}
    world.config['nodeId'] = node
    # Placeholder values for seed if present
    seed_value = ""
    seed_type = ""

    for arg_index, arg in enumerate(step.hashes):
        if arg['keys'] == "seed" and arg['type'] == "staticList":
            seed_value = arg['values']
            seed_type = arg['type']

    for iteration in range(int(num_transactions)):
        seed = ""
        if seed_value != "" and seed_type == "staticList":
            seed = getattr(static, seed_value)[iteration]

        api = api_utils.prepare_api_call(node, seed=seed)

        logger.info('Sending Transaction {}'.format(iteration + 1))
        transaction = transactions.evaluate_and_send(api, seed, step.hashes)
        transaction_hash = Transaction.from_tryte_string(
            transaction.get('trytes')[0]).hash
        transactions_to_store.append(transaction_hash)

    world.responses['evaluate_and_send'][node] = transactions_to_store
    logger.info("Transactions generated and stored")
Beispiel #7
0
 def decodeTryte(self, encoded_text):
     # More Information :: More Information https://pyota.readthedocs.io/en/latest/types.html
     try:
         txn_1 = Transaction.from_tryte_string(encoded_text)
         return {
             "address":
             txn_1.address,
             "value":
             txn_1.value,
             "legacy_tag":
             txn_1.legacy_tag,
             "hash":
             txn_1.hash,
             "timestamp":
             txn_1.timestamp,
             "tag":
             txn_1.tag,
             "current_index":
             txn_1.current_index,
             "last_index":
             txn_1.last_index,
             "bundle_hash":
             txn_1.bundle_hash,
             "trunk_transaction_hash":
             txn_1.trunk_transaction_hash,
             "branch_transaction_hash":
             txn_1.branch_transaction_hash,
             "nonce":
             txn_1.nonce,
             "signature_message_fragment":
             txn_1.signature_message_fragment.decode()
         }
     except (ValueError, TypeError):
         print("Tryte decode has Error")
         return "continue"
Beispiel #8
0
def create_inconsistent_transaction(step, node):
    """
    Creates an inconsistent transaction by generating a zero value transaction that references
    a non-existent transaction as its branch and trunk, thus not connecting with any other part
    of the tangle.

    :param node: The node that the transaction will be generated on.
    """
    world.config['nodeId'] = node
    api = api_utils.prepare_api_call(node)
    trunk = static.NULL_HASH
    branch = trunk
    trytes = static.EMPTY_TRANSACTION_TRYTES

    argument_list = {
        'trunk_transaction': trunk,
        'branch_transaction': branch,
        'trytes': [trytes],
        'min_weight_magnitude': 14
    }

    transaction = transactions.attach_store_and_broadcast(api, argument_list)
    transaction_trytes = transaction.get('trytes')
    transaction_hash = Transaction.from_tryte_string(transaction_trytes[0])

    if 'inconsistentTransactions' not in world.responses:
        world.responses['inconsistentTransactions'] = {}
    world.responses['inconsistentTransactions'][node] = transaction_hash.hash
async def zmq_iota_recv():
    ctx = Context.instance()
    print("Connecting to ZMQ...")
    s = ctx.socket(zmq.SUB)
    s.connect('tcp://%s:%s' % (IOTA_HOST, IOTA_ZMQ_PORT))
    print("Subscribing to tx_trytes...")
    s.subscribe(b"tx_trytes")
    while True:
        msg = await s.recv()
        #print('received', msg)
        topic, data, hash_ = msg.split(b' ')
        str_data = data.decode('ascii')
        str_hash = hash_.decode('ascii')

        tx = Transaction.from_tryte_string(data, hash_)

        print(str(tx.address), connection_addresses.get(str(tx.address), []),
              repr(connection_addresses))
        tasks = [
            send_json(
                subscription.connection, {
                    'id': subscription.id,
                    'type': 'transaction',
                    'data': str_data,
                    'hash': str_hash
                })
            for subscription in connection_addresses.get(str(tx.address), [])
        ]
        if tasks:
            await asyncio.wait(tasks)
    s.close()
    def get_transactions(self, tags, most_recent=True, count=10):
        """Creates Transaction objects from the transaction trytes

        :param tags: List of tags
        :param most_recent: Whether you want returned the most recent transactions
        :param count: Specifies how many transactions you want, 'most_recent' must be true, default is 10
        :return: List of Transaction objects
        """

        # Get transaction hashes from tags
        transactions_hashes = self.api.find_transactions(tags=tags)['hashes']

        # Checks list of transaction hashes is not empty
        if not transactions_hashes:
            print("No Transactions found, waiting for transactions...")
            time.sleep(60)
            self.get_transactions(tags)
        else:

            # The hashes are used to get the raw transaction trytes, which can then be converted to
            # Transaction objects.
            result = self.api.get_trytes(transactions_hashes)
            transaction_trytes = result['trytes']

            # Stores the Transaction objects in a list
            transactions = [Transaction.from_tryte_string(tryte) for tryte in transaction_trytes]

            # Sorts the transactions into order
            ordered_transactions = self.sort_data(transactions, most_recent, count)

            return ordered_transactions
Beispiel #11
0
    def get_transactions_objects(self, hashes):
        transactions = []

        trytes, trytes_status_code = self.get_trytes(hashes)

        if has_network_error(trytes_status_code):
            return None

        if has_all_digits(trytes):
            return list()

        for tryte in trytes:
            transaction = Transaction.from_tryte_string(tryte)

            transactions.append(transaction.as_json_compatible())

        hashes = [tx['hash_'] for tx in transactions]

        inclusion_states, inclusion_states_status_code = self.get_latest_inclusions(
            hashes)

        if has_network_error(inclusion_states_status_code):
            return None

        return transform_with_persistence(transactions, inclusion_states)
Beispiel #12
0
def get_transfers(full_history, print_history=True):
    account_history_executing = True
    api = Iota(iota_node, seed)
    address_count = len(address_data)
    all_txn_hashes = []
    saved_txn_hashes = []
    new_txn_hashes = []
    i = 0

    while i < address_count:
        address = address_data[i]["address"]
        address_as_bytes = [bytes(address)]
        raw_transfers = api.find_transactions(addresses=address_as_bytes)
        transactions_to_check = raw_transfers["hashes"]

        for txn_hash in transactions_to_check:
            txn_hash = str(txn_hash)
            all_txn_hashes.append(txn_hash)
        i += 1

    for txn_hash in transfers_data:
        txn_hash = str(txn_hash['transaction_hash'])
        saved_txn_hashes.append(txn_hash)

    for txn_hash in all_txn_hashes:
        if txn_hash not in saved_txn_hashes:
            new_txn_hashes.append(txn_hash)

    if len(new_txn_hashes) > 0:
        print("Retreaving and saving transfer data from " +
              str(len(new_txn_hashes)) + " transaction(s)!\n"
              "Please wait...\n")
        for txn_hash in new_txn_hashes:
            txn_hash_as_bytes = bytes(txn_hash)
            li_result = api.get_latest_inclusion([
                txn_hash_as_bytes
            ])  # Needs to be integrated into new transactions as well
            is_confirmed = li_result['states'][txn_hash]
            print(li_result)

            gt_result = api.get_trytes([txn_hash_as_bytes])
            trytes = str(gt_result['trytes'][0])
            txn = Transaction.from_tryte_string(trytes)
            timestamp = str(txn.timestamp)
            tag = str(txn.tag)
            address = str(txn.address)
            message = "some message"  # Placeholder untill message decoding is added
            value = str(txn.value)
            bundle = str(txn.bundle_hash)

            write_transfers_data(txn_hash, is_confirmed, timestamp, tag,
                                 address, message, value, bundle)

    if full_history:
        print_transaction_history(full_history, print_history)

    elif not full_history:
        print_transaction_history(full_history, print_history)
Beispiel #13
0
def showConsignment(IOTAAddress=''):
    txcache = {}
    json_data = ''
    json_api = ''
    if not IOTAAddress:
        id, addIndex, consID = readTag()
        IOTAAddress = getAddress(int(addIndex))


#	IOTAAddress = getAddress(9)
    print("loading pickle")
    if os.path.isfile("txcache" + str(IOTAAddress) + ".p"):
        txcache = pickle.load(open("txcache" + str(IOTAAddress) + ".p", "rb"))
    print IOTAAddress
    x = PrettyTable()
    x.field_names = [
        "tagID", "Terminal", "ConsignmentID", "scan_time", "Signatory"
    ]
    result = api.find_transactions(addresses=[IOTAAddress])
    myhashes = result['hashes']
    print("Please wait while retrieving records from the tangle...")
    #	print result
    json_api = []
    for txn_hash in myhashes:
        txn_hash_as_bytes = bytes(txn_hash)
        #		print (txn_hash_as_bytes)
        if not txn_hash_as_bytes in txcache:
            gt_result = api.get_trytes([txn_hash_as_bytes])
            trytes = str(gt_result['trytes'][0])
            txn = Transaction.from_tryte_string(trytes)
            timestamp = txn.timestamp
            scan_time = datetime.fromtimestamp(timestamp).strftime(
                '%Y-%m-%d %H:%M:%S')
            txn_data = str(txn.signature_message_fragment.decode())
            json_data = json.loads(txn_data)
            if not 'Signatory' in json_data:
                json_data['Signatory'] = ''
            json_data['scan_time'] = scan_time
            txcache[txn_hash_as_bytes] = json_data
            pickle.dump(txcache, open("txcache" + str(IOTAAddress) + ".p",
                                      "wb"))
        else:
            json_data = txcache[txn_hash_as_bytes]
        json_api.append(json_data)
        if all(key in json.dumps(json_data)
               for key in ["tagID", "terminal", "consignmentID"]):
            x.add_row([
                json_data['tagID'], json_data['terminal'],
                json_data['consignmentID'], json_data['scan_time'],
                json_data['Signatory']
            ])

    x.sortby = "scan_time"

    print(x)

    pickle.dump(txcache, open("txcache" + str(IOTAAddress) + ".p", "wb"))
    return (json.dumps(json_api))
Beispiel #14
0
def custom_attach(
    trytes: List[TransactionTrytes],
    mwm: int,
):
    """
    Custom attach to to tangle.

    Takes already attached bundle trytes, and except for the the head transaction,
    updates `attachment_timestamp` and re-does the pow, resulting in a new
    nonce and transaction hash.

    The head transaction remains the same as in the original bundle.

    """
    # Install the pow package together with pyota:
    # $ pip install pyota[pow]
    from pow.ccurl_interface import get_powed_tx_trytes, get_hash_trytes, \
        get_current_ms

    previoustx = None

    # Construct bundle object
    bundle = Bundle.from_tryte_strings(trytes)

    # and we need the head tx first
    for txn in reversed(bundle.transactions):
        if (not previoustx):  # this is the head transaction
            # head tx stays the same, it is the original
            previoustx = txn.hash
            continue

        #we only want to mess with tx at index 1
        if txn.current_index != 1:
            continue

        # set any old tx so that this bundles head.trunk != tx
        txn.branch_transaction_hash = 'TBLBTVTHAMPGMGQBUETQSOYHXLCDKSFRTLECTRKSTCHCEHJLCCRPGCUK9VUJNWGQCQNZCUM9IVVIOB999'  # the previous transaction
        txn.attachment_timestamp = get_current_ms()

        # Let's do the pow locally
        txn_string = txn.as_tryte_string().__str__()
        # returns a python unicode string
        powed_txn_string = get_powed_tx_trytes(txn_string, mwm)
        # construct trytestring from python string
        powed_txn_trytes = TryteString(powed_txn_string)
        # compute transaction hash
        hash_string = get_hash_trytes(powed_txn_string)
        hash_trytes = TryteString(hash_string)
        hash_ = TransactionHash(hash_trytes)

        # Create powed txn object
        powed_txn = Transaction.from_tryte_string(trytes=powed_txn_trytes,
                                                  hash_=hash_)

        previoustx = powed_txn.hash
        # put that back in the bundle
        bundle.transactions[txn.current_index] = powed_txn
    return bundle.as_tryte_strings()
Beispiel #15
0
 def get_non_consumed_txns(self, tag):
     txn_hashes_all = self.get_approved_txns(tag)
     txn_trytes_all = self.api.get_trytes(txn_hashes_all)
     txn_hashes_consumed = self.api.find_transactions(
         None, None, [tag + b"CONSUMED"], None)
     txn_trytes_consumed = self.api.get_trytes(
         txn_hashes_consumed['hashes'])
     consumedSet = []
     ret = []
     for txnTrytes in txn_trytes_consumed['trytes']:
         txn = Transaction.from_tryte_string(txnTrytes)
         consumedSet.append(txn.signature_message_fragment)
     for txnTrytes in txn_trytes_all['trytes']:
         txn = Transaction.from_tryte_string(txnTrytes)
         if txn.signature_message_fragment not in consumedSet:
             msgTryte = txn.signature_message_fragment.decode()
             ret.append(msgTryte)
     return ret
Beispiel #16
0
    async def _traverse_bundle(
            self, txn_hash: TransactionHash,
            target_bundle_hash: Optional[TransactionHash]
    ) -> List[Transaction]:
        """
        Recursively traverse the Tangle, collecting transactions until
        we hit a new bundle.

        This method is (usually) faster than ``findTransactions``, and
        it ensures we don't collect transactions from replayed bundles.
        """
        trytes: List[TryteString] = (await GetTrytesCommand(self.adapter)
                                     (hashes=[txn_hash]))['trytes']

        # If no tx was found by the node for txn_hash, it returns 9s,
        # so we check here if it returned all 9s trytes.
        if not trytes or trytes == [TransactionTrytes('')]:
            raise with_context(
                exc=BadApiResponse(
                    'Could not get trytes of bundle transaction from the Tangle. '
                    'Bundle transactions not visible.'
                    '(``exc.context`` has more info).', ),
                context={
                    'transaction_hash': txn_hash,
                    'target_bundle_hash': target_bundle_hash,
                },
            )

        transaction = Transaction.from_tryte_string(trytes[0])

        if (not target_bundle_hash) and transaction.current_index:
            raise with_context(
                exc=BadApiResponse(
                    '``_traverse_bundle`` started with a non-tail transaction '
                    '(``exc.context`` has more info).', ),
                context={
                    'transaction_object': transaction,
                    'target_bundle_hash': target_bundle_hash,
                },
            )

        if target_bundle_hash:
            if target_bundle_hash != transaction.bundle_hash:
                # We've hit a different bundle; we can stop now.
                return []
        else:
            target_bundle_hash = transaction.bundle_hash

        if transaction.current_index == transaction.last_index == 0:
            # Bundle only has one transaction.
            return [transaction]

        # Recursively follow the trunk transaction, to fetch the next
        # transaction in the bundle.
        return [transaction] + await self._traverse_bundle(
            transaction.trunk_transaction_hash, target_bundle_hash)
Beispiel #17
0
  def _traverse_bundle(self, txn_hash, target_bundle_hash=None):
    # type: (TransactionHash, Optional[BundleHash]) -> List[Transaction]
    """
    Recursively traverse the Tangle, collecting transactions until we
    hit a new bundle.

    This method is (usually) faster than ``findTransactions``, and it
    ensures we don't collect transactions from replayed bundles.
    """
    trytes = GetTrytesCommand(self.adapter)(hashes=[txn_hash])['trytes'] # type: List[TryteString]

    if not trytes:
      raise with_context(
        exc = BadApiResponse(
          'Bundle transactions not visible (``exc.context`` has more info).',
        ),

        context = {
          'transaction_hash':   txn_hash,
          'target_bundle_hash': target_bundle_hash,
        },
      )

    transaction = Transaction.from_tryte_string(trytes[0])

    if (not target_bundle_hash) and transaction.current_index:
      raise with_context(
        exc = BadApiResponse(
          '``_traverse_bundle`` started with a non-tail transaction '
          '(``exc.context`` has more info).',
        ),

        context = {
          'transaction_object': transaction,
          'target_bundle_hash': target_bundle_hash,
        },
      )

    if target_bundle_hash:
      if target_bundle_hash != transaction.bundle_hash:
        # We've hit a different bundle; we can stop now.
        return []
    else:
      target_bundle_hash = transaction.bundle_hash

    if transaction.current_index == transaction.last_index == 0:
      # Bundle only has one transaction.
      return [transaction]

    # Recursively follow the trunk transaction, to fetch the next
    # transaction in the bundle.
    return [transaction] + self._traverse_bundle(
      txn_hash            = transaction.trunk_transaction_hash,
      target_bundle_hash  = target_bundle_hash
    )
Beispiel #18
0
  def _traverse_bundle(self, txn_hash, target_bundle_hash=None):
    # type: (TransactionHash, Optional[BundleHash]) -> List[Transaction]
    """
    Recursively traverse the Tangle, collecting transactions until we
    hit a new bundle.

    This method is (usually) faster than ``findTransactions``, and it
    ensures we don't collect transactions from replayed bundles.
    """
    trytes = GetTrytesCommand(self.adapter)(hashes=[txn_hash])['trytes'] # type: List[TryteString]

    if not trytes:
      raise with_context(
        exc = BadApiResponse(
          'Bundle transactions not visible (``exc.context`` has more info).',
        ),

        context = {
          'transaction_hash':   txn_hash,
          'target_bundle_hash': target_bundle_hash,
        },
      )

    transaction = Transaction.from_tryte_string(trytes[0])

    if (not target_bundle_hash) and transaction.current_index:
      raise with_context(
        exc = BadApiResponse(
          '``_traverse_bundle`` started with a non-tail transaction '
          '(``exc.context`` has more info).',
        ),

        context = {
          'transaction_object': transaction,
          'target_bundle_hash': target_bundle_hash,
        },
      )

    if target_bundle_hash:
      if target_bundle_hash != transaction.bundle_hash:
        # We've hit a different bundle; we can stop now.
        return []
    else:
      target_bundle_hash = transaction.bundle_hash

    if transaction.current_index == transaction.last_index == 0:
      # Bundle only has one transaction.
      return [transaction]

    # Recursively follow the trunk transaction, to fetch the next
    # transaction in the bundle.
    return [transaction] + self._traverse_bundle(
      txn_hash            = transaction.trunk_transaction_hash,
      target_bundle_hash  = target_bundle_hash
    )
Beispiel #19
0
def run(address, hostname, port):

    dataset = {}

    print 'Using IOTA light node %s:%s' % (hostname, port)
    print 'Finding transactions from address %s' % address

    command = {
        'command': 'findTransactions',
        'addresses': [address[:-9]]
    }

    stringified = json.dumps(command)

    request = urllib2.Request(url="%s:%s" % (hostname, port), data=stringified, headers=headers)
    returnData = urllib2.urlopen(request).read()
    jsonData = json.loads(returnData)
    if 'hashes' in jsonData:

        print 'Transactions found, retrieving last 10...'

        command = {
            'command': 'getTrytes',
            'hashes': jsonData['hashes'][-10:]
        }

        stringified = json.dumps(command)

        request = urllib2.Request(url="%s:%s" % (hostname, port), data=stringified, headers=headers)
        returnData = urllib2.urlopen(request).read()
        jsonData = json.loads(returnData)
        tx_count = 1
        if 'trytes' in jsonData:
            num_tx = len(jsonData['trytes'])
            for tryte in jsonData['trytes']:
                tx = Transaction.from_tryte_string(tryte)
                enc_message = TryteString(tx.signature_message_fragment)
                epoch = datetime.datetime.fromtimestamp(float(tx.attachment_timestamp)/1000.)
                fmt = "%Y-%m-%d %H:%M:%S"
                timestamp = epoch.strftime(fmt)
                try:
                    data = json.loads(enc_message.decode())
                except ValueError:
                    # Decoding seems to blow up every so often.
                    pass
                # These are specific to my mqtt data stream, need to make this more flexible.
                if 'topic' in data and 'mcutemp' in data:
                    dataset[timestamp] = {'device': data['topic'], 'temp': data['mcutemp'], 'tx': tx.hash}
                    print 'Fetching transaction %s of %s ...' % (tx_count, num_tx)
                    tx_count += 1
        sorted_data = OrderedDict(sorted(dataset.items(), key=lambda x: parse(x[0])))
        for value in sorted(sorted_data.keys(), reverse=True):
            print '%s %s' % (value, sorted_data[value])
Beispiel #20
0
def issue_a_milestone(step, index, node):
    """
    This method issues a milestone with a given index.

    :param index: The index of the milestone you are issuing
    :param node: The node that the milestone will be attached to
    """
    world.config['nodeId'] = node
    address = static.TEST_BLOWBALL_COO
    api = api_utils.prepare_api_call(node)

    logger.info('Issuing milestone {}'.format(index))
    milestone = milestones.issue_milestone(address, api, index)

    if 'latestMilestone' not in world.config:
        world.config['latestMilestone'] = {}

    milestone_hash = Transaction.from_tryte_string(milestone['trytes'][0]).hash
    milestone_hash2 = Transaction.from_tryte_string(
        milestone['trytes'][1]).hash
    world.config['latestMilestone'][node] = [milestone_hash, milestone_hash2]
Beispiel #21
0
 def cache_txn_in_tangle_simple(self, data, tag):
     address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX"
     txns = self.api.get_transactions_to_approve(self.depth)
     tr = self.api.get_trytes([txns[u'branchTransaction']])
     txn = Transaction.from_tryte_string(tr[u'trytes'][0], txns[u'branchTransaction'])
     txn.trunk_transaction_hash = txns[u'trunkTransaction']
     txn.branch_transaction_hash = txns[u'branchTransaction']
     txn.tag = Tag(TryteString.from_string(tag))
     txn.signature_message_fragment = Fragment(TryteString.from_bytes(data))
     attach_trytes = attachToTangle(self.uri, txns[u'trunkTransaction'].__str__(), txns[u'branchTransaction'].__str__(), 1, txn.as_tryte_string().__str__())
     res = self.api.broadcast_and_store(attach_trytes[u'trytes'])
     return res
Beispiel #22
0
  def test_from_tryte_string_with_hash(self):
    """
    Initializing a Transaction object from a TryteString, with a
    pre-computed hash.
    """
    txn_hash =\
      TransactionHash(
        b'TESTVALUE9DONTUSEINPRODUCTION99999VALCXC'
        b'DHTDZBVCAAIEZCQCXGEFYBXHNDJFZEBEVELA9HHEJ'
      )

    txn = Transaction.from_tryte_string(b'', hash_=txn_hash)

    self.assertEqual(txn.hash, txn_hash)
Beispiel #23
0
  def test_from_tryte_string_with_hash(self):
    """
    Initializing a Transaction object from a TryteString, with a
    pre-computed hash.
    """
    # noinspection SpellCheckingInspection
    txn_hash =\
      TransactionHash(
        b'TESTVALUE9DONTUSEINPRODUCTION99999VALCXC'
        b'DHTDZBVCAAIEZCQCXGEFYBXHNDJFZEBEVELA9HHEJ'
      )

    txn = Transaction.from_tryte_string(b'', hash_=txn_hash)

    self.assertEqual(txn.hash, txn_hash)
Beispiel #24
0
def create_inconsistent_transaction(step, node):
    world.config['nodeId'] = node
    api = api_utils.prepare_api_call(node)
    branch = getattr(static_vals, "NULL_HASH")
    trunk = branch
    trytes = getattr(static_vals, "EMPTY_TRANSACTION_TRYTES")

    transaction = api.attach_to_tangle(trunk, branch, [trytes], 14)
    transaction_trytes = transaction.get('trytes')
    api.store_transactions(transaction_trytes)
    transaction_hash = Transaction.from_tryte_string(transaction_trytes[0])
    logger.info(transaction_hash.hash)

    if 'inconsistentTransactions' not in world.responses:
        world.responses['inconsistentTransactions'] = {}

    world.responses['inconsistentTransactions'][node] = transaction_hash.hash
Beispiel #25
0
    def get_transfers(self):
        """
        Get transactions

        :return:
        """
        api = Iota(current_app.config['IOTA_HOST'], self.seed)
        result = []

        for a in self.addresses:
            t = api.find_transactions(addresses=[a.address])
            for th in t['hashes']:
                gt = api.get_trytes([th])
                txn = Transaction.from_tryte_string(gt['trytes'][0])
                result.append(txn)

        return result
Beispiel #26
0
def get_txn_msg(data):
    message = ""
    list_txn = []

    try:
        list_txn = api.get_trytes([data])
    except BaseException:
        return ""

    trytes_txn = str(list_txn['trytes'][0])
    txn = Transaction.from_tryte_string(trytes_txn)

    try:
        message = TryteString(txn.signature_message_fragment).decode()
    except BaseException:
        return ""

    return message
Beispiel #27
0
def waiting_for_payment(address_with_checksum, price_total):
    waiting = True
    while waiting == True:
        time.sleep(2)
        global node
        api = Iota(node)
        find_transaction = api.findTransactions(
            addresses=[bytes(address_with_checksum)])

        try:
            hash_as_bytes = str(bytes(find_transaction["hashes"][0]))
            trytes_call = api.get_trytes([hash_as_bytes])
            trytes = trytes_call['trytes'][0]
            txn = Transaction.from_tryte_string(trytes)
            if txn.value >= price_total:
                waiting = False
        except:
            print("Waiting..")
    os.system('cls' if os.name == 'nt' else 'clear')
    return True
    def _find_transaction(self, tag=MTRAFFIC_REG_TAG):
        try:
            response = self.api.find_transactions(tags=[get_tags(tag)])
        except ConnectionError as e:
            logger.exception("Connection error: {e}".format(e=e))
        except BadApiResponse as e:
            logger.exception("Bad Api Response: {e}".format(e=e))
        else:
            if len(response["hashes"]) < 1:
                return []
            trytes = self.api.get_trytes(response["hashes"])
            transactions = []
            for trytestring in trytes["trytes"]:
                tx = Transaction.from_tryte_string(trytestring)
                transactions.append(tx)

            return [
                json.loads(tx.signature_message_fragment.as_string())
                for tx in transactions
            ]
Beispiel #29
0
def retry_bundle(hash):
    tryte = api.get_trytes(hashes=[hash])['trytes'][0]
    tx = Transaction.from_tryte_string(tryte)

    charRe = re.compile(r'[^9.]')
    if charRe.search(str(tx.hash)) and tx.current_index == 0:
        if api.get_latest_inclusion([tx.hash])['states'][tx.hash]:
            return "Transaction is already confirmed."
        elif (round(time.time()) - tx.timestamp) < 300:
            try:
                result = api.promote_transaction(transaction=hash, depth=DEPTH)
                return "Transaction is promoted."
            except:
                result = api.replay_bundle(transaction=hash, depth=DEPTH)
                return "Transaction is reattached."
        else:
            result = api.replay_bundle(transaction=hash, depth=DEPTH)
            return "Transaction is reattached."
    else:
        return "Invalid transaction provided."
    def getTransactions(self, hashes):
        txn = []
        command = {"command": "getTrytes", "hashes": hashes["hashes"]}

        stringified = json.dumps(command)

        headers = {
            "content-type": "application/json",
            "X-IOTA-API-Version": "1"
        }

        request = urllib.request.Request(url=self.host_ip,
                                         data=stringified.encode("utf-8"),
                                         headers=headers)
        returnData = urllib.request.urlopen(request).read()

        jsonData = json.loads(returnData)
        for dat in jsonData["trytes"]:
            txn.append(Transaction.from_tryte_string(dat.encode("utf-8")))
        return txn
Beispiel #31
0
def find_transaction_message(hash_txn):
    # Iota instance
    api = Iota(NODE_URL)

    message = ""
    list_txn = []

    try:
        list_txn = api.get_trytes([hash_txn])
    except BaseException:
        return ""

    trytes_txn = str(list_txn['trytes'][0])
    txn = Transaction.from_tryte_string(trytes_txn)

    try:
        message = TryteString(txn.signature_message_fragment).decode()
    except BaseException:
        return ""

    return message
Beispiel #32
0
    def fetch_data_from_tangle(self, msg_id):
        txns = self._iota_obj.find_transactions(
            tags=[Tag(TryteString.from_unicode(msg_id))])
        _trytes = self._iota_obj.get_trytes(txns['hashes']).get('trytes', [])
        _values = []
        for _t in _trytes:
            _txn = Transaction.from_tryte_string(_t)
            _value = json.loads(_txn.signature_message_fragment.decode())
            _msg_value = _value.get('data', None)
            _msg_topic = _value.get('topic', None)
            _time = _txn.timestamp
            print('Message ID : %s, Message Topic: %s, Value found : %s' \
                  %(msg_id, _msg_topic, _msg_value,))

            if self._push_data:
                # TBD : Push back to MQTT
                pass

            _tmp = (_msg_topic, _msg_value, _time)
            _values.append(_tmp)
        return _values
Beispiel #33
0
  def test_from_tryte_string(self):
    """
    Initializing a Transaction object from a TryteString.

    References:
      - http://iotasupport.com/news/index.php/2016/12/02/fixing-the-latest-solid-subtangle-milestone-issue/
    """
    trytes =\
      TransactionTrytes(
        b'GYPRVHBEZOOFXSHQBLCYW9ICTCISLHDBNMMVYD9JJHQMPQCTIQAQTJNNNJ9IDXLRCC'
        b'OYOXYPCLR9PBEY9ORZIEPPDNTI9CQWYZUOTAVBXPSBOFEQAPFLWXSWUIUSJMSJIIIZ'
        b'WIKIRH9GCOEVZFKNXEVCUCIIWZQCQEUVRZOCMEL9AMGXJNMLJCIA9UWGRPPHCEOPTS'
        b'VPKPPPCMQXYBHMSODTWUOABPKWFFFQJHCBVYXLHEWPD9YUDFTGNCYAKQKVEZYRBQRB'
        b'XIAUX9SVEDUKGMTWQIYXRGSWYRK9SRONVGTW9YGHSZRIXWGPCCUCDRMAXBPDFVHSRY'
        b'WHGB9DQSQFQKSNICGPIPTRZINYRXQAFSWSEWIFRMSBMGTNYPRWFSOIIWWT9IDSELM9'
        b'JUOOWFNCCSHUSMGNROBFJX9JQ9XT9PKEGQYQAWAFPRVRRVQPUQBHLSNTEFCDKBWRCD'
        b'X9EYOBB9KPMTLNNQLADBDLZPRVBCKVCYQEOLARJYAGTBFR9QLPKZBOYWZQOVKCVYRG'
        b'YI9ZEFIQRKYXLJBZJDBJDJVQZCGYQMROVHNDBLGNLQODPUXFNTADDVYNZJUVPGB9LV'
        b'PJIYLAPBOEHPMRWUIAJXVQOEM9ROEYUOTNLXVVQEYRQWDTQGDLEYFIYNDPRAIXOZEB'
        b'CS9P99AZTQQLKEILEVXMSHBIDHLXKUOMMNFKPYHONKEYDCHMUNTTNRYVMMEYHPGASP'
        b'ZXASKRUPWQSHDMU9VPS99ZZ9SJJYFUJFFMFORBYDILBXCAVJDPDFHTTTIYOVGLRDYR'
        b'TKHXJORJVYRPTDH9ZCPZ9ZADXZFRSFPIQKWLBRNTWJHXTOAUOL9FVGTUMMPYGYICJD'
        b'XMOESEVDJWLMCVTJLPIEKBE9JTHDQWV9MRMEWFLPWGJFLUXI9BXPSVWCMUWLZSEWHB'
        b'DZKXOLYNOZAPOYLQVZAQMOHGTTQEUAOVKVRRGAHNGPUEKHFVPVCOYSJAWHZU9DRROH'
        b'BETBAFTATVAUGOEGCAYUXACLSSHHVYDHMDGJP9AUCLWLNTFEVGQGHQXSKEMVOVSKQE'
        b'EWHWZUDTYOBGCURRZSJZLFVQQAAYQO9TRLFFN9HTDQXBSPPJYXMNGLLBHOMNVXNOWE'
        b'IDMJVCLLDFHBDONQJCJVLBLCSMDOUQCKKCQJMGTSTHBXPXAMLMSXRIPUBMBAWBFNLH'
        b'LUJTRJLDERLZFUBUSMF999XNHLEEXEENQJNOFFPNPQ9PQICHSATPLZVMVIWLRTKYPI'
        b'XNFGYWOJSQDAXGFHKZPFLPXQEHCYEAGTIWIJEZTAVLNUMAFWGGLXMBNUQTOFCNLJTC'
        b'DMWVVZGVBSEBCPFSM99FLOIDTCLUGPSEDLOKZUAEVBLWNMODGZBWOVQT9DPFOTSKRA'
        b'BQAVOQ9RXWBMAKFYNDCZOJGTCIDMQSQQSODKDXTPFLNOKSIZEOY9HFUTLQRXQMEPGO'
        b'XQGLLPNSXAUCYPGZMNWMQWSWCKAQYKXJTWINSGPPZG9HLDLEAWUWEVCTVRCBDFOXKU'
        b'ROXH9HXXAXVPEJFRSLOGRVGYZASTEBAQNXJJROCYRTDPYFUIQJVDHAKEG9YACV9HCP'
        b'JUEUKOYFNWDXCCJBIFQKYOXGRDHVTHEQUMHO999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999RKWEEVD99A99999999A99999999NFDPEEZCWVYLKZGSLCQNOFUSENI'
        b'XRHWWTZFBXMPSQHEDFWZULBZFEOMNLRNIDQKDNNIELAOXOVMYEI9PGTKORV9IKTJZQ'
        b'UBQAWTKBKZ9NEZHBFIMCLV9TTNJNQZUIJDFPTTCTKBJRHAITVSKUCUEMD9M9SQJ999'
        b'999TKORV9IKTJZQUBQAWTKBKZ9NEZHBFIMCLV9TTNJNQZUIJDFPTTCTKBJRHAITVSK'
        b'UCUEMD9M9SQJ999999999999999999999999999999999RKWEEVD99RKWEEVD99RKW'
        b'EEVD99999999999999999999999999999'
      )

    transaction = Transaction.from_tryte_string(trytes)

    self.assertIsInstance(transaction, Transaction)

    self.assertEqual(
      transaction.hash,

      Hash(
        b'JBVVEWEPYNZ9KRHNUUTRENXXAVXT9MKAVPAUQ9SJ'
        b'NSIHDCPQM9LJHIZGXO9PIRWUUVBOXNCBE9XJGMOZF'
      ),
    )

    self.assertEqual(
      transaction.signature_message_fragment,

      Fragment(
        b'GYPRVHBEZOOFXSHQBLCYW9ICTCISLHDBNMMVYD9JJHQMPQCTIQAQTJNNNJ9IDXLRCC'
        b'OYOXYPCLR9PBEY9ORZIEPPDNTI9CQWYZUOTAVBXPSBOFEQAPFLWXSWUIUSJMSJIIIZ'
        b'WIKIRH9GCOEVZFKNXEVCUCIIWZQCQEUVRZOCMEL9AMGXJNMLJCIA9UWGRPPHCEOPTS'
        b'VPKPPPCMQXYBHMSODTWUOABPKWFFFQJHCBVYXLHEWPD9YUDFTGNCYAKQKVEZYRBQRB'
        b'XIAUX9SVEDUKGMTWQIYXRGSWYRK9SRONVGTW9YGHSZRIXWGPCCUCDRMAXBPDFVHSRY'
        b'WHGB9DQSQFQKSNICGPIPTRZINYRXQAFSWSEWIFRMSBMGTNYPRWFSOIIWWT9IDSELM9'
        b'JUOOWFNCCSHUSMGNROBFJX9JQ9XT9PKEGQYQAWAFPRVRRVQPUQBHLSNTEFCDKBWRCD'
        b'X9EYOBB9KPMTLNNQLADBDLZPRVBCKVCYQEOLARJYAGTBFR9QLPKZBOYWZQOVKCVYRG'
        b'YI9ZEFIQRKYXLJBZJDBJDJVQZCGYQMROVHNDBLGNLQODPUXFNTADDVYNZJUVPGB9LV'
        b'PJIYLAPBOEHPMRWUIAJXVQOEM9ROEYUOTNLXVVQEYRQWDTQGDLEYFIYNDPRAIXOZEB'
        b'CS9P99AZTQQLKEILEVXMSHBIDHLXKUOMMNFKPYHONKEYDCHMUNTTNRYVMMEYHPGASP'
        b'ZXASKRUPWQSHDMU9VPS99ZZ9SJJYFUJFFMFORBYDILBXCAVJDPDFHTTTIYOVGLRDYR'
        b'TKHXJORJVYRPTDH9ZCPZ9ZADXZFRSFPIQKWLBRNTWJHXTOAUOL9FVGTUMMPYGYICJD'
        b'XMOESEVDJWLMCVTJLPIEKBE9JTHDQWV9MRMEWFLPWGJFLUXI9BXPSVWCMUWLZSEWHB'
        b'DZKXOLYNOZAPOYLQVZAQMOHGTTQEUAOVKVRRGAHNGPUEKHFVPVCOYSJAWHZU9DRROH'
        b'BETBAFTATVAUGOEGCAYUXACLSSHHVYDHMDGJP9AUCLWLNTFEVGQGHQXSKEMVOVSKQE'
        b'EWHWZUDTYOBGCURRZSJZLFVQQAAYQO9TRLFFN9HTDQXBSPPJYXMNGLLBHOMNVXNOWE'
        b'IDMJVCLLDFHBDONQJCJVLBLCSMDOUQCKKCQJMGTSTHBXPXAMLMSXRIPUBMBAWBFNLH'
        b'LUJTRJLDERLZFUBUSMF999XNHLEEXEENQJNOFFPNPQ9PQICHSATPLZVMVIWLRTKYPI'
        b'XNFGYWOJSQDAXGFHKZPFLPXQEHCYEAGTIWIJEZTAVLNUMAFWGGLXMBNUQTOFCNLJTC'
        b'DMWVVZGVBSEBCPFSM99FLOIDTCLUGPSEDLOKZUAEVBLWNMODGZBWOVQT9DPFOTSKRA'
        b'BQAVOQ9RXWBMAKFYNDCZOJGTCIDMQSQQSODKDXTPFLNOKSIZEOY9HFUTLQRXQMEPGO'
        b'XQGLLPNSXAUCYPGZMNWMQWSWCKAQYKXJTWINSGPPZG9HLDLEAWUWEVCTVRCBDFOXKU'
        b'ROXH9HXXAXVPEJFRSLOGRVGYZASTEBAQNXJJROCYRTDPYFUIQJVDHAKEG9YACV9HCP'
        b'JUEUKOYFNWDXCCJBIFQKYOXGRDHVTHEQUMHO999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999999999999999999999999999999999999999999999999999999999999'
        b'999999999'
      ),
    )

    self.assertEqual(
      transaction.address,

      Address(
        b'9999999999999999999999999999999999999999'
        b'99999999999999999999999999999999999999999'
      ),
    )

    self.assertEqual(transaction.value, 0)
    self.assertEqual(transaction.legacy_tag, Tag(b'999999999999999999999999999'))
    self.assertEqual(transaction.timestamp, 1480690413)
    self.assertEqual(transaction.current_index, 1)
    self.assertEqual(transaction.last_index, 1)

    self.assertEqual(
      transaction.bundle_hash,

      BundleHash(
        b'NFDPEEZCWVYLKZGSLCQNOFUSENIXRHWWTZFBXMPS'
        b'QHEDFWZULBZFEOMNLRNIDQKDNNIELAOXOVMYEI9PG'
      ),
    )

    self.assertEqual(
      transaction.trunk_transaction_hash,

      TransactionHash(
        b'TKORV9IKTJZQUBQAWTKBKZ9NEZHBFIMCLV9TTNJN'
        b'QZUIJDFPTTCTKBJRHAITVSKUCUEMD9M9SQJ999999'
      ),
    )

    self.assertEqual(
      transaction.branch_transaction_hash,

      TransactionHash(
        b'TKORV9IKTJZQUBQAWTKBKZ9NEZHBFIMCLV9TTNJN'
        b'QZUIJDFPTTCTKBJRHAITVSKUCUEMD9M9SQJ999999'
      ),
    )
    
    self.assertEqual(transaction.tag, Tag(b'999999999999999999999999999'))
    self.assertEqual(transaction.attachment_timestamp,1480690413)
    self.assertEqual(transaction.attachment_timestamp_lower_bound,1480690413)
    self.assertEqual(transaction.attachment_timestamp_upper_bound,1480690413)

    self.assertEqual(
      transaction.nonce,

      Nonce(
        b'999999999999999999999999999'
      ),
    )
  def test_get_inclusion_states(self):
    """
    Fetching inclusion states with transactions.
    """
    # noinspection PyUnusedLocal
    def create_generator(ag, start, step=1):
      for addy in [self.addy1][start::step]:
        yield addy

    # The first address received IOTA.
    self.adapter.seed_response(
      'findTransactions',

      {
        'duration': 42,

        'hashes': [
          'TESTVALUEFIVE9DONTUSEINPRODUCTION99999VH'
          'YHRHJETGYCAFZGABTEUBWCWAS9WF99UHBHRHLIOFJ',
        ],
      },
    )

    # For this test, we have to generate a real TryteString.
    transaction_trytes =\
      TryteString(
        b'KMYUMNEUAYODAQSNGWTAERRRHNZBZCOLMVVOBTVWLOFYCJKYMGRAMH9RQ9MTZOSZMH'
        b'QNZFHFEJEDFQ99HSUNVOTULDJGXEDULS9ZHABVDZODJUMCNWVCPNSCUVKVYWCEXBHW'
        b'RBZBSWFPQLWZWMUPGQIGAEGOVE9DDXBVCIPKQYCFZFBELTSMVFSIXLPTACTKAFMCTK'
        b'CPYD9BWDJMLKWAOBDSJNQYAHS9GFIQKZCROLFZJVUEIVXVNBRRLEIWTYVHURUXHSCG'
        b'DKEIEGPOCXKCYWIBUG9ABYCALYJVFLBNGMS9ARHGTQXBZFLENXCJVKHPVKD9KSAEOL'
        b'FFVAJCNKLDVHOCDARWUNKARDYMVKFKRSMUTYOUXSBFFYTKRREBDJZTLVUROQFCBXQN'
        b'SXDDYTZTEBRSXOBMLXHJKSJAVOOVCXATOWNQDWHT9CCUAAJUJKDOQLMAEZACSNFKXZ'
        b'IGWDQEUEFRZYAOSDNVMSXWYLVDAUXZSHNHAIBEMNPFUGORYUETNJK9UCEMSUJYBBDK'
        b'BHIPKEINQCGOVYCPKUPJMUCUVZOJSIWYRFMFXYUVSMOUALAQBWIMXBUBXSAETGKJRP'
        b'AHVAXHQJDMEVSRFYEXUSIEBKMGYCUKFD9JPGUV9AIYUVCRUURKMYUHMVE9OJCYYWTQ'
        b'WUWFMTBZYFXASHHVCMSWXKBRQFHHQVEQMEULJRWZKLWFFSGGKEHUZZFNDNITSRAUH9'
        b'PQK9OGLYMVBSHXQLLZHOBBIM9KVUWDLHZRDKQQVLQXGWYXEEVQPDZUO9PVXMALOMRQ'
        b'VCTHGIZLILSCFKTBRESYZGBZKHXEODNDJZ9GK9ROWYXNGFHZCCBHHZEYEOGWXRGSUD'
        b'SUZFUAUBXVXZHCUVJSYBWTCYCEDYKZNGWFZYKSQLW9FUYMWDVXKZEWT9SCVMQCODZK'
        b'DRNKTINTPNOJOLGQJDAJMFWRFSWZJLYZGSTSIDSXLUJBZRZNLEDNBKAUNGTCYUPDRW'
        b'JOCEBQ9YG9IZLLRMJITISJOTLQMOGXVQIZXHMTJVMMWM9FOIOT9KFZMANEPOEOV9HX'
        b'JNEGURUKRWDGYNPVGAWMWQVABIJNL9MDXKONEPMYACOZ9BE9UZMAFTKYWPFWIQWAPK'
        b'GUXQTOQVWYYVZYGQDLBIQDVOZIWGOMGOBAUARICQZVNXD9UVEFBBAJKQBHRHXTBUOW'
        b'VBFKYQWZWTMMXVKZRIZUBVPQ9XHLJHFHWFZUIZVSNAKBDHDFGJCYQETOMEDTOXIUT9'
        b'OAJVIHWAGTCNPEZTERMMN9EZEWSJHKQAUMXPBZTNQOEQCVXIMAAYO9NIUFLTCFIMK9'
        b'9AFAGWJFA9VOFPUDJLRAMORGSUDBLWWKXEDZ9XPQUZSGANGESHKKGGQSGSYDCRLHZD'
        b'PKA9HKYBKLKKCXYRQQIPXCFETJJDZYPCLUNHGBKEJDRCIHEXKCQQNOV9QFHLGFXOCR'
        b'HPAFCUTPMY9NOZVQHROYJSCMGRSVMOBWADAZNFIAHWGIQUUZBOVODSFAUNRTXSDU9W'
        b'EIRBXQNRSJXFRAQGHA9DYOQJGLVZUJKAQ9CTUOTT9ZKQOQNNLJDUPDXZJYPRCVLRZT'
        b'UCZPNBREYCCKHK9FUWGITAJATFPUOFLZDHPNJYUTXFGNYJOBRD9BVHKZENFXIUYDTL'
        b'CE9JYIIYMXMCXMWTHOLTQFKFHDLVPGMQNITEUXSYLAQULCZOJVBIPYP9M9X9QCNKBX'
        b'W9DVJEQFFY9KQVMKNVTAHQVRXUKEM9FZOJLHAGEECZBUHOQFZOSPRXKZOCCKAOHMSV'
        b'QCFG9CWAHKVWNA9QTLYQI9NKOSHWJCNGPJBLEQPUIWJBIOAWKLBXUCERTSL9FVCLYN'
        b'ADPYTPKJOIEMAQGWBVGSRCZINXEJODUDCT9FHOUMQM9ZHRMBJYSOMPNMEAJGEHICJI'
        b'PVXRKCYX9RZVT9TDZIMXGZJAIYJRGIVMSOICSUINRBQILMJOUQYXCYNJ9WGGJFHYTU'
        b'LWOIPUXXFNTIFNOJRZFSQQNAWBQZOLHHLVGHEPWTKKQEVIPVWZUN9ZBICZ9DZZBVII'
        b'BF9EPHARZJUFJGBQXQFQIBUECAWRSEKYJNYKNSVBCOWTFBZ9NAHFSAMRBPEYGPRGKW'
        b'WTWACZOAPEOECUO9OTMGABJVAIICIPXGSXACVINSYEQFTRCQPCEJXZCY9XZWVWVJRZ'
        b'CYEYNFUUBKPWCHICGJZXKE9GSUDXZYUAPLHAKAHYHDXNPHENTERYMMBQOPSQIDENXK'
        b'LKCEYCPVTZQLEEJVYJZV9BWU999999999999999999999999999FFL999999999999'
        b'9999999999999RJQGVD99999999999A99999999USGBXHGJUEWAUAKNPPRHJXDDMQV'
        b'YDSYZJSDWFYLOQVFGBOSLE9KHFDLDYHUYTXVSFAFCOCLQUHJXTEIQRNBTLHEGJFGVF'
        b'DJCE9IKAOCSYHLCLWPVVNWNESKLYAJG9FGGZOFXCEYOTWLVIJUHGY9QCU9FMZJY999'
        b'9999HYBUYQKKRNAVDPVGYBTVDZ9SVQBLCCVLJTPEQWWOIG9CQZIFQKCROH9YHUCNJT'
        b'SYPBVZVBNESX999999D9TARGPQTNIYRZURQGVHCAWEDRBJIIEJIUZYENVE9LLJQMXH'
        b'GSUUYUCPSOWBCXVFDCHHAZUDC9LUODYWO'
      )

    self.adapter.seed_response(
      'getTrytes',

      {
        'duration': 99,
        'trytes':   [binary_type(transaction_trytes)],
      },
    )

    transaction = Transaction.from_tryte_string(transaction_trytes)

    mock_get_bundles = mock.Mock(return_value={
      'bundles': [Bundle([transaction])],
    })

    mock_get_latest_inclusion = mock.Mock(return_value={
      'states': {
        transaction.hash: True,
      },
    })

    with mock.patch(
        'iota.crypto.addresses.AddressGenerator.create_iterator',
        create_generator,
    ):
      with mock.patch(
          'iota.commands.extended.get_bundles.GetBundlesCommand._execute',
          mock_get_bundles,
      ):
        with mock.patch(
          'iota.commands.extended.get_latest_inclusion.GetLatestInclusionCommand._execute',
          mock_get_latest_inclusion,
        ):
          response = self.command(
            seed = Seed.random(),

            inclusionStates = True,

            # To keep the test focused, only retrieve a single
            # transaction.
            start = 0,
            stop  = 1,
          )

    bundle = response['bundles'][0] # type: Bundle
    self.assertTrue(bundle[0].is_confirmed)