Esempio n. 1
0
    def test_get_addresses_single(self):
        """
    Generating a single address.
    """
        ag = AddressGenerator(self.seed_1)

        # noinspection SpellCheckingInspection
        self.assertListEqual(
            ag.get_addresses(start=0),
            [
                Address(
                    b'DLEIS9XU9V9T9OURAKDUSQWBQEYFGJLRPRVEWKN9'
                    b'SSUGIHBEIPBPEWISSAURGTQKWKWNHXGCBQTWNOGIY', ),
            ],
        )

        # noinspection SpellCheckingInspection
        self.assertListEqual(
            ag.get_addresses(start=10),
            [
                Address(
                    b'XLXFTFBXUOOHRJDVBDBFEBDQDUKSLSOCLUYWGLAP'
                    b'R9FUROUHPFINIUFKYSRTFMNWKNEPDZATWXIVWJMDD', ),
            ],
        )
Esempio n. 2
0
  def test_generator_with_offset(self):
    """
    Creating a generator that starts at an offset greater than 0.
    """
    ag = AddressGenerator(self.seed_1)

    generator = ag.create_iterator(start=1, step=2)

    # noinspection SpellCheckingInspection
    self.assertEqual(
      next(generator),

      Address(
        b'PNLOTLFSALMICK9PSW9ZWLE9KJAKPKGJZQJDAFMO'
        b'VLHXMJCJXFPVHOTTOYDIAUAYELXKZWZUITCQBIQKY',
      ),
    )

    # noinspection SpellCheckingInspection
    self.assertEqual(
      next(generator),

      Address(
        b'IWWMMHBFWCWOZQLBNXDJ9OOTIGXXU9WNUHFGUZWR'
        b'9FWGIUUUQUECHPKXJLIEKZBOVSEA9BCT9DLOCNCEC',
      ),
    )
Esempio n. 3
0
    def test_get_addresses_multiple(self):
        """
    Generating multiple addresses in one go.
    """
        ag = AddressGenerator(self.seed_2)

        self.assertListEqual(
            ag.get_addresses(start=0, count=3),
            [
                Address(
                    b'FNKCVJPUANHNWNBAHFBTCONMCUBC9KCZ9EKREBCJ'
                    b'AFMABCTEPLGGXDJXVGPXDCFOUCRBWFJFLEAVOEUPY', ),
                Address(
                    b'MSYILYYZLSJ99TDMGQHDOBWGHTBARCBGJZE9PIMQ'
                    b'LTEXJXKTDREGVTPA9NDGGLQHTMGISGRAKSLYPGWMB', ),
                Address(
                    b'IIREHGHXUHARKVZDMHGUUCHZLUEQQULLEUSJHIIB'
                    b'WFYZIZDUFTOVHAWCKRJXUZ9CSUVLTRYSUGBVRMTOW', ),
            ],
        )

        self.assertListEqual(
            ag.get_addresses(start=10, count=3),
            [
                Address(
                    b'BPXMVV9UPKBTVPJXPBHHOJYAFLALOYCGTSEDLZBH'
                    b'NFMGEHREBQTRIPZAPREANPMZJNZZNCDIUFOYYGGFY', ),
                Address(
                    b'RUCZQJWKXVDIXTLHHOKGMHOV9AKVDBG9HUQHPWNZ'
                    b'UNKJNFVMULUSLKFJGSTBSNJMRYSJOBVBQSKVXISZB', ),
                Address(
                    b'FQAKF9XVCLTBESJKWCHFOCTVABYEEJP9RXUVAEUW'
                    b'ENFUUQK9VCHFEORHCYDUJQHNUDWNRDUDZTUGKHSPD', ),
            ],
        )
Esempio n. 4
0
def clientthread(conn, addr):
    global address_num
    global seed
    conn.send("Connected to the PONG Server")
    client_num = address_num
    address_num = address_num + 1
    file = open("pong.conf", "w")
    file.write(str(address_num))
    file.close()
    generator = AddressGenerator(seed, 1, True)
    addresses = generator.get_addresses(client_num, count=1)[0]
    conn.send(str(addresses))

    while True:
        try:
            message = conn.recv(2048)
            if message:

                print "<" + addr[0] + "> " + message
                broadcast(message, conn)

            else:
                remove(conn)

        except KeyboardInterrupt:
            server.close()
        except:
            continue
Esempio n. 5
0
  def test_security_level_lowered(self):
    """
    Generating addresses with a lower security level.
    """
    ag = AddressGenerator(self.seed_1, security_level=1)

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=0, count=3),

      [
        Address(
          b'KNDWDEEWWFVZLISLYRABGVWZCHZNZLNSEJXFKVGA'
          b'UFLL9UMZYEZMEJB9BDLAASWTHEKFREUDIUPY9ICKW',
        ),

        Address(
          b'CHOBTRTQWTMH9GWFWGWUODRSGPOJOIVJUNIQIBZL'
          b'HSWNYPHOD9APWJBMJMGLHFZENWFKDYWHX9JDFXTAB',
        ),

        Address(
          b'YHTOYQUCLDHAIDILFNPITVPYSTOCFAZIUNDYTRDZ'
          b'CVMVGZPONPINNVPJTOAOKHHZWLOKIZPVASTOGAKPA',
        ),
      ],
    )
Esempio n. 6
0
  def test_generator_checksum(self):
    """
    Creating a generator with checksums on the addresses.
    """
    ag = AddressGenerator(
       self.seed_2,
       security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL,
       checksum=True
    )

    generator = ag.create_iterator()

    # noinspection SpellCheckingInspection
    self.assertEqual(
      next(generator),

      Address(
        b'FNKCVJPUANHNWNBAHFBTCONMCUBC9KCZ9EKREBCJ'
        b'AFMABCTEPLGGXDJXVGPXDCFOUCRBWFJFLEAVOEUPY'
        b'ADHVCBXFD',
      ),
    )

    # noinspection SpellCheckingInspection
    self.assertEqual(
      next(generator),

      Address(
        b'MSYILYYZLSJ99TDMGQHDOBWGHTBARCBGJZE9PIMQ'
        b'LTEXJXKTDREGVTPA9NDGGLQHTMGISGRAKSLYPGWMB'
        b'WIKQRCIOD',
      ),
    )
Esempio n. 7
0
    def _find_addresses(self, seed, index, count, security_level, checksum):
        # type: (Seed, int, Optional[int], int, bool) -> List[Address]
        """
        Find addresses matching the command parameters.
        """
        generator = AddressGenerator(seed, security_level, checksum)

        if count is None:
            # Connect to Tangle and find the first unused address.
            for addy in generator.create_iterator(start=index):
                # We use addy.address here because the commands do
                # not work on an address with a checksum
                response = WereAddressesSpentFromCommand(self.adapter)(
                    addresses=[addy.address], )
                if response['states'][0]:
                    continue

                response = FindTransactionsCommand(self.adapter)(
                    addresses=[addy.address], )
                if response.get('hashes'):
                    continue

                return [addy]

        return generator.get_addresses(start=index, count=count)
Esempio n. 8
0
  def test_security_level_elevated(self):
    """
    Generating addresses with a higher security level.
    """
    ag = AddressGenerator(self.seed_1, security_level=3)

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=0, count=3),

      [
        Address(
          b'BGHTGOUKKNTYFHYUAAPSRUEVN9QQXFOGVCH9Y9BO'
          b'NWXUBDLSKAWEOFZIVMHXBAYVPGDZEYCKNTUJCLPAX',
        ),

        Address(
          b'EGMRJEUIYFUGWAIXXZCHCZUVUUYITICVHDSHCQXG'
          b'FHJIVDCLTI9ZVRIKRLZQWW9CPOIXVDCBAHVGLUHI9',
        ),

        Address(
          b'ENPSARVJZGMMPWZTAIRHADEOZCEVIFNJWSZQHNEI'
          b'RVEVI9GYMFNEOGNUYCPGPSEFCSDHUHOQKDPVGDKYC',
        ),
      ],
    )
Esempio n. 9
0
    def test_generator_checksum(self):
        """
    Creating a generator with checksums on the addresses.
    """
        ag = AddressGenerator(
            self.seed_2,
            security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL,
            checksum=True)

        generator = ag.create_iterator()

        # noinspection SpellCheckingInspection
        self.assertEqual(
            next(generator),
            Address(
                b'FNKCVJPUANHNWNBAHFBTCONMCUBC9KCZ9EKREBCJ'
                b'AFMABCTEPLGGXDJXVGPXDCFOUCRBWFJFLEAVOEUPY'
                b'ADHVCBXFD', ),
        )

        # noinspection SpellCheckingInspection
        self.assertEqual(
            next(generator),
            Address(
                b'MSYILYYZLSJ99TDMGQHDOBWGHTBARCBGJZE9PIMQ'
                b'LTEXJXKTDREGVTPA9NDGGLQHTMGISGRAKSLYPGWMB'
                b'WIKQRCIOD', ),
        )
Esempio n. 10
0
  def test_get_addresses_single(self):
    """
    Generating a single address.
    """
    ag = AddressGenerator(self.seed_1)

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=0),

      [
        Address(
          b'DLEIS9XU9V9T9OURAKDUSQWBQEYFGJLRPRVEWKN9'
          b'SSUGIHBEIPBPEWISSAURGTQKWKWNHXGCBQTWNOGIY',
        ),
      ],
    )

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=10),

      [
        Address(
          b'XLXFTFBXUOOHRJDVBDBFEBDQDUKSLSOCLUYWGLAP'
          b'R9FUROUHPFINIUFKYSRTFMNWKNEPDZATWXIVWJMDD',
        ),
      ],
    )
Esempio n. 11
0
 def address(self):
     addresses = AddressGenerator(seed=self.seed,
                                  checksum=False,
                                  security_level=3)
     main_address = addresses.get_addresses(0, 1)
     main = str(main_address[0])
     return main
def CreateAddress():
    print("\nWelcome to IOTA addresses generator!")

    seed = InputSeed()
    if seed == None:
        return

    index = InputIndex()
    if index == None:
        return
    index = int(index)

    address_amount = InputAddressAmount()
    if address_amount == None:
        return
    address_amount = int(address_amount)

    generator = AddressGenerator(seed)
    addresses = generator.get_addresses(start=index,
                                        count=address_amount,
                                        step=1)

    offset = 0
    for address in addresses:
        print("\nYour Address #%d: %s" % (index + offset, address))
        print("\n                  https://thetangle.org/address/%s" %
              (address))
        offset += 1

    print()
Esempio n. 13
0
    def _generate_addresses(self, count):
        """
        Generate addresses for user

        :param count:
        """
        index_list = [-1]
        for i in range(0, len(self.addresses)):
            index_list.append(self.addresses[i].index)

        if max(index_list) == -1:
            start_index = 0
        else:
            start_index = max(index_list) + 1

        generator = AddressGenerator(self.seed)
        generated = generator.get_addresses(start_index, count)
        i = 0

        while i < count:
            index = start_index + i
            address = address_checksum(str(generated[i]))
            balance = address_balance(current_app.config['IOTA_HOST'], address)
            addr = IOTAAddress(index=index,
                               address=str(address),
                               balance=balance,
                               checksum=str(get_checksum(address, self.seed)))
            addr.save()
            self.addresses.append(addr)
            i += 1
        self.save()
Esempio n. 14
0
    def generate_addresses(self, count):
        """
        Generates one or more addresses and saves them in the account file

        :param count:
        :return:
        """
        index_list = [-1]
        for data in self._data['account_data'][0]['address_data']:
            index = data["index"]
            index_list.append(index)

        if max(index_list) == -1:
            start_index = 0
        else:
            start_index = max(index_list) + 1
        generator = AddressGenerator(self._seed)
        addresses = generator.get_addresses(
            start_index,
            count)  # This is the actual function to generate the address.
        i = 0

        while i < count:
            index = start_index + i
            address = addresses[i]
            balance = address_balance(
                self._data['account_data'][0]['settings'][0]['host'], address)
            self._write_address_data(index, str(address), balance)
            i += 1

        self._update_fal_balance()
Esempio n. 15
0
    def test_get_addresses_multiple(self):
        """
    Generating multiple addresses in one go.
    """
        ag = AddressGenerator(self.seed_2)

        # noinspection SpellCheckingInspection
        self.assertListEqual(
            ag.get_addresses(start=0, count=3),
            [
                Address(b'SZWZMYQYWGXWAAVQSDTIOFGTZP9PWIDDUHHNGRDP'
                        b'RCGNSXRNYWBEZIORKNNLNZHJ9QYMFYZIJJ9RFPBJT'),
                Address(b'N9KY9HCT9VTI99FFRIIBHQZIJOVSLFVWPOIFSHWL'
                        b'CCIVYLIDBKJLVQFYJNPIUNATUUCIRHUHNLFBCAXIY'),
                Address(b'BH9BWJWHIHLJSHBYBENHLQQBOCQOOMAEJJFFBCSE'
                        b'IMDVPDULGD9HBPNQKWBPM9SIDIMGUOGTPWMQSVVHZ'),
            ],
        )

        # noinspection SpellCheckingInspection
        self.assertListEqual(
            ag.get_addresses(start=10, count=3),
            [
                Address(
                    b'CCKZUWMILLQLLLIFNXBFGGPXFHNROQQOYYBMLIEOLB'
                    b'PVIVFJMQAVCCGKVGNRTKAZQLKYWMTBUEVBPGZMN', ),
                Address(
                    b'XWXALLEBVQXVRYLGPPJUL9RAIUKUXERBEMVTZJOMRB'
                    b'CGXNYA99PN9DKOPAWDSIPIRUBKFQUBQFUOKZMQW', ),
                Address(
                    b'CLYKQDU9WRHEJZSLMZKVDIWLHZKEIITWXDAHFFSQCP'
                    b'LADQKLUQLSECZMIOUDSLXRWEDAEHKRVWQRGZMLI', ),
            ],
        )
Esempio n. 16
0
    def test_get_addresses_single(self):
        """
    Generating a single address.
    """
        ag = AddressGenerator(self.seed_1)

        # noinspection SpellCheckingInspection
        self.assertListEqual(
            ag.get_addresses(start=0),
            [
                Address(
                    b'NWQBMJEBSYFCRKGLNUQZJIOQOMNMYPCIRVSVJLP9'
                    b'OFV9CZ99LFGZHDKOUDGRVJXUDPUPCVOQBKSZLPU9K', ),
            ],
        )

        # noinspection SpellCheckingInspection
        self.assertListEqual(
            ag.get_addresses(start=10),
            [
                Address(
                    b'AQNURLEH9IRPVDWNRLO9JHSY9OWTKHKIJOWSPKPW'
                    b'RQLMUI9KOGSXMONCXPEJMRK9MPYQXKZLNYJXNDUUZ', ),
            ],
        )
Esempio n. 17
0
    async def _find_addresses(self, seed: Seed, index: int,
                              count: Optional[int], security_level: int,
                              checksum: bool) -> List[Address]:
        """
        Find addresses matching the command parameters.
        """
        generator = AddressGenerator(seed, security_level, checksum)

        if count is None:
            # Connect to Tangle and find the first unused address.
            for addy in generator.create_iterator(start=index):
                # We use addy.address here because the commands do
                # not work on an address with a checksum
                # Execute two checks concurrently
                responses = await asyncio.gather(
                    WereAddressesSpentFromCommand(self.adapter)(
                        addresses=[addy.address], ),
                    FindTransactionsCommand(self.adapter)(
                        addresses=[addy.address], ),
                )
                # responses[0] -> was it spent from?
                # responses[1] -> any transaction found?
                if responses[0]['states'][0] or responses[1].get('hashes'):
                    continue

                return [addy]

        return generator.get_addresses(start=index, count=count)
Esempio n. 18
0
  def test_generator(self):
    """
    Creating a generator.
    """
    ag = AddressGenerator(self.seed_2)

    generator = ag.create_iterator()

    # noinspection SpellCheckingInspection
    self.assertEqual(
      next(generator),

      Address(
        b'FNKCVJPUANHNWNBAHFBTCONMCUBC9KCZ9EKREBCJ'
        b'AFMABCTEPLGGXDJXVGPXDCFOUCRBWFJFLEAVOEUPY',
      ),
    )

    # noinspection SpellCheckingInspection
    self.assertEqual(
      next(generator),

      Address(
        b'MSYILYYZLSJ99TDMGQHDOBWGHTBARCBGJZE9PIMQ'
        b'LTEXJXKTDREGVTPA9NDGGLQHTMGISGRAKSLYPGWMB',
      ),
    )
Esempio n. 19
0
 def __init__(self):
     conf = ConfigParser()
     path = os.path.join(os.path.dirname(__file__), 'config/config.txt')
     conf.read(path)
     self.iota = Iota(conf.get('IOTA', 'node'), conf.get('IOTA', 'seed'))
     self.generator = AddressGenerator(self.iota.seed)
     self.match_making_addr = self.generator.get_addresses(1)
     self.memcached = base.Client(('127.0.0.1', 11211))
Esempio n. 20
0
def generate_address(num):
    seed = b"N9MOJKSFIHTPRIBYDIWEHLRNBLNFSLWPVNYTEGBIRAOZRJSIBXDNCDBVPSEJRFVRSMISGQMSLAGZEVQTR"
    generator = AddressGenerator(seed=seed, security_level=2)
    results = generator.get_addresses(0, num+2)
    with open('./Snapshot.txt', 'w') as fs:
        for i in range(0, num+1):
            fs.write(str(results[i]) + ';' + '1000000000\n')
        fs.write(str(results[num+1]) +';' + str(2779530283277761-1000000000*(num+1)))
Esempio n. 21
0
  def test_get_addresses_error_step_zero(self):
    """
    Providing a ``step`` value of 0 to ``get_addresses``.
    """
    ag = AddressGenerator(seed=b'')

    with self.assertRaises(ValueError):
      ag.get_addresses(start=0, step=0)
Esempio n. 22
0
    def test_get_addresses_error_step_zero(self):
        """
    Providing a ``step`` value of 0 to ``get_addresses``.
    """
        ag = AddressGenerator(seed=b'')

        with self.assertRaises(ValueError):
            ag.get_addresses(start=0, step=0)
Esempio n. 23
0
def generate_addresses(count=1, seed=None):
    """Generates a number of IOTA addresses (given by count and optional seed)
    Returns: (address, seed)
    """
    if seed is None:
        seed = Seed.random()

    generator = AddressGenerator(seed=seed, security_level=security_level)
    return (generator.get_addresses(0, count), seed) # index, count
Esempio n. 24
0
def generator():
	
	chars=u'9ABCDEFGHIJKLMNOPQRSTUVWXYZ' #27 characters - max number you can express by one Tryte - do you remember?
	rndgenerator = random.SystemRandom()

	MySeed = u''.join(rndgenerator.choice(chars) for _ in range(81))

	generator = AddressGenerator(seed=MySeed, security_level=2)
	addresses = generator.get_addresses(0, 3) #index, count
	return(addresses)
Esempio n. 25
0
  def test_get_addresses_error_count_too_small(self):
    """
    Providing a ``count`` value less than 1 to ``get_addresses``.

    :py:class:`AddressGenerator` can potentially generate an infinite
    number of addresses, so there is no "end" to offset against.
    """
    ag = AddressGenerator(seed=b'')

    with self.assertRaises(ValueError):
      ag.get_addresses(start=0, count=0)
Esempio n. 26
0
    def test_get_addresses_error_count_too_small(self):
        """
    Providing a ``count`` value less than 1 to ``get_addresses``.

    :py:class:`AddressGenerator` can potentially generate an infinite
    number of addresses, so there is no "end" to offset against.
    """
        ag = AddressGenerator(seed=b'')

        with self.assertRaises(ValueError):
            ag.get_addresses(start=0, count=0)
Esempio n. 27
0
 def __init__(self, name, initBal=100):
     self.name = name
     self.bal = initBal
     self.seed = iota.crypto.types.Seed.random(
     )  # Generates official random 81 tryte seed
     generator = AddressGenerator(
         self.seed, security_level=1)  # Generates IOTA address from seed
     self.address = generator.get_addresses(start=0)
     self.address = self.address[0].address
     keyGen = KeyGenerator(self.seed)
     self.privKey = keyGen.get_key(
         index=0, iterations=1)  # Generate IOTA key from seed
Esempio n. 28
0
    def test_get_addresses_multiple(self):
        """
    Generating multiple addresses in one go.
    """
        # Seed is not important for this test; it is only used by
        # :py:class:`KeyGenerator`, which we will mock in this test.
        ag = AddressGenerator(seed=b'')

        # noinspection PyUnresolvedReferences
        with patch.object(ag, '_get_digest', self._mock_get_digest):
            addresses = ag.get_addresses(start=1, count=2)

        self.assertListEqual(addresses, [self.addy1, self.addy2])
Esempio n. 29
0
    def test_generator_with_offset(self):
        """
    Creating a generator that starts at an offset greater than 0.
    """
        # Seed is not important for this test; it is only used by
        # :py:class:`KeyGenerator`, which we will mock in this test.
        ag = AddressGenerator(seed=b'')

        # noinspection PyUnresolvedReferences
        with patch.object(ag, '_get_digest', self._mock_get_digest):
            generator = ag.create_iterator(start=1, step=2)

            self.assertEqual(next(generator), self.addy1)
            self.assertEqual(next(generator), self.addy3)
Esempio n. 30
0
    def test_local_cache(self):
        """
    Installing a cache only for a single instance of
    :py:class:`AddressGenerator`.
    """
        mock_generate_address = Mock(return_value=self.addy)

        with patch(
                'iota.crypto.addresses.AddressGenerator._generate_address',
                mock_generate_address,
        ):
            generator1 = AddressGenerator(Seed.random())

            # Install the cache locally.
            generator1.cache = MemoryAddressCache()

            addy1 = generator1.get_addresses(42)
            mock_generate_address.assert_called_once()

            # The second time we try to generate the same address, it is
            # fetched from the cache.
            addy2 = generator1.get_addresses(42)
            mock_generate_address.assert_called_once()
            self.assertEqual(addy2, addy1)

            # Create a new instance to verify it has its own cache.
            generator2 = AddressGenerator(generator1.seed)

            # The generator has its own cache instance, so even though the
            # resulting address is the same, it is not fetched from cache.
            addy3 = generator2.get_addresses(42)
            self.assertEqual(mock_generate_address.call_count, 2)
            self.assertEqual(addy3, addy1)
def vanity_address_generator(vanity_text, report_interval=False):
    """Generates iota seed whose first subaddress begins with vanity_text

    Type:
        Function

    Args:
        vanity_text  (str object, required) string
        report_interval  (int object, optional) reports progress via standard output at designated intervals if defined

    Returns:
        None
    """

    # Tests
    if report_interval < 0:
        raise ValueError('Report interval cannot be negative')

    if type(vanity_text) is not str:
        raise TypeError('Vanity text must be type str')

    for char in vanity_text.upper():
        if char not in string.ascii_uppercase + '9':
            raise ValueError('Vanity text must only contain chars A-Z and 9')

    # Brute force loop
    count = 0
    while True:
        secret = "".join([random.choice(string.ascii_letters + string.digits) for i in range(64)])
        seed = next(seed_generator(secret, 0, 1))

        ag = AddressGenerator(seed, checksum=True)
        address = str(ag.get_addresses(0)[0])

        if vanity_text in address[:len(vanity_text)]:
            print()
            print('Count:   ', count)
            print('Secret:  ', secret)
            print('Seed:    ', seed)
            print('Address: ', address)
            print()
            break

        # Report
        if report_interval:
            if count % int(report_interval) == 0:
                print('Count:   ', str(count) + '\t', datetime.datetime.now() - datetime.timedelta(hours=-10))

        count += 1
Esempio n. 32
0
  def test_get_addresses_multiple(self):
    """
    Generating multiple addresses in one go.
    """
    ag = AddressGenerator(self.seed_2)

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=0, count=3),

      [
        Address(
          b'FNKCVJPUANHNWNBAHFBTCONMCUBC9KCZ9EKREBCJ'
          b'AFMABCTEPLGGXDJXVGPXDCFOUCRBWFJFLEAVOEUPY',
        ),

        Address(
          b'MSYILYYZLSJ99TDMGQHDOBWGHTBARCBGJZE9PIMQ'
          b'LTEXJXKTDREGVTPA9NDGGLQHTMGISGRAKSLYPGWMB',
        ),

        Address(
          b'IIREHGHXUHARKVZDMHGUUCHZLUEQQULLEUSJHIIB'
          b'WFYZIZDUFTOVHAWCKRJXUZ9CSUVLTRYSUGBVRMTOW',
        ),
      ],
    )

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=10, count=3),

      [
        Address(
          b'BPXMVV9UPKBTVPJXPBHHOJYAFLALOYCGTSEDLZBH'
          b'NFMGEHREBQTRIPZAPREANPMZJNZZNCDIUFOYYGGFY',
        ),

        Address(
          b'RUCZQJWKXVDIXTLHHOKGMHOV9AKVDBG9HUQHPWNZ'
          b'UNKJNFVMULUSLKFJGSTBSNJMRYSJOBVBQSKVXISZB',
        ),

        Address(
          b'FQAKF9XVCLTBESJKWCHFOCTVABYEEJP9RXUVAEUW'
          b'ENFUUQK9VCHFEORHCYDUJQHNUDWNRDUDZTUGKHSPD',
        ),
      ],
    )
Esempio n. 33
0
    def test_generator(self):
        """
    Creating a generator.
    """
        # Seed is not important for this test; it is only used by
        # :py:class:`KeyGenerator`, which we will mock in this test.
        ag = AddressGenerator(seed=b'')

        # noinspection PyUnresolvedReferences
        with patch.object(ag, '_create_digest_generator',
                          self._mock_digest_gen):
            generator = ag.create_generator()

            self.assertEqual(next(generator), self.addy0)
            self.assertEqual(next(generator), self.addy1)
Esempio n. 34
0
    async def _execute(self, request: dict) -> dict:
        inclusion_states: bool = request['inclusionStates']
        seed: Seed = request['seed']
        start: int = request['start']
        stop: Optional[int] = request['stop']

        # Determine the addresses we will be scanning, and pull their
        # transaction hashes.
        if stop is None:
            my_hashes = list(
                chain(*([
                    hashes async for _, hashes in iter_used_addresses(
                        self.adapter, seed, start)
                ])))
        else:
            ft_response = \
                await FindTransactionsCommand(self.adapter)(
                    addresses=
                    AddressGenerator(seed).get_addresses(start, stop - start),
                )

            my_hashes = ft_response['hashes']

        return {
            'bundles':
            await get_bundles_from_transaction_hashes(
                adapter=self.adapter,
                transaction_hashes=my_hashes,
                inclusion_states=inclusion_states,
            ),
        }
Esempio n. 35
0
    def _execute(self, request):
        inclusion_states = request['inclusionStates']  # type: bool
        seed = request['seed']  # type: Seed
        start = request['start']  # type: int
        stop = request['stop']  # type: Optional[int]

        # Determine the addresses we will be scanning, and pull their
        # transaction hashes.
        if stop is None:
            my_hashes = list(
                chain(*(hashes for _, hashes in iter_used_addresses(
                    self.adapter, seed, start))))
        else:
            ft_response = \
                FindTransactionsCommand(self.adapter)(
                    addresses=
                    AddressGenerator(seed).get_addresses(start, stop - start),
                )

            my_hashes = ft_response['hashes']

        return {
            'bundles':
            get_bundles_from_transaction_hashes(
                adapter=self.adapter,
                transaction_hashes=my_hashes,
                inclusion_states=inclusion_states,
            ),
        }
Esempio n. 36
0
def iter_used_addresses(
        adapter,  # type: BaseAdapter
        seed,  # type: Seed
        start,  # type: int
        security_level=None,  # type: Optional[int]
):
    # type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, None]
    """
    Scans the Tangle for used addresses.

    This is basically the opposite of invoking ``getNewAddresses`` with
    ``stop=None``.
    """
    if security_level is None:
        security_level = AddressGenerator.DEFAULT_SECURITY_LEVEL

    ft_command = FindTransactionsCommand(adapter)

    for addy in AddressGenerator(seed, security_level).create_iterator(start):
        ft_response = ft_command(addresses=[addy])

        if ft_response['hashes']:
            yield addy, ft_response['hashes']
        else:
            break

        # Reset the command so that we can call it again.
        ft_command.reset()
Esempio n. 37
0
    def _execute(self, request):
        stop = request['stop']  # type: Optional[int]
        seed = request['seed']  # type: Seed
        start = request['start']  # type: int
        threshold = request['threshold']  # type: Optional[int]
        security_level = request['securityLevel']  # int

        # Determine the addresses we will be scanning.
        if stop is None:
            addresses =\
              [addy for addy, _ in iter_used_addresses(self.adapter, seed, start, security_level=security_level)]
        else:
            addresses = AddressGenerator(seed, security_level).get_addresses(
                start, stop - start)

        if addresses:
            # Load balances for the addresses that we generated.
            gb_response = GetBalancesCommand(self.adapter)(addresses=addresses)
        else:
            gb_response = {'balances': []}

        result = {
            'inputs': [],
            'totalBalance': 0,
        }

        threshold_met = threshold is None

        for i, balance in enumerate(gb_response['balances']):
            addresses[i].balance = balance

            if balance:
                result['inputs'].append(addresses[i])
                result['totalBalance'] += balance

                if (threshold
                        is not None) and (result['totalBalance'] >= threshold):
                    threshold_met = True
                    break

        if threshold_met:
            return result
        else:
            # This is an exception case, but note that we attach the result
            # to the exception context so that it can be used for
            # troubleshooting.
            raise with_context(
                exc=BadApiResponse(
                    'Accumulated balance {balance} is less than threshold {threshold} '
                    '(``exc.context`` contains more information).'.format(
                        threshold=threshold,
                        balance=result['totalBalance'],
                    ), ),
                context={
                    'inputs': result['inputs'],
                    'request': request,
                    'total_balance': result['totalBalance'],
                },
            )
Esempio n. 38
0
    def test_global_cache(self):
        """
    Installing a cache that affects all :py:class:`AddressGenerator`
    instances.
    """
        # Install the cache globally.
        AddressGenerator.cache = MemoryAddressCache()

        mock_generate_address = Mock(return_value=self.addy)

        with patch(
                'iota.crypto.addresses.AddressGenerator._generate_address',
                mock_generate_address,
        ):
            generator1 = AddressGenerator(Seed.random())

            addy1 = generator1.get_addresses(42)
            mock_generate_address.assert_called_once()

            # The second time we try to generate the same address, it is
            # fetched from the cache.
            addy2 = generator1.get_addresses(42)
            mock_generate_address.assert_called_once()
            self.assertEqual(addy2, addy1)

            # Create a new AddressGenerator and verify it uses the same
            # cache.
            generator2 = AddressGenerator(generator1.seed)

            # Cache is global, so the cached address is returned again.
            addy3 = generator2.get_addresses(42)
            mock_generate_address.assert_called_once()
            self.assertEqual(addy3, addy1)
Esempio n. 39
0
def generateAddress():
    global addressIndex
    print("Generating a new address")
    generator = AddressGenerator(seed)
    addressIndex += 1
    config.set('MainProd', 'addressIndex', addressIndex)
    with open('sytrax.ini', 'w') as configfile:
        config.write(configfile)
    IOTAAddress = getAddress(addressIndex)
Esempio n. 40
0
  def _find_addresses(self, seed, index, count, security_level, checksum):
    # type: (Seed, int, Optional[int], int, bool) -> List[Address]
    """
    Find addresses matching the command parameters.
    """
    generator = AddressGenerator(seed, security_level, checksum)

    if count is None:
      # Connect to Tangle and find the first address without any
      # transactions.
      for addy in generator.create_iterator(start=index):
        # We use addy.address here because FindTransactions does
        # not work on an address with a checksum
        response = FindTransactionsCommand(self.adapter)(
           addresses=[addy.address]
        )

        if not response.get('hashes'):
          return [addy]

    return generator.get_addresses(start=index, count=count)
Esempio n. 41
0
  def test_get_addresses_step_negative(self):
    """
    Providing a negative ``step`` value to ``get_addresses``.

    This is probably a weird use case, but what the heck.
    """
    ag = AddressGenerator(self.seed_1)

    # noinspection SpellCheckingInspection
    self.assertListEqual(
      ag.get_addresses(start=1, count=2, step=-1),

      [
        Address(
          b'PNLOTLFSALMICK9PSW9ZWLE9KJAKPKGJZQJDAFMO'
          b'VLHXMJCJXFPVHOTTOYDIAUAYELXKZWZUITCQBIQKY',
        ),

        Address(
          b'DLEIS9XU9V9T9OURAKDUSQWBQEYFGJLRPRVEWKN9'
          b'SSUGIHBEIPBPEWISSAURGTQKWKWNHXGCBQTWNOGIY',
        ),
      ],
    )