Example #1
0
  def test_checksum_valid(self):
    """
    An address is created with a valid checksum.
    """
    addy = Address(
      b'RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE'
      b'9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVAITCOXAQSD',
    )

    self.assertTrue(addy.is_checksum_valid())

    self.assertEqual(
      binary_type(addy.with_valid_checksum()),

      b'RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE'
      b'9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVAITCOXAQSD',
    )
Example #2
0
  def test_checksum_null(self):
    """
    An address is created without a checksum.
    """
    trytes = (
      b'ZKIUDZXQYQAWSHPKSAATJXPAQZPGYCDCQDRSMWWCGQJNI'
      b'PCOORMDRNREDUDKBMUYENYTFVUNEWDBAKXMV'
    )

    addy = Address(trytes)

    self.assertFalse(addy.is_checksum_valid())

    self.assertEqual(
      binary_type(addy.with_valid_checksum()),

      b'ZKIUDZXQYQAWSHPKSAATJXPAQZPGYCDCQDRSMWWCGQJNI'
      b'PCOORMDRNREDUDKBMUYENYTFVUNEWDBAKXMVJJJGBARPB',
    )
Example #3
0
  def test_with_checksum_attributes(self):
    """
    :py:meth:`Address.with_valid_checksum` also copies attributes such
    as key index and balance.
    """
    addy =\
      Address(
        trytes =
          b'ZKIUDZXQYQAWSHPKSAATJXPAQZPGYCDCQDRSMWWCGQJNI'
          b'PCOORMDRNREDUDKBMUYENYTFVUNEWDBAKXMV',

        key_index = 42,
        balance   = 86,
      )

    checked = addy.with_valid_checksum()

    self.assertEqual(checked.key_index, 42)
    self.assertEqual(checked.balance, 86)
Example #4
0
  def test_checksum_invalid(self):
    """
    An address is created with an invalid checksum.
    """
    trytes = (
      b'IGKUOZGEFNSVJXETLIBKRSUZAWMYSVDPMHGQPCETEFNZP'
      b'XSJLZMBLAWDRLUBWPIPKFNEPADIWMXMYYRKQ'
    )

    addy = Address(
      trytes + b'XYYNAFRMB' # <- Last tryte s/b 'A'.
    )

    self.assertFalse(addy.is_checksum_valid())

    self.assertEqual(
      binary_type(addy.with_valid_checksum()),

      b'IGKUOZGEFNSVJXETLIBKRSUZAWMYSVDPMHGQPCETEFNZP'
      b'XSJLZMBLAWDRLUBWPIPKFNEPADIWMXMYYRKQXYYNAFRMA',
    )
Example #5
0
  def _apply(self, value):
    super(AddressNoChecksum, self)._apply(value)

    if self._has_errors:
      return None

    # Possible it's still just a TryteString
    if not isinstance(value, Address):
      value = Address(value)

    # Bail out if we have a bad checksum
    if value.checksum and not value.is_checksum_valid():
      return self._invalid_value(
        value     = value,
        reason    = self.ADDRESS_BAD_CHECKSUM,
        exc_info  = True,

        context = {
          'supplied_checksum': value.checksum,
          'expected_checksum': value.with_valid_checksum().checksum,
        },
      )
    return Address(value.address)
Example #6
0
  def address_from_digest(digest):
    # type: (Digest) -> Address
    """
    Generates an address from a private key digest.
    """
    address_trits = [0] * (Address.LEN * TRITS_PER_TRYTE) # type: MutableSequence[int]

    sponge = Kerl()
    sponge.absorb(digest.as_trits())
    sponge.squeeze(address_trits)

    return Address.from_trits(
      trits = address_trits,

      key_index       = digest.key_index,
      security_level  = digest.security_level,
    )
    def test_fail_transfers_empty(self):
        """
    ``transfers`` is an array, but it's empty.
    """
        self.assertFilterErrors(
            {
                'changeAddress':
                Address(self.trytes_1),
                'multisigInput':
                MultisigAddress(
                    digests=[self.digest_1, self.digest_2],
                    trytes=self.trytes_2,
                ),

                # This is a variation on the ``null`` test.
                'transfers': [],
            },
            {
                'transfers': [f.Required.CODE_EMPTY],
            },
        )
Example #8
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 #9
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 #10
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.
        # noinspection SpellCheckingInspection
        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 #11
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()
class IotaApiUser(IotaUser):
    wait_time = between(0, 1)
    address = 'ZLGVEQ9JUZZWCZXLWVNTHBDX9G9KZTJP9VEERIIFHY9SIQKYBVAHIMLHXPQVE9IXFDDXNHQINXJDRPFDXNYVAPLZAW'
    message = TryteString.from_unicode('Hello world')
    tx = ProposedTransaction(address=Address(address),
                             message=message,
                             value=0)

    @task
    def send_msg(self):
        result = self.client.send_transfer(transfers=[self.tx])

    @task(0)
    def prepare_transfer(self):
        tx_trytes = self.client.prepare_transfer(transfers=[self.tx])

    @task(0)
    def send_trytes(self):
        api = Iota(adapter="http://localhost:14265", testnet=True)
        tx_trytes = api.prepare_transfer(transfers=[self.tx])
        resp_sendTrytes = self.client.send_trytes(trytes=tx_trytes['trytes'])
Example #13
0
    def test_add_signature_or_message_finalized_bundle(self):
        """
    Try to call the method on a finalized bundle.
    """
        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)

        # Finalize the bundle, no further changes should be permitted.
        self.bundle.finalize()

        with self.assertRaises(RuntimeError):
            self.bundle.add_signature_or_message([custom_fragment])
Example #14
0
    def test_pass_compatible_types(self):
        """
    The incoming request contains values that can be converted to the
    expected types.
    """
        request = {
            'addresses': [
                Address(self.address_1),
                bytearray(self.address_2.encode('ascii')),
            ],
        }

        filter_ = self._filter(request)

        self.assertFilterPasses(filter_)
        self.assertDictEqual(
            filter_.cleaned_data,
            {
                'addresses': [self.address_1, self.address_2],
            },
        )
Example #15
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 #16
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()]
    )
Example #17
0
    def test_add_checksum_second_time(self):
        """
    Checksum is added to an address that already has.
    """
        addy = Address(trytes=b'ZKIUDZXQYQAWSHPKSAATJXPAQZPGYCDCQDRSMWWCGQJNI'
                       b'PCOORMDRNREDUDKBMUYENYTFVUNEWDBAKXMVJJJGBARPB')

        addy.add_checksum()

        self.assertTrue(addy.is_checksum_valid())
        self.assertTrue(len(addy) == Address.LEN + AddressChecksum.LEN)

        self.assertEqual(
            addy,
            Address(trytes=b'ZKIUDZXQYQAWSHPKSAATJXPAQZPGYCDCQDRSMWWCGQJNI'
                    b'PCOORMDRNREDUDKBMUYENYTFVUNEWDBAKXMVJJJGBARPB'))
Example #18
0
  def test_finalize_insecure_bundle(self):
    """
    When finalizing, the bundle detects an insecure bundle hash.

    References:
      - https://github.com/iotaledger/iota.py/issues/84
    """
    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.
    self.assertEqual(bundle[0].legacy_tag, Tag('ZTDIDNQDJZGUQKOWJ9JZRCKOVGP'))

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

    # The bundle hash takes the modified legacy tag into account.
    self.assertEqual(
      bundle.hash,

      BundleHash(
        'NYSJSEGCWESDAFLIFCNJFWGZ9PCYDOT9VCSALKBD'
        '9UUNKBJAJCB9KVMTHZDPRDDXC9UFJQBJBQFUPJKFC',
      )
    )
Example #19
0
    def test_success_multiple_digests(self):
        """
    Generating a multisig address from multiple digests.
    """
        builder = MultisigAddressBuilder()
        builder.add_digest(self.digest_1)
        builder.add_digest(self.digest_2)
        addy = builder.get_address()

        self.assertIsInstance(addy, MultisigAddress)

        # noinspection SpellCheckingInspection
        self.assertEqual(
            addy,
            Address(
                b'JUIFYSUQFVBFGNHOJMLWBHMGASFGBPAUMRZRRCJF'
                b'CCOJHJKZVUOCEYSCLXAGDABCEWSUXCILJCGQWI9SF', ),
        )

        # The multisig address also keeps track of the digests used to
        # create it (mostly for troubleshooting purposes).
        self.assertListEqual(addy.digests, [self.digest_1, self.digest_2])
Example #20
0
    def Send(self, Receiver_Address, Message):
        if isinstance(Message, bytes):
            Message = Message.decode()
        Trytes_Convertion = TryteString.from_string(Message)
        TX = ProposedTransaction(address = Address(Receiver_Address), message = Trytes_Convertion, value = 0)
        bundle = ProposedBundle()
        bundle.add_transaction(TX)
        bundle.finalize()
        TX_Hash = str(bundle.hash)
        bundle_as_trytes = bundle.as_tryte_strings()
        TX_Success = False
        try:
            TX_Confirmation = self.IOTA_Api.send_trytes(trytes = bundle_as_trytes, depth = 4)
            TX_Success = TX_Hash
        except:
            if "iota.adapter.BadApiResponse" in str(sys.exc_info()[1]):
                print("Node not in Sync, finding another node....") #< ----------------------------------------------------

            elif "The subtangle has not been updated yet." in str(sys.exc_info()[1]):
                print("Node not synced yet, finding another node...") #< ----------------------------------------------------

            elif "429 response from node"in str(sys.exc_info()[1]):
                print("Too many requests to node, finding an alternative node...") #< ----------------------------------------------------

            elif "[Errno 111] Connection refused" in str(sys.exc_info()[1]):
                print("Connection error, finding an alternative node...") #< ----------------------------------------------------

            elif "403 Forbidden" in str(sys.exc_info()[1]):
                print("No access granted to node, finding an alternative node...") #< ----------------------------------------------------
                # special case; a node accepts with POW set to "True"

            elif "certificate verify failed" in str(sys.exc_info()[1]):
                print("Node does not have a valid SSL certificate, finding an alternative node...")

            else:
                print("Unexpected exception caught in send") #< ----------------------------------------------------
                print(sys.exc_info()[1]) #< ----------------------------------------------------

        return TX_Success
def send(value):
    api = Iota("http://localhost:14265")
    ti = time.time()
    api.send_transfer(
        depth=3,
        transfers=[
            ProposedTransaction(
                # Recipient of the transfer.
                address=Address(
                    "RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999"
                ),
                value=value,

                # 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=9)
    print(time.time() - ti)
Example #22
0
    def sendiota(self, address, amount):
        self.api.send_transfer(
            depth=100,

            # 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.
                    # This value may be zero.
                    value=amount,
                    # Optional tag to attach to the transfer.
                    tag=Tag(b'EXAMPLEK'),
                    # Optional message to include with the transfer.
                    message=TryteString.from_string('Hello!'),
                ),
            ],
        )
Example #23
0
    def test_fail_signature_fragment_address_wrong(self):
        """
    The second signature fragment for an input is associated with the
    wrong address.
    """
        # noinspection SpellCheckingInspection
        self.bundle[2].address =\
          Address(
            b'QHEDFWZULBZFEOMNLRNIDQKDNNIELAOXOVMYEI9P'
            b'GNFDPEEZCWVYLKZGSLCQNOFUSENIXRHWWTZFBXMPS'
          )

        validator = BundleValidator(self.bundle)

        self.assertFalse(validator.is_valid())

        self.assertListEqual(
            validator.errors,
            [
                'Transaction 1 has invalid signature (using 1 fragments).',
            ],
        )
Example #24
0
    def test_success_multiple_digests(self):
        """
    Generating a multisig address from multiple digests.
    """
        builder = MultisigAddressBuilder()
        builder.add_digest(self.digest_1)
        builder.add_digest(self.digest_2)
        addy = builder.get_address()

        self.assertIsInstance(addy, MultisigAddress)

        # noinspection SpellCheckingInspection
        self.assertEqual(
            addy,
            Address(
                b'ZYKDKGXTMGINTQLUMVNBBI9XCEI9BWYF9YOPCBFT'
                b'UUJZWM9YIWHNYZEWOPEVRVLKZCPRKLCQD9BR9FVLC', ),
        )

        # The multisig address also keeps track of the digests used to
        # create it (mostly for troubleshooting purposes).
        self.assertListEqual(addy.digests, [self.digest_1, self.digest_2])
Example #25
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.
        # 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(ValueError):
            # You can't sign the spend transaction, silly!
            self.bundle.sign_input_at(0, private_key)
    def test_fail_transfers_null(self):
        """
    ``transfers`` is null.
    """
        self.assertFilterErrors(
            {
                'changeAddress':
                Address(self.trytes_1),
                'multisigInput':
                MultisigAddress(
                    digests=[self.digest_1, self.digest_2],
                    trytes=self.trytes_2,
                ),

                # On second thought, I changed my mind.
                'transfers':
                None,
            },
            {
                'transfers': [f.Required.CODE_EMPTY],
            },
        )
Example #27
0
def transfer(message):
    address = "KTTAJJPDQBXDYFFSYNV9BVREJFGXIGNISDWD9RFHSBWZOBI9GXPXFGGLDOZLGTEZCTBXDCWUZZVYMYC9Y"
    tag = "JDIWHUEFE9S"
    value = 0

    recipient_address = address
    sender_message = message
    sender_tag = tag

    bundle_hash = ""
    prepared_transferes = []
    api = Iota(NODE_URL, 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)
    try:
        bundle_hash = api.send_transfer(
            depth=DEPTH,
            transfers=prepared_transferes,
            min_weight_magnitude=MIN_WEIGHT_MAGNITUDE)
    except Exception as e:
        print "Exception on TangleID transaction agent." + str(e)
        return "Exception on TangleID transaction agent."

    return str(bundle_hash['bundle'].hash)
Example #28
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
    )
Example #29
0
    def test_init_with_checksum(self):
        """
    Creating an address with checksum already attached.
    """
        addy = Address(b'RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE'
                       b'9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVAFOXM9MUBX')

        self.assertEqual(
            binary_type(addy),
            b'RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE'
            b'9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVAFOXM9MUBX',
        )

        self.assertEqual(
            binary_type(addy.address),
            b'RVORZ9SIIP9RCYMREUIXXVPQIPHVCNPQ9HZWYKFWYWZRE'
            b'9JQKG9REPKIASHUUECPSQO9JT9XNMVKWYGVA',
        )

        self.assertEqual(
            binary_type(addy.checksum),
            b'FOXM9MUBX',
        )
    async 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):
            await 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 #31
0
  def from_tryte_string_and_hash(cls, trytes,hash):
    # type: (TrytesCompatible) -> Transaction
    """
    Creates a Transaction object from a sequence of trytes.
    """
    tryte_string = TransactionTrytes(trytes)

    hash_ = hash

    return cls(
      hash_=TransactionHash(hash_),
      signature_message_fragment=Fragment(tryte_string[0:2187]),
      address=Address(tryte_string[2187:2268]),
      value=int_from_trits(tryte_string[2268:2295].as_trits()),
      tag=Tag(tryte_string[2295:2322]),
      timestamp=int_from_trits(tryte_string[2322:2331].as_trits()),
      current_index=int_from_trits(tryte_string[2331:2340].as_trits()),
      last_index=int_from_trits(tryte_string[2340:2349].as_trits()),
      bundle_hash=BundleHash(tryte_string[2349:2430]),
      trunk_transaction_hash=TransactionHash(tryte_string[2430:2511]),
      branch_transaction_hash=TransactionHash(tryte_string[2511:2592]),
      nonce=Hash(tryte_string[2592:2673]),
    )
Example #32
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 #33
0
def main():
    api = Iota("http://localhost:14265")

    # In this file, we tranfer tokens with 0-value; thus the seed can be ignored.
    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)
Example #34
0
    def test_success_single_digest(self):
        """
    Generating a "multisig" address from a single digest.

    This does the same thing as generating a regular address from the
    corresponding key.
    """
        builder = MultisigAddressBuilder()
        builder.add_digest(self.digest_1)
        addy = builder.get_address()

        self.assertIsInstance(addy, MultisigAddress)

        self.assertEqual(
            addy,
            Address(
                b'TBOLOKTNJ9MFGBSJBIWDZBHWJRLMKAEGUZFJFNGS'
                b'VODKPPULLGJVHTCENCD9OOCNYPRLV9XGBGLDZNHPZ', ),
        )

        # The address is still designated multisig, so we keep track of the
        # digest used to generate it.
        self.assertListEqual(addy.digests, [self.digest_1])
Example #35
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 #36
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)