def test_error_zero_iotas_transferred(self):
        """
    The bundle doesn't spend any IOTAs.

    This is considered an error case because
    :py:meth:`MultisigIota.prepare_multisig_transfer` is specialized
    for generating bundles that require multisig inputs.  Any bundle
    that doesn't require multisig functionality should be generated
    using :py:meth:`iota.api.Iota.prepare_transfer` instead.
    """
        with self.assertRaises(ValueError):
            self.command(
                transfers=[
                    ProposedTransaction(
                        address=Address(self.trytes_1),
                        value=0,
                    ),
                ],
                multisigInput=MultisigAddress(
                    digests=[self.digest_1, self.digest_2],
                    trytes=self.trytes_2,
                ),
            )
Example #2
0
    def test_sign_input_at_error_index_invalid(self):
        """
    The specified index doesn't exist in the bundle.
    """
        # Add a transaction so that we can finalize the bundle.
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(ProposedTransaction(
            address=Address(
                b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF'
                b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'
            ),

            value=42,
        ))

        self.bundle.add_inputs([self.input_0_bal_eq_42])
        self.bundle.finalize()

        private_key = \
            KeyGenerator(self.seed).get_key_for(self.input_0_bal_eq_42)

        with self.assertRaises(IndexError):
            self.bundle.sign_input_at(2, private_key)
Example #3
0
    def test_sign_input_at_error_not_finalized(self):
        """
    Cannot sign inputs because the bundle isn't finalized yet.
    """
        # Add a transaction so that we can finalize the bundle.
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(
            ProposedTransaction(
                address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF'
                                b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'),
                value=42,
            ))

        self.bundle.add_inputs([self.input_0_bal_eq_42])

        # Oops; did we forget something?
        # self.bundle.finalize()

        private_key =\
          KeyGenerator(self.seed).get_key_for(self.input_0_bal_eq_42)

        with self.assertRaises(RuntimeError):
            self.bundle.sign_input_at(1, private_key)
Example #4
0
    def test_sign_inputs_error_not_finalized(self):
        """
    Attempting to sign inputs in a bundle that hasn't been finalized
    yet.
    """
        # Add a transaction so that we can finalize the bundle.
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(ProposedTransaction(
            address=Address(
                b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF'
                b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'
            ),

            value=42,
        ))

        self.bundle.add_inputs([self.input_0_bal_eq_42])

        # Oops; did we forget something?
        # self.bundle.finalize()

        with self.assertRaises(RuntimeError):
            self.bundle.sign_inputs(KeyGenerator(b''))
Example #5
0
    def test_finalize_error_positive_balance(self):
        """
    Attempting to finalize a bundle with insufficient inputs.
    """
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(ProposedTransaction(
            address=Address(
                b'TESTVALUE9DONTUSEINPRODUCTION99999IGEFUG'
                b'LIHIJGJGZ9CGRENCRHF9XFEAWD9ILFWEJFKDLITCC'
            ),

            value=42,
        ))

        self.bundle.add_inputs([self.input_1_bal_eq_40])

        # Bundle spends 42 IOTAs, but inputs total only 40 IOTAs.
        self.assertEqual(self.bundle.balance, 2)

        # In order to finalize this bundle, we need to provide additional
        # inputs.
        with self.assertRaises(ValueError):
            self.bundle.finalize()
Example #6
0
    def test_finalize_error_negative_balance(self):
        """
    Attempting to finalize a bundle with unspent inputs.
    """
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(ProposedTransaction(
            address=Address(
                b'TESTVALUE9DONTUSEINPRODUCTION99999IGEFUG'
                b'LIHIJGJGZ9CGRENCRHF9XFEAWD9ILFWEJFKDLITCC'
            ),

            value=42,
        ))

        self.bundle.add_inputs([self.input_0_bal_eq_42, self.input_2_bal_eq_2])

        # Bundle spends 42 IOTAs, but inputs total 44 IOTAs.
        self.assertEqual(self.bundle.balance, -2)

        # In order to finalize this bundle, we need to specify a change
        # address.
        with self.assertRaises(ValueError):
            self.bundle.finalize()
Example #7
0
    def test_add_inputs_happy_path(self):
        """
    Adding a multisig input to a bundle.
    """
        # noinspection SpellCheckingInspection
        self.bundle.add_transaction(
            ProposedTransaction(
                address=Address(self.trytes_1),
                value=42,
            ), )

        self.bundle.add_inputs([
            MultisigAddress(
                trytes=self.trytes_2,
                digests=[self.digest_1, self.digest_2],
                balance=42,
            )
        ])

        # The multisig input requires a total of 4 transactions to store
        # all the signatures.  Including the spend, that makes 5
        # transactions in total.
        self.assertEqual(len(self.bundle), 5)
Example #8
0
def transfer(address, tag, message, value):

    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:
        print("Exception on TangleID transaction agent.")
        return "Exception on TangleID transaction agent."

    print(bundle_hash['bundle'].hash)
    return str(bundle_hash['bundle'].hash)
Example #9
0
    def test_finalize_insecure_bundle(self):
        """
    When finalizing, the bundle detects an insecure bundle hash.

    References:
      - https://github.com/iotaledger/iota.lib.py/issues/84
    """
        # noinspection SpellCheckingInspection
        bundle = ProposedBundle([
            ProposedTransaction(
                address=Address(
                    '9XV9RJGFJJZWITDPKSQXRTHCKJAIZZY9BYLBEQUX'
                    'UNCLITRQDR9CCD99AANMXYEKD9GLJGVB9HIAGRIBQ', ),
                tag=Tag('PPDIDNQDJZGUQKOWJ9JZRCKOVGP'),
                timestamp=1509136296,
                value=0,
            ),
        ])
        bundle.finalize()

        # The resulting bundle hash is insecure (contains a [1, 1, 1]), so
        # the legacy tag is manipulated until a secure hash is generated.
        # noinspection SpellCheckingInspection
        self.assertEqual(bundle[0].legacy_tag,
                         Tag('ZTDIDNQDJZGUQKOWJ9JZRCKOVGP'))

        # The proper tag is left alone, however.
        # noinspection SpellCheckingInspection
        self.assertEqual(bundle[0].tag, Tag('PPDIDNQDJZGUQKOWJ9JZRCKOVGP'))

        # The bundle hash takes the modified legacy tag into account.
        # noinspection SpellCheckingInspection
        self.assertEqual(
            bundle.hash,
            BundleHash(
                'NYSJSEGCWESDAFLIFCNJFWGZ9PCYDOT9VCSALKBD'
                '9UUNKBJAJCB9KVMTHZDPRDDXC9UFJQBJBQFUPJKFC', ))
    def test_fail_multisigInput_wrong_type(self):
        """
    ``multisigInput`` is not a MultisigAddress.
    """
        self.assertFilterErrors(
            {
                'changeAddress':
                Address(self.trytes_1),

                # This value must be a MultisigAddress, so that we know the
                # total security level of the digests used to create it.
                'multisigInput':
                Address(self.trytes_2),
                'transfers': [
                    ProposedTransaction(
                        address=Address(self.trytes_3),
                        value=42,
                    ),
                ],
            },
            {
                'multisigInput': [f.Type.CODE_WRONG_TYPE],
            },
        )
Example #11
0
  def test_sign_input_at_error_index_not_input(self):
    """
    The specified index references a transaction that is not an input.
    """
    # Add a transaction so that we can finalize the bundle.
    self.bundle.add_transaction(ProposedTransaction(
      address =
        Address(
          b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF'
          b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'
        ),

      value = 42,
    ))

    self.bundle.add_inputs([self.input_0_bal_eq_42])
    self.bundle.finalize()

    private_key =\
      KeyGenerator(self.seed).get_key_for(self.input_0_bal_eq_42)

    with self.assertRaises(ValueError):
      # You can't sign the spend transaction, silly!
      self.bundle.sign_input_at(0, private_key)
Example #12
0
  def test_add_inputs_error_already_finalized(self):
    """
    Attempting to add inputs to a bundle that is already finalized.
    """
    # Add 1 transaction so that we can finalize the bundle.
    self.bundle.add_transaction(
      ProposedTransaction(
        address =
          Address(
            b'TESTVALUE9DONTUSEINPRODUCTION99999XE9IVG'
            b'EFNDOCQCMERGUATCIEGGOHPHGFIAQEZGNHQ9W99CH',
          ),

        value = 0,
      ),
    )

    self.bundle.finalize()

    with self.assertRaises(RuntimeError):
      # Even though no inputs are provided, it's still an error; you
      # shouldn't even be calling ``add_inputs`` once the bundle is
      # finalized!
      self.bundle.add_inputs([])
Example #13
0
    def _execute(self, request):
        depth = request['depth']  # type: int
        min_weight_magnitude = request['minWeightMagnitude']  # type: int
        transaction = request['transaction']  # type: TransactionHash

        cc_response = CheckConsistencyCommand(
            self.adapter)(tails=[transaction])
        if cc_response['state'] is False:
            raise BadApiResponse(
                'Transaction {transaction} is not promotable. '
                'You should reattach first.'.format(transaction=transaction))

        spam_transfer = ProposedTransaction(
            address=Address(b''),
            value=0,
        )

        return SendTransferCommand(self.adapter)(
            seed=spam_transfer.address,
            depth=depth,
            transfers=[spam_transfer],
            minWeightMagnitude=min_weight_magnitude,
            reference=transaction,
        )
Example #14
0
 def send_to_iota(node: str,
                  transactions: List[Transaction],
                  local_pow: bool = False) -> str:
     logger.info(f"[SEND TO IOTA] Data: {transactions}")
     # Prepare transactions
     transfers = [
         ProposedTransaction(
             address=Address(transaction.address),
             message=TryteString.from_string(transaction.message),
             tag=Tag(transaction.tag),
             value=0,
         ) for transaction in transactions
     ]
     # Create adapter
     api = iota(adapter=node, local_pow=local_pow)
     # Send transactions to IOTA
     logger.info("[SEND TO IOTA] Sending...")
     bundle_result = api.send_transfer(transfers=transfers)["bundle"]
     logger.info("[SEND TO IOTA]            Done")
     # Bundle hash
     logger.info(f"[SEND TO IOTA] Bundle hash: {bundle_result.hash}")
     # Show bundle result
     logger.debug(bundle_result.as_json_compatible())
     return str(bundle_result.hash)
Example #15
0
    def send_to_iota(node: str, transactions: List[Transaction], local_pow: bool = False) -> str:
        """send json type data to IOTA

        Args:
            node (str): IOTA node
            transactions (List[Transaction]): transactions
            local_pow (bool, optional): local pow, might failed. Defaults to False.

        Returns:
            str: transaction hash
        """
        logger.info(f"[SEND TO IOTA] Data: {transactions}")
        # Prepare transactions
        transfers = [
            ProposedTransaction(
                address=Address(transaction.address),
                message=TryteString.from_bytes(json.dumps(transaction.message).encode()),
                tag=Tag(transaction.tag.replace("_", "9")),
                value=0,
            )
            for transaction in transactions
        ]
        # Create adapter
        logger.info(f"[SEND TO IOTA] IOTA node: {node}")
        api = iota(adapter=node, local_pow=local_pow)
        # Send transactions to IOTA
        logger.info("[SEND TO IOTA] Sending...")
        bundle_result = api.send_transfer(transfers=transfers)["bundle"]
        logger.info("[SEND TO IOTA]            Done")
        # Transaction hash
        logger.info(
            f"[SEND TO IOTA] Transaction hash: {bundle_result.transactions[0].hash}, Bundle hash: {bundle_result.hash}"
        )
        # Show bundle result
        logger.debug(bundle_result.as_json_compatible())
        return str(bundle_result.transactions[0].hash)
 def test_fail_changeAddress_wrong_type(self):
     """
 ``changeAddress`` is not a TrytesCompatible value.
 """
     self.assertFilterErrors(
         {
             'changeAddress':
             42,
             'multisigInput':
             MultisigAddress(
                 digests=[self.digest_1, self.digest_2],
                 trytes=self.trytes_2,
             ),
             'transfers': [
                 ProposedTransaction(
                     address=Address(self.trytes_3),
                     value=42,
                 ),
             ],
         },
         {
             'changeAddress': [f.Type.CODE_WRONG_TYPE],
         },
     )
    async def test_error_unspent_inputs_no_change_address(self):
        """
    The bundle has unspent inputs, but no change address was specified.

    Unlike :py:meth:`iota.api.Iota.prepare_transfer` where all of the
    inputs are owned by the same seed, creating a multisig transfer
    usually involves multiple people.

    It would be unfair to the participants of the transaction if we
    were to automatically generate a change address using the seed of
    whoever happened to invoke the
    :py:meth:`MultisigIota.prepare_multisig_transfer` method!
    """
        self.adapter.seed_response(
            command=GetBalancesCommand.command,
            response={
                'balances': [101],
                'duration': 86,
            },
        )

        with self.assertRaises(ValueError):
            await self.command(
                transfers=[
                    ProposedTransaction(
                        address=Address(self.trytes_1),
                        value=42,
                    ),
                ],
                multisigInput=MultisigAddress(
                    digests=[self.digest_1, self.digest_2],
                    trytes=self.trytes_2,
                ),

                # changeAddress = Address(self.trytes_3),
            )
Example #18
0
def send_transfer(message):
    # Iota instance
    api = Iota(NODE_URL, SEED)

    # Txn description
    txn = ProposedTransaction(
        address=Address(receiver_address),
        message=TryteString.from_string(json.dumps(message)),
        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 bundle['bundle'].hash
    def test_pass_happy_path(self):
        """
    Request is valid.
    """
        request = {
            'changeAddress':
            Address(self.trytes_1),
            'multisigInput':
            MultisigAddress(
                digests=[self.digest_1, self.digest_2],
                trytes=self.trytes_2,
            ),
            'transfers': [
                ProposedTransaction(
                    address=Address(self.trytes_3),
                    value=42,
                ),
            ],
        }

        filter_ = self._filter(request)

        self.assertFilterPasses(filter_)
        self.assertDictEqual(filter_.cleaned_data, request)
1 iota will be transfered to the given address
'''

from iota import Iota
from iota import ProposedTransaction
from iota import Address
from iota import Tag
from iota import TryteString

# This is a demonstration seed, always generate your own seed!
seed = 'EDFCUGAMUKFUTSNERKXBVFTMRPGQRLFMYOHHSVCYDTZRJWULKHKRTGCEUMPD9NPFGWFTRTKLQSQRWZDMY'

# The address to send 1i
address = 'FEEDTHESHEEP999999999999999999999999999999999999999999999999999999999999999999999'

# Since we are sending value we need a seed to sign the transaction
api = Iota('https://nodes.devnet.iota.org:443', seed)

tx = ProposedTransaction(
    address=Address(address),
    message=TryteString.from_unicode('This transaction should include 1i!'),
    tag=Tag('VALUETX'),
    value=1)

tx = api.prepare_transfer(transfers=[tx])

result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9)

print('Transaction sent to the tangle!')
print('https://devnet.thetangle.org/address/%s' % address)
Example #21
0
def send_iota(data_crypt, data_summary, api, address):
    #FUNCION EMPLEADA PARA MANDAR LA TRANSACCION DE VALOR CERO A LA RED.

    data_def = ''
    #SE DECLARA UN STRING DONDE GUARDAREMOS CONSECUTIVAMENTE TODA LA INFORMACION
    #CIFRADA DE LOS CLIENTES. EL METODO DE ENCRIPTACION PERMITIRA SEPARARLO SIN
    #PROBLEMAS, COMO SE VE EN ESTE APARTADO, EN Lectura de datos de la red.

    t0 = time.time()
    #REGISTRO DE TIEMPO PARA LLEVAR UN CONTROL DEL PROCESO

    for i in range(3):
        #BUCLE EMPLEADO PARA CIFRAR CON LA CLAVE PUBLICA DE CADA CLIENTE SU PARTE
        #CORRESPONDIENTE DE LA LISTA data_crypt, QUE SE HA DEFINIDO EN LA OTRA FUNCION.

        path = '/home/pi/Documents/FJavierGb/ULTIMATES/Public_Key'
        path1 = path + str(i)
        path2 = path1 + '.py'
        #SISTEMA VASTO PARA ABRIR EL DOCUMENTO DONDE SE GUARDA LA LLAVE PUBLICA
        #DE CADA CLIENTE DENTRO DE LA RASPBERRY. LA DIRECCION DEBE SER FIJA UNA
        #VEZ SE IMPLANTE EL SISTEMA EN UN DISPOSITIVO.

        public_key = open(path2, 'r')
        pubk = public_key.read()
        #FUNCIONES EMPLEADAS PARA ABRIR Y GUARDAR EN LA VARIABLE pubk LA CLAVE
        #PUBLICA DEL CLIENTE ESPECIFICO EN CADA ITERACION.

        pubk1 = RSA.importKey(pubk)
        cipher1 = PKCS1_OAEP.new(pubk1)
        #FUNCIONES QUE PREPARAN EL ALGORITMO A UTILIZAR JUNTO A LA CLAVE PUBLICA
        #PARA ENCRIPTAR EL MENSAJE EN BYTES. VER APARTADO 3.3.

        data_crypt[i] = cipher1.encrypt(str(data_crypt[i]))
        #ENCRIPTA LA PARTE CORRESPONDIENTE DEL MENSAJE DE CADA CLIENTE CON SU
        #CLAVE PUBLICA. PREVIAMENTE, TODA LA LISTA QUE CORRESPONDE A CADA CLIENTE
        #SE TRANSFORMA EN UNA STRING PARA PODER CONVERTIRSE CORRECTAMENTE EN BYTES.

        public_key.close()
        #SE CIERRA EL DOCUMENTO DONDE SE ENCUENTRA LA LLAVE PUBLICA

        data_def = data_def + data_crypt[i]
        #UNE TODAS LAS PARTES ENCRIPTADAS EN UNA UNICA

    api.send_transfer(transfers=[
        ProposedTransaction(address=Address(address[0]),
                            message=TryteString.from_bytes(data_def),
                            tag=Tag(b'RPICTVFCOJAVIER'),
                            value=0,
                            timestamp=float(int(data_summary.iloc[5, 12])))
    ])
    #PAQUETE DE DATOS QUE ENVIAMOS AL NODO AL QUE ESTAMOS CONECTADOS. LOS ELEMENTOS
    #SE HAN EXPLICADO COMPLETAMENTE EN EL APARTADO 4.3. PERO CABE DESTACAR QUE
    #ES UNA TRANSACCION DE VALOR 0, QUE SE MANDA A NUESTRA PROPIA DIRECCION, QUE
    #SE EMPLEA UN TAG PROPIO DEL AUTOR Y QUE SE EMPLEA COMO TIMESTAMP LA FECHA
    #DE LA ULTIMA MEDIDA QUE SE TOMO DENTRO DEL DOCUMENTO.

    t1 = time.time()
    #REGISTRO DE TIEMPO PARA LLEVAR UN CONTROL DEL PROCESO
    t2 = t1 - t0
    #DIFERENCIA ENTRE AMBOS REGISTROS, QUE INDICA EL TIEMPO QUE HA TARDADO EN
    #REALIZARSE LA TRANSACCION.
    print('Enviado en:', t2)
Example #22
0
# Encode to base64, output contains only ASCII chars
b64_cipher = b64encode(cipher)

print('Constructing transaction locally...')
# Convert to trytes
trytes_encrypted_data = TryteString.from_bytes(b64_cipher)

# Generate an address from your seed to post the transfer to
my_address = api.get_new_addresses(index=42)['addresses'][0]

# Tag is optional here
my_tag = Tag(b'CONFIDENTIALINFORMATION')

# Prepare a transaction object
tx = ProposedTransaction(
    address=my_address,
    value=0,
    tag=my_tag,
    message=trytes_encrypted_data,
)

print('Sending transfer...')
# Send the transaction to the network
response = api.send_transfer([tx])

print('Check your transaction on the Tangle!')
print('https://utils.iota.org/transaction/%s/devnet' %
      response['bundle'][0].hash)
print('Tail transaction hash of the bundle is: %s' %
      response['bundle'].tail_transaction.hash)
Example #23
0
        b'UPYQLREUEUETMRIGNNYLHVJSUKJZCEOGMO9OPXSY9ZNWWKDTTNOGVOJVZBNCBLLXZZWLWWJMUQPADKES9'
    ),
    Address(
        b'NDGHOGDRXEXNFQOW9XQIYKYAUIEZMTZDQMPEQTSDHTQEKCIYYANZMGDOJBSRCNT9RBC9CJDTBVBFDQF99'
    ),
    Address(
        b'NZRHABYULAZM9KEXRQODGUZBLURTOKSGWWMOPIAJSTJFVAHNCCMJSVULRKGD9PLBMKOEGBNZRJHQSVVCA'
    ),
    Address(
        b'EECOCPAECTETNWT9ERFUJCFXQWRVXFZDWHSPSOOSLTDKKNYSVKTVZJASDV9HAYTNZSQIW99JLUYLQSFMY'
    )
]

# Prepare the original bundle
original_trytes = api.prepare_transfer(transfers=[
    ProposedTransaction(address=addys[0], value=0),
    ProposedTransaction(address=addys[1], value=0),
    ProposedTransaction(address=addys[2], value=0),
    ProposedTransaction(address=addys[3], value=0),
]).get('trytes')

gtta_response = api.get_transactions_to_approve(3)

trunk = gtta_response.get('trunkTransaction')
branch = gtta_response.get('branchTransaction')

attached_original_trytes = api.attach_to_tangle(trunk, branch,
                                                original_trytes).get('trytes')

# So we have the original bundle attached, time to construct the new one
# We need to re-attach, but take special care, so we dont use the api, rather we do it ourself
Example #24
0
        # If null, a random seed will be generated.
        seed=b'SEED9GOES9HERE',
    )

# Example of sending a transfer using the sandbox.
# For more information, see :py:meth:`Iota.send_transfer`.
# noinspection SpellCheckingInspection
iota.send_transfer(
    depth=100,

    # One or more :py:class:`ProposedTransaction` objects to add to the
    # bundle.
    transfers=[
        ProposedTransaction(
            # Recipient of the transfer.
            address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG'
                            b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR'),

            # Amount of IOTA to transfer.
            # This value may be zero.
            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, Tangle!'),
        ),
    ],
)
#!/usr/bin/python
from iota import Iota
from iota import Address, ProposedTransaction, ProposedBundle, Tag, Transaction
from iota import TryteString
from iota.crypto.signing import KeyGenerator

#
# Create a new bundle transaction
# Send from 42 iota account 2 to account 3
#

# Connect to the node
api = Iota('http://localhost:14265', "S9YOBZWUIHQFGHQCUOFCKHFR99IJMSZNNHUDXRAGDZKLGEBGPNDWROALSUODRJNMFFQHDVNISRMVMPVNE")

# Trx setup
output_trx = ProposedTransaction(
    address = Address("E9LVPMKJIAGCIPVKMUOYTQMSYAUQDUMEYUUCLXRQUWJJ9JXRDXQNGIOUPQVIMIWHFIRXD9QSYOP9KG9BWARSINOJ9W"),
    message = TryteString.from_string("Sending some money"),
    tag     = Tag("PACIFICSOUND"),
    value   = 42)

# Propagate
api.send_transfer(1, [output_trx])
Example #26
0
def batch_transfer(filename,
                   node_uri,
                   seed,
                   amount_of_seeds=100,
                   amount_per_seed=10000,
                   batch_size=25,
                   depth=3,
                   tag='GIFT',
                   message='',
                   pow_node_uri=None):
    needed_funds = amount_of_seeds * amount_per_seed
    print('You are about to spend %s iota spread out over %s addresses.' %
          (needed_funds, amount_of_seeds))
    print('Checking your seeds balance...')

    if pow_node_uri:
        router = RoutingWrapper(node_uri)
        router.add_route('attachToTangle', pow_node_uri)
        api = Iota(router, seed)
    else:
        api = Iota(node_uri, seed)

    inputs = api.get_inputs()
    balance = inputs['totalBalance']

    if balance < needed_funds:
        print(
            "You don't have enough funds available on your SEED, please make sure your seed has at least %si available!"
            % needed_funds)
        return

    print(
        'You have enough available to transfer the %si, Generating %d seeds and addresses now...'
        % (needed_funds, amount_of_seeds))

    seedlist = []
    for i in range(amount_of_seeds):
        random_seed = ''.join(
            [choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ9') for x in range(81)])
        gen = AddressGenerator(random_seed)
        new_addr = gen.get_addresses(0, 1, 2)[0]
        seedlist.append((random_seed, new_addr))
        print('.', sep='', end='', flush=True)

    print('\n')

    with open(filename, 'w') as fh:
        writer = csv.writer(fh)
        writer.writerow(['Seed', 'Address', 'Iota'])

        for gseed, gaddr in seedlist:
            writer.writerow([gseed, gaddr, amount_per_seed])

    print('All seeds and addresses are now available in %s!' % filename)

    amount_of_bundles = (amount_of_seeds // batch_size) + 1

    if amount_of_seeds % batch_size == 0:
        amount_of_bundles -= 1

    print(
        'We will generate and send %d bundles containing %d transactions per bundle max, this can take a while...'
        % (amount_of_bundles, batch_size))

    from_addr = None
    for i in range(amount_of_bundles):
        sliced = seedlist[i * batch_size:(i + 1) * batch_size]
        print('Starting transfer of bundle %d containing %d seeds...' %
              (i + 1, len(sliced)))

        transfers = []
        for gseed, gaddr in sliced:
            transfers.append(
                ProposedTransaction(
                    address=gaddr,
                    value=amount_per_seed,
                    tag=Tag(tag),
                    message=TryteString.from_string(message),
                ))

        bundle = api.send_transfer(depth=depth, transfers=transfers)

        for tx in bundle['bundle'].transactions:
            if tx.current_index == tx.last_index:
                print('Remainder:', tx.current_index, tx.address, tx.value)
                from_addr = tx.address

                if amount_per_seed == 0:
                    continue

                print(
                    'Waiting for the TX to confirm and the remainder address (%s) to fill...'
                    % tx.address)
                while True:
                    balances = api.get_balances([tx.address], 100)
                    if balances['balances'][0] > 0:
                        break
                    else:
                        print('...', sep='', end='', flush=True)

                    sleep(5)

                print('\n')

        print('Transfer complete.')

    print('All done!')
'''
This example creates a simple transaction with a custom message/tag
There is no value attached to this transaction.
'''

from iota import Iota
from iota import ProposedTransaction
from iota import Address
from iota import Tag
from iota import TryteString

# Note that we don't need a seed to send 0 value transactions since these
# transactions are not signed, we can publish to any address
api = Iota('https://nodes.devnet.iota.org:443')

address = 'TOKLOARHKXQCVPPVVIPIJGLUTLTKFHYGMBBLOXJFYGSARLOTYFFSDZNYCOBOCNPGRMJWZCQBNOROUCE9G'

tx = ProposedTransaction(address=Address(address),
                         message=TryteString.from_unicode('You did it!'),
                         tag=Tag('HELLOWORLD'),
                         value=0)

tx = api.prepare_transfer(transfers=[tx])

result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9)

print('Transaction sent to the tangle!')
print('https://devnet.thetangle.org/address/%s' % address)
Example #28
0
from iota import (
    __version__,
    Address,
    Iota,
    ProposedTransaction,
    Tag,
    TryteString,
)
from six import text_type

api = Iota('http://localhost:14265')
txn_2 =\
  ProposedTransaction(
    address =
      Address(
        b'FJHSSHBZTAKQNDTIKJYCZBOZDGSZANCZSWCNWUOCZXFADNOQSYAHEJPXRLOVPNOQFQXXGEGVDGICLMOXX'
      ),

    message = TryteString.from_unicode('thx fur cheezburgers'),
    tag     = Tag(b'KITTEHS'),
    value   = 0,
)

c = api.prepare_transfer([txn_2])["trytes"]

K = api.send_trytes(depth=3, trytes=c, min_weight_magnitude=9)
print('Transfer complete.')
print(c)
print('\n')
print(K["trytes"])
    async def test_unspent_inputs_with_change_address(self):
        """
    The bundle has unspent inputs, so it uses the provided change
    address.
    """
        self.adapter.seed_response(
            command=GetBalancesCommand.command,
            response={
                'balances': [101],
                'duration': 86,
            },
        )

        pmt_result =\
          await self.command(
            transfers = [
              ProposedTransaction(
                address = Address(self.trytes_1),
                value   = 42,
              ),
            ],

            multisigInput =
              MultisigAddress(
                digests = [self.digest_1, self.digest_2],
                trytes  = self.trytes_2,
              ),

            changeAddress = Address(self.trytes_3),
          )

        bundle = Bundle.from_tryte_strings(pmt_result['trytes'])

        self.assertEqual(len(bundle), 6)

        # Spend Transaction
        txn_1 = bundle[0]
        self.assertEqual(txn_1.address, self.trytes_1)
        self.assertEqual(txn_1.value, 42)

        # Input 1, Part 1 of 4
        txn_2 = bundle[1]
        self.assertEqual(txn_2.address, self.trytes_2)
        self.assertEqual(txn_2.value, -101)
        self.assertEqual(txn_2.signature_message_fragment, Fragment(b''))

        # Input 1, Part 2 of 4
        txn_3 = bundle[2]
        self.assertEqual(txn_3.address, self.trytes_2)
        self.assertEqual(txn_3.value, 0)
        self.assertEqual(txn_3.signature_message_fragment, Fragment(b''))

        # Input 1, Part 3 of 4
        txn_4 = bundle[3]
        self.assertEqual(txn_4.address, self.trytes_2)
        self.assertEqual(txn_4.value, 0)
        self.assertEqual(txn_4.signature_message_fragment, Fragment(b''))

        # Input 1, Part 4 of 4
        txn_5 = bundle[4]
        self.assertEqual(txn_5.address, self.trytes_2)
        self.assertEqual(txn_5.value, 0)
        self.assertEqual(txn_5.signature_message_fragment, Fragment(b''))

        # Change
        txn_6 = bundle[5]
        self.assertEqual(txn_6.address, self.trytes_3)
        self.assertEqual(txn_6.value, 59)
    async def test_happy_path(self):
        """
    Preparing a bundle with a multisig input.
    """
        self.adapter.seed_response(
            command=GetBalancesCommand.command,
            response={
                'balances': [42],

                # Would it be cheeky to put "7½ million years" here?
                'duration': 86,
            },
        )

        pmt_result =\
          await self.command(
            transfers = [
              ProposedTransaction(
                address = Address(self.trytes_1),
                value   = 42,
              ),
            ],

            multisigInput =
              MultisigAddress(
                digests = [self.digest_1, self.digest_2],
                trytes  = self.trytes_2,
              ),
          )

        # The command returns the raw trytes.  This is useful in a
        # real-world scenario because trytes are easier to transfer between
        # each entity that needs to apply their signature.
        #
        # However, for purposes of this test, we will convert the trytes
        # back into a bundle so that we can inspect the end result more
        # easily.
        bundle = Bundle.from_tryte_strings(pmt_result['trytes'])

        #
        # This bundle looks almost identical to what you would expect from
        # :py:meth:`iota.api.Iota.prepare_transfer`, except:
        # - There are 4 inputs (to hold all of the signature fragments).
        # - The inputs are unsigned.
        #
        self.assertEqual(len(bundle), 5)

        # Spend Transaction
        txn_1 = bundle[0]
        self.assertEqual(txn_1.address, self.trytes_1)
        self.assertEqual(txn_1.value, 42)

        # Input 1, Part 1 of 4
        txn_2 = bundle[1]
        self.assertEqual(txn_2.address, self.trytes_2)
        self.assertEqual(txn_2.value, -42)
        self.assertEqual(txn_2.signature_message_fragment, Fragment(b''))

        # Input 1, Part 2 of 4
        txn_3 = bundle[2]
        self.assertEqual(txn_3.address, self.trytes_2)
        self.assertEqual(txn_3.value, 0)
        self.assertEqual(txn_3.signature_message_fragment, Fragment(b''))

        # Input 1, Part 3 of 4
        txn_4 = bundle[3]
        self.assertEqual(txn_4.address, self.trytes_2)
        self.assertEqual(txn_4.value, 0)
        self.assertEqual(txn_4.signature_message_fragment, Fragment(b''))

        # Input 1, Part 4 of 4
        txn_5 = bundle[4]
        self.assertEqual(txn_5.address, self.trytes_2)
        self.assertEqual(txn_5.value, 0)
        self.assertEqual(txn_5.signature_message_fragment, Fragment(b''))