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 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)
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', ), ], )
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', ), ], )
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)
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()
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', ), ], )
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 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()
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, ), }
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()
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)
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', ), )
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, ), }
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
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()
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', ), ], )
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'], }, )
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))
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)
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)))
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)
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
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)
def test_cache_miss_seed(self): """ Cached addresses are keyed by seed. """ 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()) generator1.get_addresses(42) mock_generate_address.assert_called_once() generator2 = AddressGenerator(Seed.random()) generator2.get_addresses(42) self.assertEqual(mock_generate_address.call_count, 2)
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)
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
def __init__(self, walletfile, apifactory): # this api instance is used for non-node calls only self.walletdata = walletfile self.apifactory = apifactory self.seed = self.walletdata.seed self.api = iota.Iota('http://0.0.0.0:0', seed=self.seed) self.addrgen = AddressGenerator(self.seed) self.stopevent = threading.Event() self.refreshthread = RefreshAddrsThread(self, self.stopevent, 15) self.refreshthread.start()
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])
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)