def get_milestoneStartIndex(url): try: api = Iota(url) node_info = api.get_node_info() return int(node_info["milestoneStartIndex"]) except: return 0
def checknodestate(): api = Iota("https://field.deviota.com:443") nodeinfo = api.get_node_info() latestmilestone = (nodeinfo['latestMilestoneIndex']) latestsubtanglemilestone = (nodeinfo ['latestSolidSubtangleMilestoneIndex']) print(str(latestmilestone) + " " + str(latestsubtanglemilestone)) if latestmilestone - latestsubtanglemilestone > 3: return 2 else: return 1
def get_latest_solid_milestones(test, time_elapsed): for node in test.get_nodes(): api = Iota(test.get_api_address(node)) response = api.get_node_info() index = response.get('latestSolidSubtangleMilestoneIndex') if test.get_latest_milestone() == 0: index = response.get('latestMilestoneIndex') if node == 'nodeD': index = 0 logger.info("Node: {} Index: {}".format(node, index)) test.add_index(node, index, time_elapsed)
class Node: def __init__(self, seed, iota_node, route_pow=False, pow_node=''): # Node variables self.iota_node = iota_node # Public node self.pow_node = pow_node # Local node to perform PoW # Creates an Iota API self.api = self.create_api(seed, route_pow) def create_api(self, seed, route_pow) -> Iota: """Creates an Iota object to interact with the tangle :param seed: The seed of the device :param route_pow: Boolean to state whether PoW is outsourced :return: An Iota object """ try: if route_pow is True: self.api = \ Iota( RoutingWrapper(self.iota_node) .add_route('attachToTangle', self.pow_node) .add_route('interruptAttachingToTangle', self.pow_node), seed=seed ) else: self.api = Iota(self.iota_node, seed) # Uncomment to test node after creating an API # self.test_node() return self.api except ConnectionRefusedError as e: print(e) print("Ensure all nodes are working correctly before connecting") def test_node(self): """Tests the connection to the node and if it is synced """ try: status = self.api.get_node_info() print("Successfully connected to IOTA Node!") if abs(status['latestMilestoneIndex'] - status['latestSolidSubtangleMilestoneIndex']) > 3: print("\rIota node is not synced!") else: print("\rIota node is synced!") except requests.exceptions.ConnectionError: print("Connection refused")
def test_wireup(self): """ Verify that the command is wired up correctly. (sync) The API method indeed calls the appropiate command. """ with patch( 'iota.commands.core.get_node_info.GetNodeInfoCommand.__call__', MagicMock(return_value=async_return( 'You found me!'))) as mocked_command: api = Iota(self.adapter) response = api.get_node_info() self.assertTrue(mocked_command.called) self.assertEqual(response, 'You found me!')
from iota import Iota # Create a new instance of the IOTA API object # Specify which node to connect to api = Iota(adapter='https://nodes.devnet.iota.org:443') # Call the `get_node_info()` method for information about the node and the Tangle response = api.get_node_info() print(response)
return TryteString.from_unicode(dataString) #Seed generator def generateSeed(): seed = '' for i in range(81): seed += random.choice(chars) return seed sender_seed = b'OF9JOIDX9NVXPQUNQLHVBBNKNBVQGMWHIRZBGWJOJLRGQKFMUMZFGAAEQZPXSWVIEBICOBKHAPWYWHAUF' receiver_seed = b'DBWJNNRZRKRSFAFRZDDKAUFSZCTDZHJXDLHVCEVQKMFHN9FYEVNJS9JPNFCLXNKNWYAJ9CUQSCNHTBWWB' api = Iota(uri, seed=sender_seed) print(api.get_node_info()) def generateAddress(): gna_result = api.get_new_addresses(count=2) addresses = gna_result['addresses'] return addresses def storeJson(file): receiver_address = generateAddress()[0] sender_address = generateAddress()[1] print('receiver address = ', receiver_address) print('sender address = ', sender_address)
class MyIOTA: def __init__(self, node, seed): self.node = node self.seed = seed self.api = False self._update = False self.transfers = [] self._debug = False self.wallet = self.get_filename() self.addr_dict = {} self.min_weight_magnitude = 14 self.api = Iota(self.node, self.seed) self.USED = True self.NOT_USED = False def Address(self, addr_string): return Address(addr_string) def get_addr_dict(self): return self.addr_dict def set_addr_dict(self, addr, value, used): self.addr_dict[addr] = (value, used) def s_addr(self, addr, n=3): s_addr = str(addr) l = len(s_addr) return s_addr[:n] + '...' + s_addr[l - n:] def get_filename(self): h = hashlib.sha256() h.update(self.seed) filename = h.hexdigest()[:20] + '.txt' return filename def init_wallet(self): filename = self.wallet # file exists if os.path.isfile(filename): filefd = open(filename, 'r+') self.debug( 'Wallet file {0} exists. Opening it...'.format(filename)) for line in filefd: line = line.rstrip('\n') addr, index, value, used = line.split(',') self.debug('reading from file: {0},{1},{2}'.format( self.s_addr(addr, 3), value, used)) used = used == 'True' addr = Address(addr, key_index=int(index), security_level=2) self.addr_dict[addr] = (int(index), int(value), used) filefd.close() else: filefd = open(filename, 'w') self.debug('Wallet file {0} doesnt exist. Creating it...'.format( filename)) filefd.close() def is_empty_wallet(self): return len(self.addr_dict) == 0 def get_fund_inputs(self, inputs): total_fund = 0 for addr in inputs: index, value, used = self.addr_dict[addr] # TODO: abs. is this right? total_fund += abs(value) return total_fund def write_updates(self): filefd = open(self.wallet, 'w') self.debug('Writing (updating) wallet...') for addr in self.addr_dict: v = self.addr_dict[addr] line = 'Writing: {0},{1},{2},{3}\n'.format(self.s_addr(addr), v[0], v[1], v[2]) self.debug(line) filefd.write('{0},{1},{2},{3}\n'.format(addr, v[0], v[1], v[2])) filefd.close() def update_wallet(self, input_fund, inputs, change_addr): copy_dict = self.addr_dict.copy() for addr in inputs: v = self.addr_dict[addr] #self.debug('Spending {0} from input {1}'.format(self.s_addr(addr), v)) # Negative fund and used address new_value = (v[0], -v[1], not v[2]) self.debug('Updating input address {0} to: {1}'.format( self.s_addr(addr), new_value)) self.addr_dict[addr] = new_value change_fund = self.get_fund_inputs(inputs) - input_fund v = self.addr_dict[change_addr] change_value = (v[0], change_fund, self.NOT_USED) self.debug('Updating change address {0} to: {1}'.format( self.s_addr(change_addr), change_value)) self.addr_dict[change_addr] = change_value self.write_updates() def enable_debug(self): self._debug = True def debug(self, msg): if self._debug: print '[+] Debug: ', msg def get_node_info(self): return self.api.get_node_info() def make_addr_list(self, start_index, n): self.iota_assert(start_index >= 0 and n > 0, 'must be positive numbers. N should be at least 1.') result = self.api.get_new_addresses(index=start_index, count=n) addresses = result['addresses'] for i in range(n): addr = addresses[i] value = self.get_addr_balance(addr) # TODO: Why always False self.addr_dict[addr] = (i, value, False) self.write_updates() def get_addr_balance(self, addr): # TODO: addr is a list with just one element result = self.api.get_balances([addr]) balance = result['balances'] return (balance[0]) def prepare_transfer(self, transfer_value, dest_addr, tag='DEFAULT', msg='DEFAULT'): # TODO: verify address (checksum) # TODO: use mi, gi, etc msg = TryteString.from_string(msg) txn = ProposedTransaction( address=Address(dest_addr), message=msg, tag=Tag(tag), value=transfer_value, ) return txn def find_transactions(self): addr_list = [] for e in self.addr_dict.items(): addr = e[0] addr_list.append(addr) return self.api.findTransactions(addresses=addr_list)['hashes'] def get_bundle(self, trans): return self.api.getBundles(transaction=trans) def get_latest_inclusion(self, addrl): return self.api.get_latest_inclusion(hashes=addrl) def get_total_fund(self): total_fund = 0 for addr in self.addr_dict.items(): # key and value from dict k, v = addr index, value, used = v #if not used: total_fund += value return total_fund def get_number_of_address(self): return len(self.addr_dict) def is_all_addr_used(self): for addr in self.addr_dict: for e in self.addr_dict.items(): addr, v = e index, value, used = v if used == False: return True def get_more_addr(self, n=10): start_index = self.get_number_of_address() self.debug('Getting more addresses...please wait...') self.make_addr_list(start_index, n) def send_transfer(self, input_fund, inputs, outputs, change_addr, savetofile=True): # TODO: How to send MANY transactions. self.debug('Sending {0} transactions, please wait...'.format( len(outputs))) self.api.send_transfer(inputs=inputs, transfers=outputs, depth=7, change_address=change_addr, min_weight_magnitude=self.min_weight_magnitude) self.debug('Sent.') if self.is_all_addr_used(): # We do an update to wallet file here. self.get_more_addr(n=10) if savetofile: self.update_wallet(input_fund, inputs, change_addr) def get_bundles(self, hasht): return self.api.get_bundles(hasht) def get_trytes(self, hashl): return self.api.get_trytes(hashl)['trytes'][0] def get_transaction_from_trytes(self, trytes): txn = Transaction.from_tryte_string(trytes) return txn def get_transaction_fields(self, txn): #confirmed = str(txn.is_confirmed) timestamp = str(txn.timestamp) address = str(txn.address) value = str(txn.value) message = str(txn.signature_message_fragment) #message = str(txn.message) tag = str(txn.tag) return (timestamp, address, value, tag, message) def get_info_transactions(self, transactions_hashes): txn_tuples = [] for h in transactions_hashes: trytes = self.get_trytes([h]) txn = self.get_transaction_from_trytes(trytes) # Get confirmed flag li_result = self.get_latest_inclusion([bytes(h)]) confirmed_t = li_result['states'][h] (_, addr_t, value_t, tag_t, msg_t) = self.get_transaction_fields(txn) txn_tuples.append((confirmed_t, addr_t, value_t, tag_t, msg_t)) return txn_tuples def get_any_valid_addr(self): #TODO: verify #return self.addr_dict.keys()[0] for e in self.addr_dict.items(): addr, v = e index, value, used = v if not used: return addr return None def get_inputs(self, fund): # TODO: Zero fund fund_sum = 0 addr_list = [] change_addr = None # Zero fund transactions. We return any addr and any change_addr if fund == 0: # TODO: What if it conflicts with one another? addr_list.append(self.get_any_valid_addr()) change_addr = self.get_any_valid_addr() return (addr_list, change_addr) for e in self.addr_dict.items(): addr, v = e index, value, used = v if fund_sum < fund: #if value > 0 and not used: if value > 0 and used == self.NOT_USED: fund_sum += value self.debug( 'Found request: {0}. Found address {1} with fund {2}.'. format(fund, self.s_addr(addr), value)) addr_list.append(addr) for e in self.addr_dict.items(): addr, v = e index, value, used = v if used == self.NOT_USED and addr not in addr_list: change_addr = addr self.debug('Using {0} as change addr.'.format( self.s_addr(addr))) break return (addr_list, change_addr) #else: # # TODO # self.iota_assert(True, 'No change addr available.') def iota_assert(self, condition, msg): if not condition: print 'Error: ', msg sys.exit(-1)
class TangleConnector: def __init__(self, url='https://nutzdoch.einfachiota.de', seed="TESTSEED9"): self.iri_url = url self.iota_api = Iota(url, seed) def get_node(self) -> dict: """ Get IRI node info """ try: res = self.iota_api.get_node_info() except Exception as e: logging.warning("Failed to IRI node info for " + self.iri_url, e) res = None return res def get_tips(self) -> dict: """ Get all unreferenced transactions """ try: res = self.iota_api.get_tips() except Exception as e: logging.warning("Failed to get tips", e) res = None return res def get_hashes_from_addr(self, address: Address) -> List[TransactionHash]: """ Get all tx from address """ try: response = self.iota_api.find_transactions(addresses=[address]) hashes = response['hashes'] except Exception as e: logging.warning( "Failed to get all tx from address " + address.__str__(), e) hashes = None return hashes def get_trytes_from_hashes( self, hashes: List[TransactionHash]) -> List[TryteString]: """ Get tryte signature fragments from hashes """ try: response = self.iota_api.get_trytes(hashes) if response['trytes']: trytes = [tryte[0:2187] for tryte in response['trytes']] except Exception: #logging.warning("Failed to get all signature fragments") trytes = None return trytes def get_all_trytes_from_address( self, address: Address) -> Dict[TransactionHash, TryteString]: """ Get all trytes from address """ hashes = self.get_hashes_from_addr(address) trytes = self.get_trytes_from_hashes(hashes) if hashes and trytes: result = dict(zip(hashes, trytes)) else: result = None return result @staticmethod def get_json_from_tryte(tryte: TryteString) -> dict: try: str_from_tryte = tryte.as_string() dict_from_tryte = json.loads(str_from_tryte) except Exception as e: logging.error("Failed to convet trytes to JSON", e) dict_from_tryte = None return dict_from_tryte def send_msg_to_addr(self, address: Address, msg: str, tag: str) -> dict: """ Sends msg on Tangle to address with a tag """ try: response = self.iota_api.send_transfer( depth=5, transfers=[ ProposedTransaction(address=address, value=0, tag=Tag(tag), message=TryteString.from_string(msg)) ]) except Exception as e: logging.warning( "Message '" + msg + "' has failed to be stored in " + address.__str__(), e) response = None return response
from iota import Iota, TransactionHash import Queue api = Iota('https://nodes.iota.cafe:443') txhash = 'AYIEJ9IIFDWIJFDLKWQVGQM9RFIYQKNNXQGWGOHFJVVEONZMJDVGRGKNN9OBJUARFYMJJ9CZMRZQA9999' tips = api.get_node_info() n = 0 tocheck = [TransactionHash(txhash)] while tocheck: approvees = api.find_transactions(approvees=tocheck)['hashes'] n += len(approvees) tocheck = approvees print n, '/', tips['tips']
class TangleConnector: def __init__(self, url='https://perma.iota.partners:443', seed="TESTSEED9"): self.iri_url = url self.iota_api = Iota(url, seed) def get_node(self) -> Dict: """ Get IRI node info """ try: res = self.iota_api.get_node_info() except BadApiResponse as e: logger.warning("Failed to IRI node info for " + self.iri_url, e) res = None return res def get_tips(self) -> Dict: """ Get all unreferenced transactions """ try: res = self.iota_api.get_tips() except BadApiResponse as e: logger.warning("Failed to get tips", e) res = None return res def get_hashes_from_addr(self, address: Address) -> List[TransactionHash]: """ Get all tx from address """ try: response = self.iota_api.find_transactions(addresses=[address]) hashes = response['hashes'] except (BadApiResponse, KeyError) as e: logger.warning( "Failed to get all tx from address " + address.__str__(), e) hashes = None return hashes def get_trytes_from_hashes( self, hashes: List[TransactionHash]) -> List[TryteString]: """ Get tryte signature fragments from hashes """ try: response = self.iota_api.get_trytes(hashes) trytes = [tryte[0:2187] for tryte in response['trytes']] except (BadApiResponse, KeyError) as e: logger.warning("Failed to get all signature fragments", e) trytes = None return trytes def get_all_trytes_from_address( self, address: Address) -> Dict[TransactionHash, TryteString]: """ Get all trytes from address """ hashes = self.get_hashes_from_addr(address) trytes = self.get_trytes_from_hashes(hashes) if hashes and trytes: result = dict(zip(hashes, trytes)) else: result = None return result @staticmethod def get_json_from_tryte(tryte: TryteString) -> Dict: try: str_from_tryte = tryte.as_string() dict_from_tryte = json.loads(str_from_tryte) except ValueError as e: logger.error("Failed to convet trytes to JSON", e) dict_from_tryte = None return dict_from_tryte def send_msg_to_addr(self, address: Address, msg: str, tag: str) -> Dict: """ Sends msg on Tangle to address with a tag """ try: response = self.iota_api.send_transfer( depth=2, transfers=[ ProposedTransaction(address=address, value=0, tag=Tag(tag), message=TryteString.from_string(msg)) ]) except BadApiResponse as e: logger.warning( "Message '" + msg + "' has failed to be stored in " + address.__str__(), e) response = None return response def get_bundles_from_addr(self, address: Address) -> List[Dict]: ''' Retrive all bundles sent to this address from IRI # requres IRI 1.6+ (or it seems so) ''' hashes = self.get_hashes_from_addr(address) bundles = [] if hashes: for tx in hashes: try: # have to loop through all txs, if tx is not 'tail' of a bundle then get_bundles() throws error bundle = self.iota_api.get_bundles(tx) except BadApiResponse: bundle = None if bundle: bundles.append(bundle) return bundles def get_messages_from_bundles(self, bundles: List) -> Dict: """ Loop through list of bundles and get string per bundle # requres IRI 1.6+ (or it seems so) """ output_msgs = {} for bundle in bundles: tx_list = bundle['bundles'][0].as_json_compatible() msg = '' for tx in tx_list: # if its a bundle with iotas, just get text from first tx in bundle, the rest are signatures if tx['current_index'] == 0 and tx['value'] > 0: msg = tx['signature_message_fragment'].as_string() break # if its a bundle without iota value, then consequently get all message fields and join strings if tx['value'] == 0: msg = msg + tx['signature_message_fragment'].as_string() bundle_hash = tx_list[0]['bundle_hash'].__str__() addr = tx_list[0]['address'].__str__() timestamp = tx_list[0]['timestamp'] value = tx_list[0]['value'] output_msgs[bundle_hash] = { 'msg': msg, 'address': addr, 'timestamp': timestamp, 'value': value } return output_msgs def get_all_msg_from_addr_by_bundle(self, address: Address) -> Dict: ''' Get dict of all msg with timestamps from address by bundle hash as key # requres IRI 1.6+ (or it seems so) ''' bundles = self.get_bundles_from_addr(address) hashes_and_msgs = self.get_messages_from_bundles(bundles) return hashes_and_msgs