def get_transfers(full_history, print_history=True): account_history_executing = True api = Iota(iota_node, seed) address_count = len(address_data) all_txn_hashes = [] saved_txn_hashes = [] new_txn_hashes = [] i = 0 while i < address_count: address = address_data[i]["address"] address_as_bytes = [bytes(address)] raw_transfers = api.find_transactions(addresses=address_as_bytes) transactions_to_check = raw_transfers["hashes"] for txn_hash in transactions_to_check: txn_hash = str(txn_hash) all_txn_hashes.append(txn_hash) i += 1 for txn_hash in transfers_data: txn_hash = str(txn_hash['transaction_hash']) saved_txn_hashes.append(txn_hash) for txn_hash in all_txn_hashes: if txn_hash not in saved_txn_hashes: new_txn_hashes.append(txn_hash) if len(new_txn_hashes) > 0: print("Retreaving and saving transfer data from " + str(len(new_txn_hashes)) + " transaction(s)!\n" "Please wait...\n") for txn_hash in new_txn_hashes: txn_hash_as_bytes = bytes(txn_hash) li_result = api.get_latest_inclusion([ txn_hash_as_bytes ]) # Needs to be integrated into new transactions as well is_confirmed = li_result['states'][txn_hash] print(li_result) gt_result = api.get_trytes([txn_hash_as_bytes]) trytes = str(gt_result['trytes'][0]) txn = Transaction.from_tryte_string(trytes) timestamp = str(txn.timestamp) tag = str(txn.tag) address = str(txn.address) message = "some message" # Placeholder untill message decoding is added value = str(txn.value) bundle = str(txn.bundle_hash) write_transfers_data(txn_hash, is_confirmed, timestamp, tag, address, message, value, bundle) if full_history: print_transaction_history(full_history, print_history) elif not full_history: print_transaction_history(full_history, print_history)
def findmessages(TXN_BUNDLE): api = Iota('http://node.deviceproof.org:14265') dict_txn = api.find_transactions(bundles = [TXN_BUNDLE.rstrip()]) if len(dict_txn["hashes"]) == 0: return "" tail_hash = dict_txn['hashes'] test = str(tail_hash)[19:100] bundle = api.get_bundles(test) signature_message_fragment = str(bundle["bundles"][0][0].signature_message_fragment) ans = TryteString(signature_message_fragment).decode() return ans
def findmessages(TXN_BUNDLE): #print("hello bundle is : " + str(TXN_BUNDLE)) api = Iota('http://node.deviceproof.org:14265') dict_txn = api.find_transactions(bundles=[TXN_BUNDLE.rstrip()]) #print("Transaction = ",dict_txn['hashes']) tail_hash = dict_txn['hashes'] test = str(tail_hash)[19:100] #print("Transaction hash = ",test) bundle = api.get_bundles(test) signature_message_fragment = str( bundle["bundles"][0][0].signature_message_fragment) ans = TryteString(signature_message_fragment).decode() return ans
def get_transfers(self): """ Get transactions :return: """ api = Iota(current_app.config['IOTA_HOST'], self.seed) result = [] for a in self.addresses: t = api.find_transactions(addresses=[a.address]) for th in t['hashes']: gt = api.get_trytes([th]) txn = Transaction.from_tryte_string(gt['trytes'][0]) result.append(txn) return result
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.find_transactions.FindTransactionsCommand.__call__', MagicMock(return_value=async_return( 'You found me!'))) as mocked_command: api = Iota(self.adapter) response = api.find_transactions('addresses') self.assertTrue(mocked_command.called) self.assertEqual(response, 'You found me!')
class Replay: def __init__(self, node, seed, bundle, replay_callback=None, depth=7, min_weight_magnitude=14): self.api = Iota(node, seed) self.depth = depth self.min_weight_magnitude = min_weight_magnitude if replay_callback: self.replay_callback = replay_callback self.replay(bundle) def fetch_tail_transaction(self, bundle_hash): ft_result = self.api.find_transactions(bundles=[bundle_hash]) transaction_hashes = ft_result['hashes'] gt_result = self.api.get_trytes(transaction_hashes) bundle = Bundle.from_tryte_strings(gt_result['trytes']) return bundle.tail_transaction.hash def replay(self, bundle): tail_transaction = self.fetch_tail_transaction(bundle) try: self.api.replay_bundle( transaction=tail_transaction, depth=self.depth, min_weight_magnitude=self.min_weight_magnitude) if callable(self.replay_callback): self.replay_callback( 'Successfully replayed your specified bundle!') except: if callable(self.replay_callback): self.replay_callback( 'Something went wrong while replaying your bundle! Please try again.' )
class Collector(Crypt): def __init__(self, secret, node='https://nodes.thetangle.org:443'): super(Collector, self).__init__(secret) self.api = Iota(adapter=node) def getData(self, txHash): hashes = api.find_transactions(addresses=[ address, ])['hashes'] def decode(self, frag): hiddenMessage = frag.signature_message_fragment.decode() decrypted = self.decrypt(bytes(hiddenMessage, 'utf=8')) return json.loads(decrypted) def read(self, silent=False): address = Address(self.address) txHashes = self.api.find_transactions(addresses=[ address, ])['hashes'] batchSize = 80 sets = math.ceil(len(txHashes) / batchSize) txs = [] for i in range(sets): start = time.time() resp = self.api.get_transaction_objects( txHashes[i * batchSize:(i + 1) * batchSize])['transactions'] txs += resp duration = time.time() - start if not silent: print(f'Fetched {len(resp)} events in {duration:.1f} sec.') return sorted([self.decode(t) for t in txs], key=lambda a: a[0], reverse=True) def readLatest(self, silent=False): messages = self.read() secconds, msg = messages[0] timestamp = datetime.datetime.fromtimestamp(secconds) return f'{timestamp}: {msg}'
class Collector: def __init__(self, endpoint=None): self.api = Iota(adapter='https://nodes.thetangle.org:443') if endpoint is None: self.endpoint = Controller.endpoint else: self.endpoint = endpoint def getData(self, txHash): hashes = api.find_transactions(addresses=[ address, ])['hashes'] def read(self): address = Address(self.endpoint) txHashes = self.api.find_transactions(addresses=[ address, ])['hashes'] txs = self.api.get_transaction_objects(txHashes)['transactions'] decode = lambda a: json.loads(a.signature_message_fragment.decode()) return sorted([decode(t) for t in txs], key=lambda a: a[0], reverse=True)
def get_txn_hash_from_bundle(hash_bundle): # Iota instance api = Iota(NODE_URL) obj_txn = api.find_transactions(bundles=[hash_bundle]) return str(obj_txn['hashes'][0])
# Read right new_right_list, right_list = readRight(filename_list, RIGHT_PATH) # Test Transaction print 'Start testing transaction' test_len = len(new_right_list) print 'test len', test_len cnt = 0 r_cnt = 0 api = Iota('http://localhost:14265') for new_right in new_right_list: res = api.find_transactions(tags=[new_right['tag']]) print 'Test Progress: ', r_cnt, '/', cnt, '/', test_len cnt += 1 if len(res['hashes']) != 1: continue r_cnt += 1 right_list.append(new_right) # Restore src = open(RIGHT_PATH, 'w') src.write(json.dumps(right_list)) src.close()
LOCAL_NODE).add_route( 'interruptAttachingToTangle', LOCAL_NODE)) bundle_hash = input('Paste bundle hash: ') """ API.replay_bundle does not accept a bundle hash as argument. You have to pass the transaction hash with a currentIndex of 0 (= the first transaction or "tail transaction" of a bundle). That's why we have to get the transaction hashes of the bundle with API.find_transactions. Then we have to find out which of the returned transactions has a currentIndex of 0. """ print('Fetching transaction hashes...') transaction_hashes = API.find_transactions(bundles=[bundle_hash])['hashes'] print('Received transaction hashes.') print('Fetching transaction trytes...') bundle_trytes = API.get_trytes(transaction_hashes)['trytes'] print('Received transaction trytes.') from iota import Transaction for transaction_trytes in bundle_trytes: transaction = Transaction.from_tryte_string(transaction_trytes) if transaction.is_tail: print('Reattaching...') API.replay_bundle(transaction.hash, 3) print('Reattached') break
# coding=utf-8 from iota import Iota from config_iota_wallet import NODE_URL, SEED api = Iota(NODE_URL, SEED) dict_txn = api.find_transactions(tags=['NTCTODAY']) print("The tag NTCTODAY transaction hash: " + str(dict_txn['hashes']))
class IotaClient(object): """Python IOTA client wrapper""" def __init__(self, seed, provider, depth=5, min_weight_magnitude=14): self._api = Iota(provider, seed) self._depth = depth self._min_weight_magnitude = min_weight_magnitude self.address = self._get_address() @staticmethod def _compose_transaction(address, msg, tag, val): txn = \ ProposedTransaction( address=Address(address), message=TryteString.from_unicode(msg), tag=Tag(tag), value=val ) return txn def _get_address(self): address = self._api.get_new_addresses(0, 1)['addresses'][0] return str(address) def get_transactions_from_address(self, address): """ Gets transaction object from address sorted on timestamp (from latest to earliest). :param address: Address to fetch transaction from """ transactions = self._api.find_transactions(addresses=[address]) transaction_hashes = transactions['hashes'] if not transaction_hashes: raise ValueError("No transactions on address") trytes = self._api.get_trytes(transaction_hashes)['trytes'] trytes_and_hashes = list(zip(trytes, transaction_hashes)) transactions = list( map(lambda pair: Transaction.from_tryte_string(pair[0], pair[1]), trytes_and_hashes)) sorted_transactions = sorted(transactions, key=lambda t: t.timestamp, reverse=True) return sorted_transactions def get_messages_from_address(self, address): """ Gets messages (sorted by timestamp). Returns a dict with 'json_message' and 'timestamp keys' :param address: Address to fetch messages from """ sorted_transactions = self.get_transactions_from_address(address) messages = list( map( lambda t: { 'json_message': json.loads(Fragment.as_string(t.signature_message_fragment) ), 'timestamp': t.timestamp }, sorted_transactions)) return messages @staticmethod def get_message(transaction): message = transaction['signature_message_fragment'].decode() json_message = json.loads(message) return json_message def send_transaction(self, address, msg, tag, val): txn = self._compose_transaction(Address(address), msg, tag, val) mwm = self._min_weight_magnitude depth = self._depth self._api.send_transfer(depth, [txn], None, None, mwm)
class Escrow: def __init__(self, node='https://nodes.thetangle.org:443', seed=None): #Get Seed if seed is None: self.seed = self.getSeed() else: self.seed = seed #Setup API self.api = Iota(node, self.seed) #Generates a seed for escrow account def getSeed(self): #If no seed, create one if not os.path.isfile('seed.txt'): path = pathlib.Path(__file__).parent.absolute() seed = ''.join([random.choice(LETTERS) for i in range(81)]) open('seed.txt', 'w+').write(seed) logging.info("Placed new seed in seed.txt") return open('seed.txt').read().strip().encode('utf-8') #Creates an escrow holding address def createEscrow(self): try: self.holdingAddress = self.api.get_new_addresses( count=None, checksum=True)['addresses'][0] except iota.adapter.BadApiResponse as e: logging.warning("Bad response from server retrying.") return self.createEscrow() return self.holdingAddress #Waits for a transactions with a refund address def getRefundAddress(self): #This is the escrow address address = self.holdingAddress try: #Get Hashes from ledger txHashes = self.api.find_transactions(addresses=[ address, ])['hashes'] #If no hashes, user has not submitted an address yet. if len(txHashes) == 0: return None else: #Check messages for a valid address txs = self.api.get_transaction_objects( txHashes)['transactions'] for tx in txs: msg = tx.signature_message_fragment.decode() try: self.deposit = Address(msg.strip()) return self.deposit except: pass logging.warning("Invalid address recieved") except requests.exceptions.ConnectionError as e: #Sometimes the public nodes will reject a request print("Error contacting server; retrying") return self.getRefundAddress() #Cli version of escrow def startCli(self, collateral, fee=0, delay=120, deposit=None): #Create holding address self.createEscrow() self.fee = fee self.collateral = collateral #Wait for a deposit address to be entered if self.requestDeposit(collateral, deposit, delay): while not self.checkCondition(): sleep(3) self.finalizeEscrow() #Wait for escrow address to recieve collateral def requestDeposit(self, collateral, deposit=None, duration=120): #For CLI prompt a deposit address if deposit is None: self.deposit = input("What is the deposit address: ") print( f"You have {duration/60:.1f} min to deposit {collateral} IOTA to {self.holdingAddress}" ) #Wait for escrow to recive collateral funds. count = 0 while count < duration: time.sleep(1) balance = self.getBalance(self.holdingAddress) if balance >= collateral: print("Successfully deposited into escrow", balance) return True return False #Condition to release escrow def checkCondition(self): #Setup a check condition #For example RFID or some ledger condition return True #Refund user their collateral, remoing the fee def finalizeEscrow(self, fee=None, deposit=None): if fee is None: fee = self.fee if deposit is None: deposit = self.deposit #Return money to deposit address returnAmount = self.getBalance(self.holdingAddress) #Calcualte return amount if returnAmount > 0: returnAmount -= fee #Setup transaction message = "Repayment of collateral" feeLocation = self.api.get_new_addresses(count=1, checksum=True)['addresses'][0] txs = [ ProposedTransaction(address=Address(deposit), value=returnAmount, message=TryteString.from_unicode(message)), ] #Send transaction try: bundle = self.api.send_transfer(transfers=txs)['bundle'] except iota.adapter.BadApiResponse as e: print("Node did not respond. Retrying.") return self.finalizeEscrow(fee, deposit) logging.info(bundle.transactions[0].hash) logging.info("Sent money back to recipient") self.addRevenue(fee) def getBalance(self, address): try: response = self.api.get_balances(addresses=[address])['balances'] return response[0] except requests.exceptions.ConnectionError as e: logging.info("Error contacting server; retrying") return self.getBalance(self, address) #Record the amount of revenue recieved def addRevenue(self, money, filename='revenue.txt'): if not os.path.isfile(filename): open(filename, 'w+').write('0') current = int(open(filename).read().strip()) current += money open(filename, 'w+').write(str(current)) #Get the current amount of revenue def getRevenue(self, filename="revenue.txt"): if not os.path.isfile(filename): return 0 return int(open(filename).read().strip()) #Send revenue to an address def sendRevenue(self, outputAddress): revenue = self.getRevenue() logger.info(f"Currently have {revenue} revenue.") message = "Output fees from escrow." txs = [ ProposedTransaction(address=Address(outputAddress), value=revenue, message=TryteString.from_unicode(message)), ] try: logger.info("Sending transfer to node.") bundle = self.api.send_transfer(transfers=txs)['bundle'] except iota.adapter.BadApiResponse as e: print("Bad api resonse retrying") return self.sendRevenue(outputAddress) print(bundle.transactions[0].hash)
def gen_bundle_info_for_transfer(bundle_idx, label, seed, dst_addr, value): # api api = Iota('http://localhost:14265', seed) # find all transactions for address trxs = api.find_transactions(addresses=[dst_addr])['hashes'] bundle = None # try to find the right bundle for trx in trxs: try: trx_bundles = api.get_bundles(trx)['bundles'] for trx_bundle in trx_bundles: try: if trx_bundle.transactions[ 0].value == value and trx_bundle.transactions[ 0].address == dst_addr: bundle = trx_bundle break except: pass if bundle: break except: pass # If trx could not be found, raise and stop now if not bundle: raise BaseException("Could not find bundle for trx %s (%di)" % (dst_addr, value)) bundle_info = \ """ //! //! Bundle %d //! %s //! static const std::string BUNDLE_%d_HASH = "%s"; """ % (bundle_idx, label, bundle_idx, bundle.hash) for i in range(0, len(bundle.transactions)): trx_idx = i + 1 trx = bundle.transactions[i] bundle_info += \ """ static const std::string BUNDLE_%d_TRX_%d_HASH = "%s"; static const std::string BUNDLE_%s_TRX_%s_ADDRESS = "%s"; static const std::string BUNDLE_%d_TRX_%d_ADDRESS_WITHOUT_CHECKSUM = "%s"; static const std::string BUNDLE_%d_TRX_%d_TRYTES = "%s"; static const std::string BUNDLE_%d_TRX_%d_SIGNATURE_FRAGMENT = "%s"; static const int64_t BUNDLE_%d_TRX_%d_CURRENT_INDEX = %d; static const int64_t BUNDLE_%d_TRX_%d_LAST_INDEX = %d; static const std::string BUNDLE_%d_TRX_%d_NONCE = "%s"; static const std::string BUNDLE_%d_TRX_%d_TAG = "%s"; static const int64_t BUNDLE_%d_TRX_%d_TS = %d; static const std::string BUNDLE_%d_TRX_%d_TRUNK = "%s"; static const std::string BUNDLE_%d_TRX_%d_BRANCH = "%s"; static const int64_t BUNDLE_%d_TRX_%d_VALUE = %d; """ % ( bundle_idx, trx_idx, trx.hash, bundle_idx, trx_idx, trx.address.with_valid_checksum(), bundle_idx, trx_idx, trx.address, bundle_idx, trx_idx, trx.as_tryte_string(), bundle_idx, trx_idx, trx.signature_message_fragment, bundle_idx, trx_idx, trx.current_index, bundle_idx, trx_idx, trx.last_index, bundle_idx, trx_idx, trx.nonce, bundle_idx, trx_idx, trx.tag, bundle_idx, trx_idx, trx.timestamp, bundle_idx, trx_idx, trx.trunk_transaction_hash, bundle_idx, trx_idx, trx.branch_transaction_hash, bundle_idx, trx_idx, trx.value ) return bundle_info
from iota import Iota from config import NODE_URL TAG = "BIILABS" api = Iota(NODE_URL) dict_txn = api.find_transactions(tags=[TAG]) print(dict_txn['hashes'])
from iota import Iota from config import NODE_URL TXN_BUNDLE = "YKIMBDFFYFDRFTEXGFGZYFKCPTRTCDLJCHUWJTXRJRQQGHEVOZKZYOPCO9LAGKXYWRJVWKWTVGCJZNSSA" api = Iota(NODE_URL) dict_txn = api.find_transactions(bundles=[TXN_BUNDLE]) print(dict_txn['hashes'])
class IotaCache(object): def __init__(self, uri=None, seed=None): if not uri: self.uri = "http://localhost:14700" else: self.uri = uri if not seed: self.seed = 'EBZYNR9YVFIOAZUPQOLRZXPPPIKRCJ9EJKVCXMYVLMNOCCOPYPJKCWUZNLJZZZZWTMVQUXZFYLVLZXJ9Q' else: self.seed = seed self.api = Iota(self.uri, self.seed) def cache_txn_in_tangle(self, ipfs_addr, tag): api_response = self.api.get_new_addresses() addy = api_response['addresses'][0] address = binary_type(addy).decode('ascii') result = self.api.send_transfer( depth=3, transfers=[ ProposedTransaction( address=Address(address), value=0, tag=Tag(tag), message=TryteString.from_string(ipfs_addr), ), ], ) return result def get_approved_txns(self, tag): ret = [] transactions = self.api.find_transactions(None, None, [tag], None) if len(transactions['hashes']) == 0: return ret tips = self.api.get_tips() states = self.api.get_inclusion_states(transactions['hashes'], tips['hashes']) i = 0 for txn in transactions['hashes']: if states['states'][i] is True: ret.append(txn) return ret def get_non_consumed_txns(self, tag): txn_hashes_all = self.get_approved_txns(tag) txn_trytes_all = self.api.get_trytes(txn_hashes_all) txn_hashes_consumed = self.api.find_transactions( None, None, [tag + b"CONSUMED"], None) txn_trytes_consumed = self.api.get_trytes( txn_hashes_consumed['hashes']) consumedSet = [] ret = [] for txnTrytes in txn_trytes_consumed['trytes']: txn = Transaction.from_tryte_string(txnTrytes) consumedSet.append(txn.signature_message_fragment) for txnTrytes in txn_trytes_all['trytes']: txn = Transaction.from_tryte_string(txnTrytes) if txn.signature_message_fragment not in consumedSet: msgTryte = txn.signature_message_fragment.decode() ret.append(msgTryte) return ret def set_txn_as_synced(self, ipfs_addr, tag): result = self.cache_txn_in_tangle(ipfs_addr, tag + b"CONSUMED") return result
class IotaCache(object): def __init__(self, uri=None, seed=None): if not uri: self.uri = "http://localhost:14700" else: self.uri = uri if not seed: self.seed = 'EBZYNR9YVFIOAZUPQOLRZXPPPIKRCJ9EJKVCXMYVLMNOCCOPYPJKCWUZNLJZZZZWTMVQUXZFYLVLZXJ9Q' else: self.seed = seed self.api = Iota(self.uri, self.seed, testnet=True) self.mwm = 1 self.depth = 15 def cache_txn_in_tangle_sdk(self, ipfs_addr, tag): api_response = self.api.get_new_addresses() addy = api_response['addresses'][0] address = binary_type(addy).decode('ascii') result = self.api.send_transfer( depth=self.depth, transfers=[ ProposedTransaction( address=Address(address), value=0, tag=Tag(tag), message=TryteString.from_string(ipfs_addr), ), ], min_weight_magnitude=self.mwm, ) return result def cache_txn_in_tangle_simple(self, data, tag): address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX" txns = self.api.get_transactions_to_approve(self.depth) tr = self.api.get_trytes([txns[u'branchTransaction']]) txn = Transaction.from_tryte_string(tr[u'trytes'][0], txns[u'branchTransaction']) txn.trunk_transaction_hash = txns[u'trunkTransaction'] txn.branch_transaction_hash = txns[u'branchTransaction'] txn.tag = Tag(TryteString.from_string(tag)) txn.signature_message_fragment = Fragment(TryteString.from_bytes(data)) attach_trytes = attachToTangle(self.uri, txns[u'trunkTransaction'].__str__(), txns[u'branchTransaction'].__str__(), 1, txn.as_tryte_string().__str__()) res = self.api.broadcast_and_store(attach_trytes[u'trytes']) return res def cache_txn_in_tangle_message(self, data, tag): #address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX" address = "14dD6ygPi5WXdwwBTt1FBZK3aD8uDem1FY" res = storeMessage(self.uri, address, data, tag) return res def get_balance(self, coin_type, account): address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX" res = getBalance(self.uri, address, coin_type, account) return res def get_approved_txns(self, tag): ret = [] transactions = self.api.find_transactions(None, None, [tag], None) if len(transactions['hashes']) == 0: return ret tips = self.api.get_tips() states = self.api.get_inclusion_states(transactions['hashes'], tips['hashes']) i = 0 for txn in transactions['hashes']: if states['states'][i] is True: ret.append(txn) return ret def get_non_consumed_txns(self, tag): ret = [] txn_hashes_all = self.get_approved_txns(tag) if len(txn_hashes_all) == 0: return ret txn_trytes_all = self.api.get_trytes(txn_hashes_all) consumedSet = [] txn_hashes_consumed = self.api.find_transactions(None, None, [tag+b"CONSUMED"], None) if len(txn_hashes_consumed['hashes']) != 0: txn_trytes_consumed = self.api.get_trytes(txn_hashes_consumed['hashes']) i=0 for txnTrytes in txn_trytes_consumed['trytes']: txn = Transaction.from_tryte_string(txnTrytes, txn_hashes_consumed['hashes'][i]) i+=1 consumedSet.append(txn.signature_message_fragment) i=0 for txnTrytes in txn_trytes_all['trytes']: txn = Transaction.from_tryte_string(txnTrytes, txn_hashes_all[i]) i+=1 if txn.signature_message_fragment not in consumedSet: msgTryte = txn.signature_message_fragment.decode() ret.append(msgTryte) return ret def set_txn_as_synced(self, ipfs_addr, tag): result = self.cache_txn_in_tangle_sdk(ipfs_addr, tag+b"CONSUMED") return result def add_neighbors(self, uris): res = addNeighbors(self.uri, uris) return res def get_block_content(self, hashes): res = getBlockContent(self.uri, hashes) return res def get_dag(self, dag_type): res = getDAG(self.uri, dag_type) return res def get_utxo(self, dag_type): res = getUTXO(self.uri, dag_type) return res def get_total_order(self): res = getTotalOrder(self.uri) return res
class Verifier: def __init__(self, id, iota_host, seed, push): self._id = id self._iota_obj = Iota(iota_host, seed) self._conn = None self._push_data = push self._initial_setup() def _initial_setup(self): _create_table_reqd = not os.path.exists(DB_FILE) self._conn = sqlite3.connect(DB_FILE) c = self._conn.cursor() if _create_table_reqd: cmd_ = "CREATE TABLE {t_name} (msg_id INTEGER PRIMARY KEY, timestamp TEXT, " \ "item_name TEXT, item_value TEXT)".format(t_name=TABLE_NAME) c.execute(cmd_) c.execute("PRAGMA TABLE_INFO ({t_name})".format(t_name=TABLE_NAME)) column_names = [t[1] for t in c.fetchall()] if self._id not in column_names: c.execute("ALTER TABLE {t_name} ADD COLUMN '{c_name}' TEXT DEFAULT 'False'"\ .format(t_name=TABLE_NAME, c_name=self._id)) self._conn.commit() def fetch_data_from_tangle(self, msg_id): txns = self._iota_obj.find_transactions( tags=[Tag(TryteString.from_unicode(msg_id))]) _trytes = self._iota_obj.get_trytes(txns['hashes']).get('trytes', []) _values = [] for _t in _trytes: _txn = Transaction.from_tryte_string(_t) _value = json.loads(_txn.signature_message_fragment.decode()) _msg_value = _value.get('data', None) _msg_topic = _value.get('topic', None) _time = _txn.timestamp print('Message ID : %s, Message Topic: %s, Value found : %s' \ %(msg_id, _msg_topic, _msg_value,)) if self._push_data: # TBD : Push back to MQTT pass _tmp = (_msg_topic, _msg_value, _time) _values.append(_tmp) return _values def verification(self, topic, value): print('Please overload this method in your class ... ') return 'False' def save_to_db(self, msg_id, timestamp, item_name, item_value, verification_ans): c = self._conn.cursor() _msg_id = int(msg_id) _time_val = str(timestamp) try: _time_val = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime(timestamp)) except: pass try: _cmd = "INSERT INTO {t_name} (msg_id, timestamp, item_name, item_value, {v_name}) "\ "VALUES ('{m_id}', '{t}', '{i_name}', '{i_val}', '{v_val}') "\ .format(t_name=TABLE_NAME, v_name=self._id, m_id=_msg_id, t=_time_val, i_name=item_name, i_val=item_value, v_val=verification_ans) c.execute(_cmd) except sqlite3.IntegrityError: # Row was already present, just update it with our verification answer c.execute("UPDATE {t_name} SET {c_name}='{c_val}' WHERE msg_id={m_id}"\ .format(t_name=TABLE_NAME, c_name=self._id, c_val=verification_ans, m_id=_msg_id)) self._conn.commit() def run(self, msg_id): values = self.fetch_data_from_tangle(msg_id) # For each msg_id there should be only one value if len(values) == 0: return elif len(values) > 1: raise Exception value = values[0] msg_topic = value[0] msg_value = value[1] msg_time = value[2] verification_ans = self.verification(msg_topic, msg_value) self.save_to_db(msg_id=msg_id, timestamp=msg_time, item_name=msg_topic, item_value=msg_value, verification_ans=verification_ans) def __del__(self): self._conn.close()
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
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 from config import NODE_URL TNX_HASH = "MFXNIHJUSCFBIJCGLJGHHVD9C9VAVACOU99LZZDGITMGQGKNPWUWQVMNANBTYSGFSZTLJKYPREHYZ9999" api = Iota(NODE_URL) dict_txn = api.find_transactions(approvees=[TNX_HASH]) print(dict_txn['hashes'])
] # Define full node to be used when retrieving cleaning records iotaNode = "https://nodes.thetangle.org:443" # Create an IOTA object api = Iota(iotaNode) # Create PrettyTable object x = PrettyTable() # Specify column headers for the table x.field_names = ["tagID", "Hotel", "Room", "last_cleaned"] # Find all transacions for selected IOTA address result = api.find_transactions(addresses=address) # Create a list of transaction hashes myhashes = result['hashes'] # Print wait message print("Please wait while retrieving cleaning records from the tangle...") # Loop trough all transaction hashes for txn_hash in myhashes: # Convert to bytes txn_hash_as_bytes = bytes(txn_hash) # Get the raw transaction data (trytes) of transaction gt_result = api.get_trytes([txn_hash_as_bytes])
class IOTAWrapper: def __init__(self, seed=IOTA_SEED, node_address=IOTA_PROVIDER): self.api = Iota(node_address, seed) def get_traffic_status_within(self, radius_in_km, latitude, longitude): """ Get traffic status within a radius from longitude and latitude""" traffics = [] if latitude is None or longitude is None: return [] transactions = self._find_transaction() if transactions is not None and len(transactions) > 0: for tx in transactions: if is_within_certain_radius(tx, float(latitude), float(longitude), radius_in_km): traffics.append(tx) return traffics def broadcast_traffic_status(self, latitude, longitude, traffic_status, tag=MTRAFFIC_REG_TAG, depth=4, min_weight_magnitude=None): logger.info( "Broadcast traffic status at lat:{}, lon:{}, status:{}".format( latitude, longitude, traffic_status)) message = { "lat": latitude, "lon": longitude, "status": traffic_status, "timestamp": get_current_timestamp() } try: transfers = [ # All hail the glory of IOTA and their dummy transactions for tag retrieval. Without multiple # transaction, Tangle doesn't seem to pick up our Tag and completely change the value of Tag ProposedTransaction( # This address is wholeheartedly irrelevant address=Address( "FNAZ9SXUWMPPVHKIWMZWZXSFLPURWIFTUEQCMKGJAKODCMOGCLEAQQQH9BKNZUIFKLOPKRVHDJMBTBFYK" ), value=0), ProposedTransaction( address=Address( "FNAZ9SXUWMPPVHKIWMZWZXSFLPURWIFTUEQCMKGJAKODCMOGCLEAQQQH9BKNZUIFKLOPKRVHDJMBTBFYK" ), value=0, tag=get_tags(tag), message=TryteString.from_string(json.dumps(message)), ) ] response = self.api.send_transfer( depth=depth, transfers=transfers, min_weight_magnitude= min_weight_magnitude, # if None, the api will use default number for main-net ) except ConnectionError as e: logger.exception("Connection error: {e}".format(e=e)) except BadApiResponse as e: logger.exception("Bad Api Response: {e}".format(e=e)) except: logger.exception("Bad coding") else: bundle = Bundle(response['bundle']) print("Bundle Hash: {}\nFrom Address: {}\nTag:".format( bundle.hash, bundle.transactions[0].address, bundle.transactions[0].tag)) return response def _find_transaction(self, tag=MTRAFFIC_REG_TAG): try: response = self.api.find_transactions(tags=[get_tags(tag)]) except ConnectionError as e: logger.exception("Connection error: {e}".format(e=e)) except BadApiResponse as e: logger.exception("Bad Api Response: {e}".format(e=e)) else: if len(response["hashes"]) < 1: return [] trytes = self.api.get_trytes(response["hashes"]) transactions = [] for trytestring in trytes["trytes"]: tx = Transaction.from_tryte_string(trytestring) transactions.append(tx) return [ json.loads(tx.signature_message_fragment.as_string()) for tx in transactions ]
def main(): #FUNCION PRINCIPAL. SIEMPRE SE LLAMA Y EXISTE PARA DAR MAYOR GRANULIDAD AL #SCRIPT, MEJORANDO SU ENTENDIMIENTO Y EL ANALISIS DE ERRORES SEED = 'INTRODUCIR SEMILLA AQUI' #CLAVE PRIVADA DEL CLIENTE EN IOTA. VER EL APARTADO 3.4. PARA SABER COMO #DEBE CREARSE. NODE = 'https://nodes.thetangle.org:443' #NODO AL QUE VAMOS A CONECTARNOS Y LEER LAS TRANSACCIONES. PARA SABER MAS #DE ESTE NODO, VER EL APARTADO 3.4. #SE TRATA DEL NODO DE LA PAGINA thetangle.org. api = Iota(NODE, SEED) #FUNCION QUE CONECTA NUESTRA SEED AL NODO CON EL QUE VAMOS A TRABAJAR. #HAY QUE TENER EN CUENTA QUE LAS TRANSACCIONES QUE VAN A ENCONTRARSE CON #LAS FUNCIONES EMPLEADAS SON LAS QUE SE ENCUENTRAN EN EL TANGLE DESDE EL #ULTIMO SNAPSHOT (VER APARTADO 3.4.) #EN LA PÁGINA THETANGLE.ORG APARECERAN MAS DE LAS QUE SE ENCONTRARAN AQUI. #YA QUE MANTIENE UN REGISTRO DE TRANSACCIONES DESPUES DE SNAPSHOTS direccion = [ Address( 'XPVUPUY9XEHE9QKFNLVYFTITCTJQXXUOUEPVRBZBFXMLWBS9NNFWNIVQUROOCLHGIKAZKHYMQJPRCXRYX' ) ] #SE TRATA DE LA DIRECCION A LA QUE SE VAN A ENVIAR LAS TRANSACCIONES DE VALOR #CERO (VER APARTADO 3.4.), PERTENECIENTE A LA SEMILLA DEL AUTOR DEL PROYECTO. #SERA LA DIRECCION EN LA QUE TRATAREMOS DE LEER LA INFORMACION. hashes = api.find_transactions(addresses=direccion) #LA FUNCION api.find_transactions PERMITE OBTENER UN DICT CON TODAS LAS #TRANSACCIONES QUE SE HAN ENVIADO A LA DIRECCION QUE SE ESPECIFIQUE. SE #GUARDA EN hashes Y SOLO NOS INTERESA EL CONTENIDO DE 'hashes'. print('¿Quiere buscar una fecha concreta? Sí (1)/N (0)))') #SALIDA POR PANTALLA QUE PREGUNTA SI QUIERES BUSCAR UNA FECHA CONCRETA O UN #INTERVALO modo = input() #FUNCION QUE PERMITE INTRODUCIR POR PANTALLA EL MODO DE BUSQUEDA if modo == 0: #CONDICIONAL SI SE SELECCIONA BUSCAR UN INTERVALO print('Escriba el intervalo:') #SALIDA POR PANTALLA QUE INDICA QUE DEBES INDICAR EL INTERVALO print('Escriba el límite superior:') #SALIDA POR PANTALLA QUE INDICA QUE DEBES INDICAR EL LIMITE SUPERIOR upper_fecha = time.mktime( datetime(input('Introduzca el anno:'), input('Introduzca el mes:'), input('Introduzca el dia:'), input('Introduzca la hora:'), input('Introduzca los min:'), input('Introduzca los seg:')).timetuple()) #FUNCION QUE TRANSFORMA EN TIEMPO UNIX UN TIEMPO ESTRUCTURADO EN #ANNO, MES, DIA, HORA Y SEGUNDO PARA FACILITAR EL INPUT DEL #LIMITE SUPERIOR. print('Escriba el límite inferior:') #SALIDA POR PANTALLA QUE INDICA QUE DEBES INDICAR EL LIMITE INFERIOR lower_fecha = time.mktime( datetime(input('Introduzca el anno:'), input('Introduzca el mes:'), input('Introduzca el dia:'), input('Introduzca la hora:'), input('Introduzca los min:'), input('Introduzca los seg:')).timetuple()) #FUNCION QUE TRANSFORMA EN TIEMPO UNIX UN TIEMPO ESTRUCTURADO EN #ANNO, MES, DIA, HORA Y SEGUNDO PARA FACILITAR EL INPUT DEL #LIMITE INFERIOR. lista_timestamp_interv(api, upper_fecha, lower_fecha, hashes) #LLAMADA A LA FUNCION lista_timestamp_interv PASANDOLE COMO INPUTS EL #ACCESO AL NODO ESPECIFICADO, LAS FECHAS LIMITES Y EL LISTADO DE HASHES #DE LA DIRECCION ESPECIFICADA. if modo == 1: #CONDICIONAL SI SE SELECCIONA BUSCAR UNA FECHA CONCRETA fecha = time.mktime( datetime(input('Introduzca el anno:'), input('Introduzca el mes:'), input('Introduzca el dia:'), input('Introduzca la hora:'), input('Introduzca los min:'), input('Introduzca los seg:')).timetuple()) #FUNCION QUE TRANSFORMA EN TIEMPO UNIX UN TIEMPO ESTRUCTURADO EN #ANNO, MES, DIA, HORA Y SEGUNDO PARA FACILITAR EL INPUT DE LA FECHA. lista_timestamp_conc(api, fecha, hashes)
''' This example fetches and prints transactions for a given address ''' from iota import Iota from iota import Transaction import pprint api = Iota('https://nodes.devnet.iota.org:443') address = 'TOKLOARHKXQCVPPVVIPIJGLUTLTKFHYGMBBLOXJFYGSARLOTYFFSDZNYCOBOCNPGRMJWZCQBNOROUCE9G' transactions = api.find_transactions(addresses=[address,]) # We found all transactions on this address, now we need to put all hashes # in a iterable to send it to the get_trytes function hashes = [] for txhash in transactions['hashes']: hashes.append(txhash) # Get Trytes accepts multiple Transaction Hashes trytes = api.get_trytes(hashes)['trytes'] # get_trytes returns us a list fo raw trytes, so we need to convert them # into transaction objects first for trytestring in trytes: tx = Transaction.from_tryte_string(trytestring) print('\n\nTransaction %s (tag %s):' % (tx.hash, tx.tag)) # To see what's avaialble in this object uncomment the next line
from datetime import datetime from iota import Address, Iota, Transaction with open("tangle/config/address_tan.conf") as in_file: # read as string # strip any carriage return characters # and encode as bytes() ADDRESS = in_file.read().rstrip("\n").encode() # 0. Where is data stored? receiver = Address(ADDRESS) # 1. Connect to public node api = Iota("https://durian.iotasalad.org:14265") # 2. Retrieve all transactions txs = api.find_transactions(addresses=[receiver]) # 3. Iterate over transactions, decode and print for tx_hash in txs["hashes"]: tx_hash_b = bytes(tx_hash) tx_data_trytes = api.get_trytes([tx_hash_b]) tryte_str = str(tx_data_trytes["trytes"][0]) tx = Transaction.from_tryte_string(tryte_str) timestamp = datetime.fromtimestamp(tx.timestamp) tx_data = str(tx.signature_message_fragment.decode()) print("{ts}: {tx}".format(ts=timestamp, tx=tx_data))
from iota import Iota from config import NODE_URL ADDRESS = "SSEFNDKCIFHOFFCA9IXNBEQIYUQEXHIIHQIOWIEEAFBENHVS9ZASLWKPZNQFSTUCQXJAOKJDDHVXVXGUBBA9CFNYXW" api = Iota(NODE_URL) dict_txn = api.find_transactions(addresses = [ADDRESS]) print(dict_txn['hashes'])
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']