Ejemplo n.º 1
0
 def cache_txn_in_tangle_simple(self, ipfs_addr, tag):
     address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX"
     txns = self.api.get_transactions_to_approve(1)
     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_string(ipfs_addr));
     attach_trytes = self.api.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
Ejemplo n.º 2
0
    def get_transactions_as_file_buffer(self, filename, bufsize, ID_msg,
                                        source_addr, dest_addr):
        txn_list = []
        index = 0
        value = 0

        header = ['{0}'.format(source_addr)]
        body = self.get_buffer_from_file(filename, bufsize)

        buffer_msg = []
        buffer_msg.extend(header)
        buffer_msg.extend(body)

        l = len(buffer_msg)

        for msg in buffer_msg:
            TAG = '{0}|{1}|{2}'.format(ID_msg, index, l)
            TAG = TryteString.from_string(TAG)

            txn = self.iota.prepare_transfer(0, dest_addr, TAG, msg)
            txn_list.append(txn)

            index += 1

        return txn_list
Ejemplo n.º 3
0
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}
Ejemplo n.º 4
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
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)
Ejemplo n.º 6
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
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
def anchor_building_block(api, building_address, tag, message_string):
    message = TryteString.from_string(message_string)
    result = api.send_transfer(transfers=[
        ProposedTransaction(
            address=building_address, value=0, tag=tag, message=message)
    ])
    return result
Ejemplo n.º 9
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]
         }
Ejemplo n.º 10
0
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.')
Ejemplo n.º 11
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
Ejemplo n.º 12
0
 def test_from_string(self):
   """
   Converting a Unicode string into a TryteString.
   """
   self.assertEqual(
     binary_type(TryteString.from_string('你好,世界!')),
     b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD',
   )
Ejemplo n.º 13
0
 def test_from_string(self):
     """
 Converting a Unicode string into a TryteString.
 """
     self.assertEqual(
         binary_type(TryteString.from_string('你好,世界!')),
         b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD',
     )
Ejemplo n.º 14
0
def create_and_send_transactions(dest_address, amount, message):
    transaction = ProposedTransaction(address=Address(dest_address),
                                      value=amount,
                                      tag=None,
                                      message=TryteString.from_string(message))

    pt = api.prepare_transfer(transfers=[transaction], change_address=None)
    api.send_trytes(pt['trytes'], depth=100)
Ejemplo n.º 15
0
def pay(amount, reciever, message):
    proposedTrx = ProposedTransaction(address=Address(reciever),
                                      value=0,
                                      tag=Tag("AACHELORTEST"),
                                      message=TryteString.from_string(message))

    proposedBundle = ProposedBundle([proposedTrx])
    preparedBundle = api.prepare_transfer(proposedBundle)
    publishedBundle = api.send_transfer(depth=3, transfers=proposedBundle)
    return publishedBundle
Ejemplo n.º 16
0
    def broadcast_traffic_status(self,
                                 latitude,
                                 longitude,
                                 traffic_status,
                                 tag=MTRAFFIC_REG_TAG,
                                 depth=4,
                                 min_weight_magnitude=None):
        logger.info(
            "Broadcast traffic status at lat:{}, lon:{}, status:{}".format(
                latitude, longitude, traffic_status))
        message = {
            "lat": latitude,
            "lon": longitude,
            "status": traffic_status,
            "timestamp": get_current_timestamp()
        }

        try:
            transfers = [
                # All hail the glory of IOTA and their dummy transactions for tag retrieval. Without multiple
                # transaction, Tangle doesn't seem to pick up our Tag and completely change the value of Tag
                ProposedTransaction(
                    # This address is wholeheartedly irrelevant
                    address=Address(
                        "FNAZ9SXUWMPPVHKIWMZWZXSFLPURWIFTUEQCMKGJAKODCMOGCLEAQQQH9BKNZUIFKLOPKRVHDJMBTBFYK"
                    ),
                    value=0),
                ProposedTransaction(
                    address=Address(
                        "FNAZ9SXUWMPPVHKIWMZWZXSFLPURWIFTUEQCMKGJAKODCMOGCLEAQQQH9BKNZUIFKLOPKRVHDJMBTBFYK"
                    ),
                    value=0,
                    tag=get_tags(tag),
                    message=TryteString.from_string(json.dumps(message)),
                )
            ]
            response = self.api.send_transfer(
                depth=depth,
                transfers=transfers,
                min_weight_magnitude=
                min_weight_magnitude,  # if None, the api will use default number for main-net
            )
        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))
        except:
            logger.exception("Bad coding")
        else:
            bundle = Bundle(response['bundle'])
            print("Bundle Hash: {}\nFrom Address: {}\nTag:".format(
                bundle.hash, bundle.transactions[0].address,
                bundle.transactions[0].tag))
            return response
Ejemplo n.º 17
0
 def create_transaction(cls, text):
     tx = [
         ProposedTransaction(
             # Recipient
             address=Address(cls.address),
             value=0,
             tag=Tag(b'TAG'),
             message=TryteString.from_string(text),
         ),
     ]
     return tx
Ejemplo n.º 18
0
  def test_as_string_not_utf8_errors_ignore(self):
    """
    The tryte sequence does not represent a valid UTF-8 sequence, and
    errors='ignore'.
    """
    # Chop off a couple of trytes to break up a multi-byte sequence.
    trytes = TryteString.from_string('你好,世界!')[:-2]

    self.assertEqual(
      trytes.as_string('ignore'),
      '你好,世界',
    )
Ejemplo n.º 19
0
def attach_debug_message_to_tangle(data):
    tag = "SWARMNODETESTINGDATA"
    message = TryteString.from_string(data)
    address = "BXEOYAONFPBGKEUQZDUZZZODHWJDWHEOYY9AENYF9VNLXZHXBOODCOTYXW9MGGINTEJPLK9AGOPTPODVX"
    value = 0

    # Get tips
    print("Attaching debug data to tangle ... %s" % (str(data)))
    dict_tips = get_tips(0)

    print("Debug bundle = %s" %
        (str(send_transfer(tag, message, address, value, dict_tips, 0))))
Ejemplo n.º 20
0
def prepare_transferes():
    new_transfer = True
    prepared_transferes = []
    while new_transfer:
        get_recipient_address = True
        while get_recipient_address:
            recipient_address = raw_input(
                "\nPlease enter the receiving address: ")

            if len(recipient_address) == 81:
                print(
                    "You enterd a address without checksum. Are you sure you want to continiue?"
                )
                yes = yes_no_user_input()
                if yes:
                    get_recipient_address = False
                else:
                    print(
                        "Good choice! Addresses with checksum are a lot safer to use."
                    )
            elif len(recipient_address) == 90:
                is_valid = is_valid_address(recipient_address)
                if is_valid:
                    get_recipient_address = False
                else:
                    print("Invalid address!! Please try again!")
            else:
                print(
                    "\nYou enterd a invalid address. Address must be 81 or 90 Char long!"
                )

        recipient_address = bytes(recipient_address)
        user_message = raw_input("Please enter a message: ")
        user_tag = raw_input("Please enter a tag: ")
        user_tag = bytes(user_tag)
        transfer_value = transfer_value_user_input()
        txn = \
            ProposedTransaction(
                address=Address(
                    recipient_address
                ),

                message=TryteString.from_string(user_message),
                tag=Tag(user_tag),
                value=transfer_value,
            )
        prepared_transferes.append(txn)
        print("Do you want to prepare another transfer?")
        yes = yes_no_user_input()
        if not yes:
            new_transfer = False

    review_transfers(prepared_transferes)
Ejemplo n.º 21
0
    def test_as_string_not_utf8_errors_ignore(self):
        """
    The tryte sequence does not represent a valid UTF-8 sequence, and
    errors='ignore'.
    """
        # Chop off a couple of trytes to break up a multi-byte sequence.
        trytes = TryteString.from_string('你好,世界!')[:-2]

        self.assertEqual(
            trytes.as_string('ignore'),
            '你好,世界',
        )
Ejemplo n.º 22
0
 def Send(self, ReceiverAddress, Message):
     text_transfer = TryteString.from_string(str(Message))
     #This now proposes a transaction to a person. The "message = ..." command is a message that the receiver should be able to decode once arrived.
     txn_2 = ProposedTransaction(address=Address(ReceiverAddress),
                                 message=text_transfer,
                                 value=0)
     #Now create a new bundle (i.e. propose a bundle)
     bundle = ProposedBundle()
     #Add the transaction "txn_2" to the bundle. We can also add several addresses for receiving but we get to that later.
     bundle.add_transaction(txn_2)
     bundle.finalize()
     coded = bundle.as_tryte_strings()
     send = self.api.send_trytes(trytes=coded, depth=4)
Ejemplo n.º 23
0
    def test_as_string_not_utf8_errors_strict(self):
        """
    The tryte sequence does not represent a valid UTF-8 sequence, and
    errors='strict'.
    """
        # Chop off a couple of trytes to break up a multi-byte sequence.
        trytes = TryteString.from_string('你好,世界!')[:-2]

        # Note the exception type.  The trytes were decoded to bytes
        # successfully; the exception occurred while trying to decode the
        # bytes into Unicode code points.
        with self.assertRaises(UnicodeDecodeError):
            trytes.as_string('strict')
Ejemplo n.º 24
0
    def prepare_transfer(self, transfer_value, dest_addr, tag = 'DEFAULT', msg = 'DEFAULT'):
        # TODO: verify address (checksum)
        # TODO: use mi, gi, etc

        msg = TryteString.from_string(msg)

        txn = ProposedTransaction(address=Address(dest_addr),
                message=msg,
                tag=Tag(tag),
                value=transfer_value,
                )

        return txn
Ejemplo n.º 25
0
  def test_as_string_not_utf8_errors_strict(self):
    """
    The tryte sequence does not represent a valid UTF-8 sequence, and
    errors='strict'.
    """
    # Chop off a couple of trytes to break up a multi-byte sequence.
    trytes = TryteString.from_string('你好,世界!')[:-2]

    # Note the exception type.  The trytes were decoded to bytes
    # successfully; the exception occurred while trying to decode the
    # bytes into Unicode code points.
    with self.assertRaises(UnicodeDecodeError):
      trytes.as_string('strict')
Ejemplo n.º 26
0
  def test_as_string_not_utf8_errors_replace(self):
    """
    The tryte sequence does not represent a valid UTF-8 sequence, and
    errors='replace'.
    """
    # Chop off a couple of trytes to break up a multi-byte sequence.
    trytes = TryteString.from_string('你好,世界!')[:-2]

    self.assertEqual(
      trytes.as_string('replace'),

      # Note that the replacement character is the Unicode replacement
      # character, not '?'.
      '你好,世界�',
    )
Ejemplo n.º 27
0
    def test_as_string_not_utf8_errors_replace(self):
        """
    The tryte sequence does not represent a valid UTF-8 sequence, and
    errors='replace'.
    """
        # Chop off a couple of trytes to break up a multi-byte sequence.
        trytes = TryteString.from_string('你好,世界!')[:-2]

        self.assertEqual(
            trytes.as_string('replace'),

            # Note that the replacement character is the Unicode replacement
            # character, not '?'.
            '你好,世界�',
        )
def send_summary():
    global data_frame
    new_data = {}

    ## IOTA'S IMPLEMENTATION
    data_summary = data_frame.describe([]).round(4)
    print(data_summary)

    dict_summary = data_summary.to_dict()

    for key, value in dict_summary.items():
        new_data["Num"] = int(value.pop("count"))
        new_data[key] = list(value.values())

    data_frame = pd.DataFrame()

    json_summary = json.dumps(new_data)
    print(json_summary)
    print(len(json_summary))

    trytes = TryteString.from_string(json_summary)  # Code Json data in trytes

    print('Message sent to tangle:',
          trytes.decode())  # shows decoded msg sent to tangle

    print('sleep...')
    time.sleep(1)

    print(api)

    t0 = time.time()

    api.send_transfer(
        depth=3,
        transfers=[
            ProposedTransaction(
                address=Address(Address(address[0], )),
                value=0,
                tag=tag,
                message=trytes,
            ),
        ],
    )

    t1 = time.time()

    print('Time:', time.strftime('%H:%M:%S', time.localtime()),
          ' data transfered! in:', round((t1 - t0), 1), 'seconds ')
Ejemplo n.º 29
0
    def test_add_transaction_short_message(self):
        """
    Adding a transaction to a bundle, with a message short enough to
    fit inside a single transaction.
    """
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(
            ProposedTransaction(
                address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999AETEXB'
                                b'D9YBTH9EMFKF9CAHJIAIKDBEPAMH99DEN9DAJETGN'),
                message=TryteString.from_string('Hello, IOTA!'),
                value=42,
            ))

        # We can fit the message inside a single fragment, so only one
        # transaction is necessary.
        self.assertEqual(len(self.bundle), 1)
Ejemplo n.º 30
0
    def cache_txn_in_tangle(self, ipfs_addr, tag):
        api_response = self.api.get_new_addresses()
        addy = api_response['addresses'][0]
        address = binary_type(addy).decode('ascii')

        result = self.api.send_transfer(
            depth=3,
            transfers=[
                ProposedTransaction(
                    address=Address(address),
                    value=0,
                    tag=Tag(tag),
                    message=TryteString.from_string(ipfs_addr),
                ),
            ],
        )
        return result
def transfer(node):
    start_send = time.time()

    address = "ILXW9VMJQVFQVKVE9GUZSODEMIMGOJIJNFAX9PPJHYQPUHZLTWCJZKZKCZYKKJJRAKFCCNJN9EWOW9N9YDGZDDQDDC"
    tag = "TAG"
    message = "MSG"
    value = 0
    node_url = node

    recipient_address = address
    sender_message = message
    sender_tag = tag

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

    sender_tag = 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)
    try:
        bundle_hash = api.send_transfer(
            depth=DEPTH,
            transfers=prepared_transferes,
            min_weight_magnitude=MIN_WEIGHT_MAGNITUDE
        )
    except Exception as e:
        print("Error" + str(e))
        return "0, 0"

    done_send = time.time()
    elapsed_send = int(done_send - start_send)

    return elapsed_send, bundle_hash['bundle'].hash
Ejemplo n.º 32
0
def get_zero_transactions(filename, fileid, value, bufsize, dest_addr):
    txn_list = []
    index = 1

    buffer_msg = get_buffer_from_file(filename, bufsize)
    l = len(buffer_msg)

    for msg in buffer_msg:
        TAG = '{0}|{1}|{2}'.format(index, l, fileid)
        TAG = TryteString.from_string(TAG)

        txn = iota.prepare_transfer(dest_addr, value, TAG, msg)
        txn_list.append(txn)

        index += 1

    return txn_list
def send_transaction(node_url, address, tag, messages, values):
    propose_bundle = ProposedBundle()

    # Setting output transaction ...
    txn_output = ProposedTransaction(
        address = Address(address),
        value = values,
        tag = Tag(tag),
        message = TryteString.from_string(messages)
    )

    propose_bundle.add_transaction(txn_output)
    propose_bundle.finalize()
    trytes = propose_bundle.as_tryte_strings()

    api = Iota(node_url)

    # Tips
    trunk_hash, branch_hash = gtta(node_url)

    for tx_tryte in trytes:
        # Attachment timestamp insert
        timestamp = TryteString.from_trits(
            trits_from_int(int(time.time() * 1000), pad=27))
        tx_tryte = insert_to_trytes(2619, 2628, str(timestamp), tx_tryte)

        # timestamp_lower_bound = MIN_VALUE
        # timestamp_upper_bound = MAX_VALUE
        tx_tryte = insert_to_trytes(2637, 2646, str("MMMMMMMMM"), tx_tryte)

        # Tips insert - trunk
        tx_tryte = insert_to_trytes(2430, 2511, str(trunk_hash), tx_tryte)
        # Tips insert - branch
        tx_tryte = insert_to_trytes(2511, 2592, str(branch_hash), tx_tryte)

        # Do PoW for this transaction
        tx_tryte = attach_to_tangle(node_url, trunk_hash, branch_hash, tx_tryte)

        # Prepare to store and broadcast ...
        try:
            api.broadcast_and_store(tx_tryte)
        except Exception as e:
            return str("Error: %s" % (str(e)))

        return str(propose_bundle.hash)
Ejemplo n.º 34
0
 def send_msg_to_addr(self, address: Address, msg: str, tag: str) -> dict:
     """
     Sends msg on Tangle to address with a tag
     """
     try:
         response = self.iota_api.send_transfer(
             depth=5,
             transfers=[
                 ProposedTransaction(address=address,
                                     value=0,
                                     tag=Tag(tag),
                                     message=TryteString.from_string(msg))
             ])
     except Exception as e:
         logging.warning(
             "Message '" + msg + "' has failed to be stored in " +
             address.__str__(), e)
         response = None
     return response
Ejemplo n.º 35
0
  def test_add_transaction_short_message(self):
    """
    Adding a transaction to a bundle, with a message short enough to
    fit inside a single transaction.
    """
    # noinspection SpellCheckingInspection
    self.bundle.add_transaction(ProposedTransaction(
      address =
        Address(
          b'TESTVALUE9DONTUSEINPRODUCTION99999AETEXB'
          b'D9YBTH9EMFKF9CAHJIAIKDBEPAMH99DEN9DAJETGN'
        ),

      message = TryteString.from_string('Hello, IOTA!'),
      value   = 42,
    ))

    # We can fit the message inside a single fragment, so only one
    # transaction is necessary.
    self.assertEqual(len(self.bundle), 1)
Ejemplo n.º 36
0
    # want, but to keep this example focused, we will only include a
    # single spend transaction.
    transfers = [
      ProposedTransaction(
        address =
          Address(
            b'TESTVALUE9DONTUSEINPRODUCTION99999NDGYBC'
            b'QZJFGGWZ9GBQFKDOLWMVILARZRHJMSYFZETZTHTZR',
          ),

        value = 42,

        # If you'd like, you may include an optional tag and/or
        # message.
        tag = Tag(b'KITTEHS'),
        message = TryteString.from_string('thanx fur cheezburgers'),
      ),
    ],

    # Specify our multisig address as the input for the spend
    # transaction(s).
    # Note that PyOTA currently only allows one multisig input per
    # bundle (although the protocol does not impose a limit).
    multisig_input = multisig_address,

    # If there will be change from this transaction, you MUST specify
    # the change address!  Unlike regular transfers, multisig transfers
    # will NOT automatically generate a change address; that wouldn't
    # be fair to the other participants!
    change_address = None,
  )
Ejemplo n.º 37
0
  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)