Ejemplo n.º 1
0
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,))
Ejemplo n.º 2
0
def cast_message(value, private_key):
    ###data for hash function
    data = (value).encode("utf-8")
    ##message to store in the tangle
    message = TryteString.from_unicode(value)
    signature = sign_message(data, private_key)
    end = TryteString.from_unicode('?')
    message = message + signature + end
    return message
Ejemplo n.º 3
0
def print_bundle_tail_result(result, timer, tx_num=1):
    for bundle in result.values():
        for transaction in bundle.transactions[1:]:
            i = transaction.current_index + tx_num
            print('--------------------')
            print(f'    Tx{i} hash: ' + str(transaction.hash))
            print(f'    Tx{i} address: ' + str(transaction.address))
            print(f'    Tx{i} value: ' + str(transaction.value))
            print(f'    Tx{i} message: ' +
                  str(transaction.signature_message_fragment.decode()))
            print(f'    Tx{i} message size: ' + str(
                len(
                    TryteString.from_unicode(
                        transaction.signature_message_fragment.decode()))) +
                  ' trytes  (max 2187 trytes)')
            print(f'    Tx{i} tag: ' + str(transaction.tag))
            print(f'    Tx{i} nonce: ' + str(transaction.nonce))
            print(f'    Tx{i} branch hash: ' +
                  str(transaction.branch_transaction_hash))
            print(f'    Tx{i} trunk hash: ' +
                  str(transaction.trunk_transaction_hash))
            print(f'    Tx{i} timestamp: ' + str(
                datetime.utcfromtimestamp(transaction.timestamp).strftime(
                    '%Y-%m-%d %H:%M:%S')))
        print('--------------------')
        print('Tail Tx hash: ' + str(bundle.tail_transaction.hash))
        print('Tail Tx address: ' + str(bundle.tail_transaction.address))
        print('Tail Tx value: ' + str(bundle.tail_transaction.value))
        print('Tail Tx message: ' +
              str(bundle.tail_transaction.signature_message_fragment.decode()))
        print('Tail Tx message size: ' + str(
            len(
                TryteString.from_unicode(
                    bundle.tail_transaction.signature_message_fragment.decode(
                    )))) + ' trytes  (max 2187 trytes)')
        print('Tail Tx tag: ' + str(bundle.tail_transaction.tag))
        print('Tail Tx nonce: ' + str(bundle.tail_transaction.nonce))
        print('Tail Tx branch hash: ' +
              str(bundle.tail_transaction.branch_transaction_hash))
        print('Tail Tx trunk hash: ' +
              str(bundle.tail_transaction.runk_transaction_hash))
        print('Tail Tx timestamp: ' + str(
            datetime.utcfromtimestamp(bundle.tail_transaction.timestamp).
            strftime('%Y-%m-%d %H:%M:%S')))
        print('--------------------')
        print('Bundle hash: ' + str(bundle.hash))
        print('Bundle confirmation: ' + str(bundle.is_confirmed))
        print('Bundle upload time: ' + str(round(timer, 2)) + ' seconds  (' +
              str(round(timer / len(bundle.transactions), 2)) + ' sec/tx)')
Ejemplo n.º 4
0
  def test_add_signature_or_message_invalid_start_index(self):
    """
    Attempting to add fragments to a bundle, but `start_index` is invalid.
    """
    # Add 3 transactions to the bundle.
    for i in ['A', 'B', 'C']:
      self.bundle.add_transaction(ProposedTransaction(
        address =
          Address(
            'TESTVALUE' + i + 'DONTUSEINPRODUCTION99999QARFLF'
            'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'
          ),
        message = TryteString.from_unicode('This should be overwritten'),
        value = 0,
      ))

    fragment1 = Fragment.from_unicode('This is the first fragment.')

    with self.assertRaises(ValueError):
      self.bundle.add_signature_or_message([fragment1], start_index=-1)

    with self.assertRaises(ValueError):
      self.bundle.add_signature_or_message([fragment1], start_index=3)

    with self.assertRaises(TypeError):
      self.bundle.add_signature_or_message([fragment1], 'not an int')
Ejemplo n.º 5
0
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")
Ejemplo n.º 6
0
def on_message(client, userdata, msg):
    if msg.payload:
        addresstobeused = str(msg.payload)
        print(msg.topic + " " + addresstobeused)
        print("Received the address!")
        transfers = api.get_account_data()
        print(transfers)
        bundle = api.send_transfer(
            depth=100,
            transfers=[
                ProposedTransaction(
                    # Recipient of the transfer.
                    address=Address(
                        addresstobeused[2:-1]).with_valid_checksum(),
                    # Amount of IOTA to transfer.
                    # This value may be zero.
                    value=0,
                    # Optional tag to attach to the transfer.
                    tag=Tag('TESTING'),
                    # Optional message to include with the transfer.
                    # message = TryteString.from_string('Please work!'),
                    message=TryteString.from_unicode('Happy Holi!')),
            ],
        )
        print(api.get_node_info())
Ejemplo n.º 7
0
  def test_add_signature_or_message_too_long_fragments(self):
    """
    Trying to add too many fragments to a bundle, when there aren't enough
    transactions to hold them.
    """
    # Add 3 transactions to the bundle.
    for i in ['A', 'B', 'C']:
      self.bundle.add_transaction(ProposedTransaction(
        address =
          Address(
            'TESTVALUE' + i + 'DONTUSEINPRODUCTION99999QARFLF'
            'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'
          ),
        message= TryteString.from_unicode('This should be overwritten'),
        value = 0,
      ))

    fragment1 = Fragment.from_unicode('This is the first fragment.')
    # 4 fragments, 3 txs in bundle
    fragments = [fragment1] * 4

    with self.assertRaises(ValueError):
      self.bundle.add_signature_or_message(fragments)

    # Length is okay, but overflow because of offset
    fragments = [fragment1] * 3

    with self.assertRaises(ValueError):
      self.bundle.add_signature_or_message(fragments,start_index=1)
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
    def test_add_signature_or_message(self):
        """
    Add a fragment to a transaction.
    """
        # Add a transaction
        self.bundle.add_transaction(
            ProposedTransaction(
                address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF'
                                b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'),
                message=TryteString.from_unicode('This should be overwritten'),
                value=0,
            ))
        custom_msg = \
          'The early bird gets the worm, but the custom-msg gets into the bundle.'
        custom_fragment = Fragment.from_unicode(custom_msg)

        # Before finalization, the method adds to message field...
        self.bundle.add_signature_or_message([custom_fragment])
        self.assertEqual(self.bundle._transactions[0].message, custom_fragment)

        # ... because upon finalization, this is translated into
        # signature_message_fragment field.
        self.bundle.finalize()
        self.assertEqual(
            self.bundle._transactions[0].signature_message_fragment,
            custom_fragment)

        # Do we have the right text inside?
        self.assertEqual(self.bundle.get_messages()[0], custom_msg)
Ejemplo n.º 10
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
        )
Ejemplo n.º 11
0
    def finalizeEscrow(self, fee=None, deposit=None):
        if fee is None: fee = self.fee
        if deposit is None: deposit = self.deposit
        #Return money to deposit address
        returnAmount = self.getBalance(self.holdingAddress)

        #Calcualte return amount
        if returnAmount > 0:
            returnAmount -= fee

        #Setup transaction
        message = "Repayment of collateral"
        feeLocation = self.api.get_new_addresses(count=1,
                                                 checksum=True)['addresses'][0]
        txs = [
            ProposedTransaction(address=Address(deposit),
                                value=returnAmount,
                                message=TryteString.from_unicode(message)),
        ]

        #Send transaction
        try:
            bundle = self.api.send_transfer(transfers=txs)['bundle']
        except iota.adapter.BadApiResponse as e:
            print("Node did not respond. Retrying.")
            return self.finalizeEscrow(fee, deposit)
        logging.info(bundle.transactions[0].hash)
        logging.info("Sent money back to recipient")
        self.addRevenue(fee)
Ejemplo n.º 12
0
 def test_from_unicode(self):
     """
 Converting a Unicode string into a TryteString.
 """
     self.assertEqual(
         binary_type(TryteString.from_unicode('你好,世界!')),
         b'LH9GYEMHCF9GWHZFEELHVFOEOHNEEEWHZFUD',
     )
Ejemplo n.º 13
0
def sendMoney(address,data,amount):
	tx = ProposedTransaction(address=Address(address),message=TryteString.from_unicode(str(data)),tag=Tag('SENDMONEY'),value=amount)
	tx = node.prepare_transfer(transfers=[tx])
	try:
		result = node.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9)
		return 1
	except:
		return 0
Ejemplo n.º 14
0
def tx_to_tangle(api, address_in, data_in, tag_in='', value_in=0):
    result = api.send_transfer(transfers=[
        ProposedTransaction(address=address_in,
                            message=TryteString.from_unicode(data_in),
                            tag=Tag(tag_in.encode()),
                            value=value_in)
    ])
    return result
Ejemplo n.º 15
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])
Ejemplo n.º 16
0
 def send(trak_id, lat, lon):
     dict_message = {"trak_id": trak_id, "lat": lat, "lon": lon}
     message = TryteString.from_unicode(str(dict_message))
     tx = ProposedTransaction(address=Address(address),
                              message=message,
                              tag=Tag(b'KUBERFLETE9999999'),
                              value=0)
     result = api.send_transfer(transfers=[tx])
     return result
Ejemplo n.º 17
0
 def _compose_transaction(address, msg, tag, val):
     txn = \
         ProposedTransaction(
             address=Address(address),
             message=TryteString.from_unicode(msg),
             tag=Tag(tag),
             value=val
         )
     return txn
Ejemplo n.º 18
0
    def test_add_signature_or_messagee_multiple(self):
        """
    Add multiple fragments.
    """
        # Add 3 transactions to the bundle, For convenience, we use
        # 3 different addresses, so they are not grouped together and
        # bundle.get_messages() returns a list of messages mapping to
        # the 3 transactions.
        for i in ['A', 'B', 'C']:
            self.bundle.add_transaction(
                ProposedTransaction(
                    address=Address(
                        'TESTVALUE' + i + 'DONTUSEINPRODUCTION99999QARFLF'
                        'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'),
                    message=TryteString.from_unicode(
                        'This should be overwritten'),
                    value=0,
                ))

        fragment1 = Fragment.from_unicode('This is the first fragment.')
        fragment2 = Fragment.from_unicode('This is the second fragment.')

        self.bundle.add_signature_or_message([fragment1, fragment2])

        bundle_fragments = []
        for tx in self.bundle:
            bundle_fragments.append(tx.message)

        self.assertListEqual(bundle_fragments, [
            fragment1, fragment2,
            TryteString.from_unicode('This should be overwritten')
        ])

        self.bundle.finalize()

        bundle_fragments_unicode = []
        for tx in self.bundle:
            bundle_fragments_unicode.append(
                tx.signature_message_fragment.decode())

        self.assertListEqual(bundle_fragments_unicode, [
            fragment1.decode(),
            fragment2.decode(), 'This should be overwritten'
        ])
Ejemplo n.º 19
0
def convert(data, salt):
    OUTPUT_SIZE = 80  # Number of characters to fit IOTA address
    hash_shake = sha3.shake_128()
    if salt is None:
        hash_shake.update(data.encode())
    else:
        hash_shake.update(data.encode() + salt.encode())
    msg_trytes = TryteString.from_unicode(
        hash_shake.hexdigest(int(OUTPUT_SIZE / 4))) + TryteString(b'9')
    return Address(msg_trytes)
Ejemplo n.º 20
0
 def send_funds(self):
     tx = ProposedTransaction(
         address=Address(self.owner),
         message=TryteString.from_unicode('IOTAPay Device V1'),
         tag=Tag('IOTAPAYTRANSACTION'),
         value=self.summary
     )
     tx = self.api.prepare_transfer(transfers=[tx], inputs=self.value_addresses, change_address=self.owner)
     result = self.api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=14)
     print('Transaction with:', self.summary, 'iota sent to the tangle!')
Ejemplo n.º 21
0
def store_iota(string):
    """
    We assume the string will not exceed 2187 Trytes as it is supposed to be a hash with a short fixed length

    :param string: message to be sent in the IOTA transaction
    :return: If the input string is hexadecimal : a dictionary containing the string sent in the transaction
    and the transaction hash.
            If not : False
    :rtype: Dictionary if the input string is hexadecimal or boolean if not.

    """
    if string != "":
        message = TryteString.from_unicode(
            string
        )  # Note: if message > 2187 Trytes, it is sent in several transactions
        logger.debug("'%s' ready to be sent" % string)
        proposed_transaction = ProposedTransaction(address=Address(address),
                                                   value=0,
                                                   message=message)
        transfer = api.send_transfer(  # Execution of the transaction = only time consuming operation
            depth=depth,
            transfers=[proposed_transaction],
        )
        tx_hash = str(get_transaction_hashes(transfer)[0])

        created = datetime.datetime.now().isoformat()

        if tx_hash is None:
            result = {
                'status': 'timeout',
                'message': string,
                'blockchain': 'iota',
                'network_info': networkinfo,
                'network_type': networktype,
                'created': created
            }
            logger.error(result)
            return result
        else:
            logger.debug("'%s' sent" % string)
            result = {
                'status': 'added',
                'txid': tx_hash,
                'message': string,
                'blockchain': 'iota',
                'network_info': networkinfo,
                'network_type': networktype,
                'created': created
            }
            logger.info(result)
            return result

    else:
        logger.error({"emtpy message": string})
        return False
Ejemplo n.º 22
0
def on_message(client, userdata, msg):
    """ receiving data"""
    try:
        sensors = msg.payload
        sensors = json.loads(sensors.decode('utf-8'))
    except e:
        print("Check the message: ",e)

    logfile = open("enviro.csv", "a")
    print(sensors["timestamp"], ",",\
          sensors["device_name"], ",",\
          sensors["device_owner"], ",",\
          sensors["city"], ",",\
          sensors["lng"], ",",\
          sensors["lat"], ",",\
          sensors["lux"], ",",\
          sensors["rgb"], ",",\
          sensors["accel"], ",",\
          sensors["heading"], ",",\
          sensors["temperature"], ",",\
          sensors["pressure"], file=logfile)
    logfile.close()


    api = Iota('https://nodes.devnet.iota.org:443') 
    address = 'H9TJVEEAOAI9ADCFSRIKOYHNLVDIRDIIREXQUJNBIWBSINJIJXXDTPTRDOZRRSCUOLZAXVZNRHDCWVSVD'
    tx = ProposedTransaction(
        address=Address(address),
        #message=TryteString.from_unicode(sensors),
        message=TryteString.from_unicode(json.dumps(sensors)),
        tag=Tag('ENVIROPHATIII'),
        value=0
    )
    print(tx)
    try:
        tx = api.prepare_transfer(transfers=[tx])
    except:
        print("PREPARE EXCEPTION",tx)
    try:
        result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9)
    except:
        print("EXCEPTION", result)

    print("\nTimestamp: ", sensors["timestamp"])
    print("Device: ", sensors["device_name"])
    print("Device owner email: ", sensors["device_owner"])
    print("Device location: ", sensors["city"], " at longitude: ", sensors["lng"], " and latitude: ", sensors["lat"])
    print("Light: ", sensors["lux"])
    print("RGB: ", sensors["rgb"])
    print("Accelerometer: ", sensors["accel"])
    print("Heading: ", sensors["heading"])
    print("Temperature: ", sensors["temperature"])
    print("Pressure: ", sensors["pressure"])

    return sensors
Ejemplo n.º 23
0
    def test_add_signature_or_message_multiple_offset(self):
        """
    Add multiple fragments with offset.
    """
        # Add 3 transactions to the bundle.
        for i in ['A', 'B', 'C']:
            self.bundle.add_transaction(
                ProposedTransaction(
                    address=Address(
                        'TESTVALUE' + i + 'DONTUSEINPRODUCTION99999QARFLF'
                        'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'),
                    message=TryteString.from_unicode(
                        'This should be overwritten'),
                    value=0,
                ))

        fragment1 = Fragment.from_unicode('This is the first fragment.')
        fragment2 = Fragment.from_unicode('This is the second fragment.')

        self.bundle.add_signature_or_message([fragment1, fragment2], 1)

        bundle_fragments = []
        for tx in self.bundle:
            bundle_fragments.append(tx.message)

        self.assertListEqual(bundle_fragments, [
            TryteString.from_unicode('This should be overwritten'), fragment1,
            fragment2
        ])

        self.bundle.finalize()

        bundle_fragments_unicode = []
        for tx in self.bundle:
            bundle_fragments_unicode.append(
                tx.signature_message_fragment.decode())

        self.assertListEqual(bundle_fragments_unicode, [
            'This should be overwritten',
            fragment1.decode(),
            fragment2.decode()
        ])
Ejemplo n.º 24
0
def bundle_to_tangle(api, address_in, dframe_in, tag_in=''):
    transfer_txs = []
    for index, row in dframe_in.iterrows():
        transfer_txs.append(
            ProposedTransaction(address=address_in,
                                message=TryteString.from_unicode(
                                    row.to_json()),
                                tag=Tag(tag_in.encode()),
                                value=0))
    result = api.send_transfer(transfers=transfer_txs)
    return result
Ejemplo n.º 25
0
def on_message(client, userdata, msg):
    """ receiving data"""

    try:
        sensors = msg.payload
        sensors = json.loads(sensors.decode('utf-8'))
    except e:
        print("Check the message: ", e)

    # this format stores data in CSV format in AstroPiOTA.log
    logfile = open("AstroPiOTA.csv", "a")
    print(str(sensors["timestamp"]),",",str(sensors["lng"]),",",\
        str(sensors["lat"]),",",str(sensors["device_name"]),",",str(sensors["temperature"]),",",\
        str(sensors["humidity"]),",",str(sensors["pressure"]),",",str(sensors["pitch"]),",",\
        str(sensors["roll"]),",",str(sensors["yaw"]),",",str(sensors["x"]),",",\
        str(sensors["y"]),",",str(sensors["z"]),",",str(sensors["device_owner"]),",",str(sensors["city"]),file=logfile)
    logfile.close()

    # this prints the AstroPiOTA data message
    print("\nTimestamp: ", str(sensors["timestamp"]))
    print("Device: ", sensors["device_name"])
    print("Device owner email: ", sensors["device_owner"])
    print("Device location: ", sensors["city"], " at longitude: ",
          sensors["lng"], " and latitude: ", sensors["lat"])

    print("Temperature: ", sensors["temperature"])
    print("Humidity: ", sensors["humidity"])
    print("Pressure: ", sensors["pressure"])

    print("Pitch: ", sensors["pitch"])
    print("Roll: ", sensors["roll"])
    print("Yaw: ", sensors["yaw"])

    print("Accelerometer x: ", sensors["x"])
    print("Accelerometer y: ", sensors["y"])
    print("Accelerometer z: ", sensors["z"])

    api = Iota('https://nodes.devnet.iota.org:443')
    address = '999999999999999999999999999999999999999999999999999999999999999999999999999999999'
    tx = ProposedTransaction(
        address=Address(address),
        #message=TryteString.from_unicode(sensors),
        message=TryteString.from_unicode(json.dumps(sensors)),
        tag=Tag('ASTROPIOTAIIIDEMO'),
        value=0)
    print(tx)
    try:
        tx = api.prepare_transfer(transfers=[tx])
    except:
        print("PREPARE EXCEPTION", tx)
    try:
        result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9)
    except:
        print("EXCEPTION", result)
Ejemplo n.º 26
0
def prepare_bundle():
    message = TryteString.from_unicode('Bang')
    address = 'ZQGVEQ9JUZZWCZXLWVNTHBDX9G9KZTJP9VEERIIFHY9SIQKYBVAHIMLHXPQVE9IXFDDXNHQINXJDRPFDXNYVAPLZAW'

    transfers = [
        ProposedTransaction(address=Address(address), value=0),
        ProposedTransaction(address=Address(address), value=0),
        ProposedTransaction(address=Address(address), value=0)
    ]
    trytes = api.prepare_transfer(transfers=transfers).get('trytes')
    return trytes
Ejemplo n.º 27
0
 def sendTransaction(self, data, tag):
     # Structure transaction-构造交易
     tx = ProposedTransaction(
         address=Address(iotaAddress),
         message=TryteString.from_unicode(data),
         tag=Tag(tag),
         value=0
     )
     tx = api.prepare_transfer(transfers=[tx])
     result = api.send_trytes(tx['trytes'], depth=iota_depth, min_weight_magnitude=iota_min_weight_magnitude)
     print('Transaction sent to the tangle! result:{}'.format(result))
Ejemplo n.º 28
0
    def test_decode_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_unicode('你好,世界!')[:-2]

        self.assertEqual(
            trytes.decode('ignore'),
            '你好,世界',
        )
Ejemplo n.º 29
0
Archivo: emi.py Proyecto: SLeeTech/EMI
    def send_message(message, root_address, tag):

        pt = ProposedTransaction(address=root_address,
                                 message=TryteString.from_unicode(message),
                                 tag=tag,
                                 value=0)

        ## Send the Transaction
        FinalBundle = api.send_transfer(depth=3,
                                        transfers=[pt],
                                        min_weight_magnitude=14)['bundle']

        return FinalBundle
Ejemplo n.º 30
0
    def test_decode_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_unicode('你好,世界!')[:-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.decode('strict')