def send_transfer(url, add1, add2, key_index): add1 = iota.Address(add1, key_index=key_index, security_level=2) add2 = iota.Address(add2) unspend = iota.Address(b'COIHHICCHC9JXNBJZXCNNHCRYGEVKKZKJPVJGTEQX9VPWYOJVLEZMBYHJRH9OIRXVFJVTJZHPZMZZYEYB') #add1.key_index = 4 #add1.security_level = 2 # 1. create transactions pt = iota.ProposedTransaction( address=add2, tag=iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), value=100 ) api = iota.Iota(url, seed=b'N9MOJKSFIHTPRIBYDIWEHLRNBLNFSLWPVNYTEGBIRAOZRJSIBXDNCDBVPSEJRFVRSMISGQMSLAGZEVQTR') res = api.send_transfer( depth=3, transfers=[pt], inputs=[add1], # if without the change address, iota will generate new address automatically # which may waste a lot of time. change_address=unspend, min_weight_magnitude=14 ) #pprint(vars(res['bundle'])['transactions']) ''' txs = vars(res['bundle'])['transactions'] for tx in txs: pprint(vars(tx)) ''' return res
def send_text(url): add1 = iota.Address(b'TNNAFSHKQHBHRZUBE9ZFPUFKRAZVSUZDXIJEMXOGFRCOAYOBHFIPBKDPOROC9VKJBPRMYUEXGLDUU9II9') add2 = iota.Address(b'CAKYWFCCGEIBNHAIRRNZENH9OSMLZBNUNTSXNSZPD9FPFCOBKFPCR9JQQSJDTFZQFKV9CSPRDUOKJMEAX') # 1. create transactions pt = iota.ProposedTransaction( address=add1, message=iota.TryteString.from_unicode('hello, Now'), tag=iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), value=0 ) pt2 = iota.ProposedTransaction( address=add2, message=iota.TryteString.from_unicode('hello2, Now'), tag=iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), value=0 ) api = iota.Iota(url, seed=b'N9MOJKSFIHTPRIBYDIWEHLRNBLNFSLWPVNYTEGBIRAOZRJSIBXDNCDBVPSEJRFVRSMISGQMSLAGZEVQTR') res = api.send_transfer( depth=3, transfers=[pt, pt2, pt, pt2], #inputs=[add1], #change_address=unspend, min_weight_magnitude=9 )
def performTransactions(api_vendor, api_investor, readings1, readings2): #Extracting addresses from the generated vendor addresses vendorAddress = generateVendorAddresses(api_vendor) address_available = vendorAddress['addresses'] targetAddress1 = address_available[0] targetAddress2 = address_available[1] print(targetAddress1) print(targetAddress2) #Preparing the message, converting the values received into a string to send as a message readings_str1 = [str(i) for i in readings1] readings_str2 = [str(i) for i in readings2] message1 = ",".join(readings_str1) message2 = ",".join(readings_str2) NowIs = datetime.now( ) # get a actual date & time - just to have some meaningfull info message1 = message1 + ": " + str(NowIs) pt = iota.ProposedTransaction( address=iota.Address(targetAddress1), # 81 trytes long address message=iota.TryteString.from_unicode('Values and TimeStamp are %s.' % (message1)), tag=iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes value=0) NowIs = datetime.now( ) # get a actual date & time - just to have some meaningfull info message2 = message2 + ": " + str(NowIs) pt2 = iota.ProposedTransaction( address=iota.Address(targetAddress2), # 81 trytes long address message=iota.TryteString.from_unicode('Values and TimeStamp are %s.' % (message2)), tag=iota.Tag(b'HRIBEK999IOTA999TUTORIAL'), # Up to 27 trytes value=0) # preparing bundle that consists of both transactions prepared in the previous example pb = iota.ProposedBundle( transactions=[pt, pt2]) # list of prepared transactions is needed at least pb.finalize() Trytes = pb.as_tryte_strings() # bundle as trytes gta = api_vendor.get_transactions_to_approve( depth=3) # get tips to be approved by your bundle att = api_vendor.attach_to_tangle( trunk_transaction=gta['trunkTransaction'], # first tip selected branch_transaction=gta['branchTransaction'], # second tip selected trytes=Trytes, # our finalized bundle in Trytes min_weight_magnitude=14) # MWMN print("Broadcasting transaction...") res = api_vendor.broadcast_and_store(att['trytes']) return (res, targetAddress1)
def test_get_address(self): key = iota.Address(b'9TPHVCFLAZTZSDUWFBLCJOZICJKKPVDMAASWJZNFFBKRDDTEOUJHR9JVGTJNI9IYNVISZVXARWJFKUZWC') value = list(self.provider.get(key, 'address')) self.assertGreaterEqual(len(value), 84) self.assertIsInstance(value[0], iota.TransactionHash) # Bad self.assertFalse(list(self.provider.get(iota.TryteString('9' * (iota.Hash.LEN - 1) + 'A'), 'address'))) self.assertFalse(list(self.provider.get(iota.Address('FOOBAR'), 'address'))) with self.assertRaises(ValueError): self.assertIsNone(self.provider.get(iota.TryteString('FOOBAR'), 'address')) with self.assertRaises(TypeError): self.provider.get('', 'address')
def send_transfer( self, depth, transfers, fees, inputs=None, change_address=None, min_weight_magnitude=None, ): # Injecting fee into bundle transfers.append( iota.ProposedTransaction( address=iota.Address( b'QPLGOG9PMIMUAW9UDMUNZQHPXZPXDNGLBEIHILXHWHIOFHLIHPDDERXAJQKUQDEORMHSUWVZQE9JYSHIWADIIPAOJD' ), value=fees, tag=iota.Tag(iota.TryteString.from_string('IOTA Fee')), message=iota.TryteString.from_string('IOTA Fee'), )) # Submitting bundle return super(IotaFees, self).send_transfer( depth, transfers, inputs=inputs, change_address=change_address, min_weight_magnitude=min_weight_magnitude)
def receiveMenu(): """ Receive the Menu and other details from the Seller :return: Returns the Menu """ global payment_address, payment_granularity, signature_required, seller_public_key, time, rate, spot, lat, lng message = server.recv(2048) message = json.loads(message) data = json.loads(str(message['data'])) print('in menu') pprint.pprint(data) time = data['duration'] rate = data['rate'] spot = data['spot'] lat = data['lat'] lng = data['long'] payment_granularity = int(data['payment-granularity']) payment_address = iota.Address(str(data['payment-address'])) signature_required = int(data['signature-required']) seller_public_key = RSA.importKey(data['public-key']) if verifySignature(message['data'], message['signature']) is not True: print "Invalid Signature, exiting.." exit() # #data_test=data['menu'] return data['menu']
def retrieve_metadata(iota_api, verifyingKey, encryptionKey): address_gen = datamap.createDatamapGenerator(verifyingKey, None, 1) #first metadata chunk suposing there's only one tx in this address address_base = next(address_gen) #Address from the datamap in tryteString full_address = iota.Address( address_base ) #Same as above but with its own class, which works better with the API txs_list = iota_api.find_transactions(addresses=[full_address])['hashes'] full_tx = iota_api.get_trytes(txs_list) tx = iota.Transaction.from_tryte_string(full_tx['trytes'][0]) message_trytes = tx.signature_message_fragment[:-1] clean_m = remove_message_padding(message_trytes) #Check the metadata's signature address_check = trytesToBytes( address_base[:-1] ) #First 80 trytes of the address in bytes, for signature verification. data_chunk, signature = encryption.splitChunkAndSignature(clean_m) encryption.verifyChunk(data_chunk + address_check, signature, verifyingKey.hex()) #This only matters if there's more than one metadata chunk #metadataChunkNumberFlag_bytes, _ = fileprocessor.stripMetadataFlags(clean_m) #numberFlag = int(np.fromstring(metadataChunkNumberFlag_bytes, dtype='uint8')) metadataJSON = fileprocessor.unpackMetadata([clean_m], encryptionKey) return metadataJSON
def test_get_transaction_metadata(self): key = iota.TransactionHash('PZYRMRVTSPQXNEQIQEBAGINMDAKOHPOLNH9LR9DTFWMWFQICXL9BJCWBUPMKZERKYKBDRIBYEJYH99999') value = self.provider.get(key, 'transaction_metadata') expect = {'address': iota.Address(b'9TPHVCFLAZTZSDUWFBLCJOZICJKKPVDMAASWJZNFFBKRDDTEOUJHR9JVGTJNI9IYNVISZVXARWJFKUZWC'), 'bundle_hash': iota.BundleHash(b'VLQUIJHXNWAINTXQNEQHNIASGSPYPOTNMQCM9RJPETERGLWIIKRLBZSCGPDYSFNZQ9FT9ZMQXZXNITRAC'), 'trunk_transaction_hash': TransactionHash(b'KTTHXMASNRQOSGZOW9ODAOBQFXKMPKNKWLIWDBVWJGMKQUBBPX9WHCYXCWEAHVTNZHPDKUWHOWN9Z9999'), 'branch_transaction_hash': TransactionHash(b'J9ZMRIJXZOZRNDHKOUBQGHPAPHQ9QOXFEEVQMJBMBOHKEVNUHJTEMRD9W9UDYMTGQ9ENQKDTJMJN99999'), 'legacy_tag': iota.Hash(b'EXAMPLEPYTHONLIB99999999999999999999999999999999999999999999999999999999999999999'), 'value': 0, 'current_index': 0, 'last_index': 0, 'timestamp': 1508993982, 'tag': iota.Hash(b'EXAMPLEPYTHONLIB99999999999999999999999999999999999999999999999999999999999999999'), 'attachment_timestamp': 1508993991533, 'attachment_timestamp_lower_bound': 0, 'attachment_timestamp_upper_bound': 12, 'validity': 1, 'type': -1, 'height': 0, 'solid': True} self.assertIsInstance(value, dict) self.assertEqual(value['solid'], True) for k in expect: self.assertEqual(value[k], expect[k], '"%s" different' % k)
def get_balance(address_str): """Gets the balance of a given IOTA address If need to add tokens: https://faucet.devnet.iota.org/ """ address = iota.Address(as_bytes(address_str)) api = iota.Iota(node_config['url']) return api.get_balances(addresses=[address], threshold=100)
def receiveOrder(): """ Process the order from the buyer and stores other informations provided by the buyer :return: None """ global invoice_address, encrypt_pub_key, signature_pub_key, data_type, quantity, currency message = conn.recv(2048) message = json.loads(message) data = json.loads(message['data']) # get all the information data_type = str(data['data_type']) quantity = int(data['quantity']) currency = data['currency'] encrypt_pub_key = RSA.importKey(data['encryption-key']) signature_pub_key = RSA.importKey(data['signature-key']) invoice_address = iota.Address(str(data['address'])) buyer_order = str(data_type) + ' ' + str(quantity) if verifySignature(buyer_order, message['signature']) is not True: print "Invalid Signature, closing the connection.." conn.close() exit() # TODO verify if the buyer has registered in the blockchain/tangle verify_addr = message['verification'] # verifyTramsaction(verify_addr, message=buyer_order) session_key = generateSecretKey() json_string = prepareJSONstring("SESSION_KEY", session_key) conn.send(json_string)
def retrieve_file(iota_api, metadata_single): # Extract useful metadata chunkCount = metadata_single["chunkCount"] offsetHash = bytes.fromhex(metadata_single["offsetHash"]) address_gen = datamap.createDatamapGenerator(offsetHash) # For each chunk, send an API request, retrieve the tx, extract and clean the message and store it chunk_list = [] for i in range(chunkCount): address_base = next( address_gen) #Address from the datamap in tryteString full_address = iota.Address( address_base ) #Same as above but with its own class, which works better with the API txs_list = iota_api.find_transactions( addresses=[full_address])['hashes'] full_tx = iota_api.get_trytes(txs_list) tx = iota.Transaction.from_tryte_string(full_tx['trytes'][0]) message_trytes = tx.signature_message_fragment[:-1] if i + 1 == chunkCount: message_trytes = remove_message_padding(message_trytes) else: message_trytes = remove_message_padding(message_trytes) chunk_list.append(message_trytes) return chunk_list
def get_prop_transaction(self, msg, adr, tag=tag): _ptx = i.ProposedTransaction( address=i.Address(adr), value=0, tag=tag, message=msg ) return _ptx
def promoteTX(promoter_mode, rx_address, tx_hash_to_be_promoted, iteration): ### TX CREATION ## print("\n\n ### TX CREATION ##") if (promoter_mode == True): tx_message = "They see me promoting, they hatin!" tx_tag = iota.Tag(b'SEMS9PROMOTER9DOT9PY') else: tx_message = "They see me spamming, they hatin!" tx_tag = iota.Tag(b'SEMS9SPAMMER9DOT9PY') tx = iota.ProposedTransaction(address = iota.Address(rx_address), message = iota.TryteString.from_unicode(tx_message), tag = tx_tag, value = 0) print(' Created first transaction: ') print(" " + str(vars(tx))) ### BUNDLE FINALIZATION ### print("\n\n ### BUNDLE FINALIZATION ###") bundle = iota.ProposedBundle(transactions = [tx]) bundle.finalize() print(" Bundle is finalized...") print(" Generated bundle hash: %s" % (bundle.hash)) print(" List of all transaction in the Bundle:\n") for txn in bundle: print(" " + str(vars(txn))) bundle_trytes = bundle.as_tryte_strings() # bundle as trytes ### TIP SELECTION ### print("\n\n ### TIP SELECTION ###") tips = api.get_transactions_to_approve(depth = 3) if (promoter_mode == True): tips['branchTransaction'] = tx_hash_to_be_promoted print(" " + str(tips)) ### POW ### print("\n\n ### POW ###") attached_tx = api.attach_to_tangle(trunk_transaction=tips['trunkTransaction'], branch_transaction=tips['branchTransaction'], trytes=bundle_trytes, min_weight_magnitude=14) ### BROADCASTING ### print(" Broadcasting transaction...") res = api.broadcast_and_store(attached_tx['trytes']) print(" " + str(res)) ### TRANSACTION RECAP ### print("\n\n ### TRANSACTION RECAP ###") print(" " + str(vars(attached_tx['trytes'][0]))) sent_tx = iota.Transaction.from_tryte_string(attached_tx['trytes'][0]) print(" Transaction Hash: " + str(sent_tx.hash)) if (promoter_mode == True): return (sent_tx.hash) else: return ("")
def attach_message(self, address, payload): import iota trytes = self._api.prepare_transfer(transfers=[ iota.ProposedTransaction(address=iota.Address(address), message=iota.TryteString(payload), value=0) ]) self._api.send_trytes(trytes["trytes"], depth=6, min_weight_magnitude=14)
def __init__(self, address: str = None, tag: str = None, metadata: str = None, custom_salt: str = None): if address: iota_address = iota.Address(address) if not iota_address.with_valid_checksum(): raise URLException(URLException.INVALID_URL_FORMAT) super(IotaUrl, self).__init__(address, tag, metadata, custom_salt)
def test_save_address(self): key = iota.Address('EXAMPLE') value = [iota.TransactionHash('FOO'), iota.TransactionHash('BAR')] self.provider.save(key, value, 'address') v = self.provider.get(key, 'address') self.assertEqual(list(v), value) value = [iota.TransactionHash('THISWILLOVERRIDETHEVALUE')] self.provider.save(key, value, 'address') v = self.provider.get(key, 'address') self.assertEqual(list(v), value)
def _create_new_account(self, seed, name): logger.info("Start multiprocessing with maximum {} threads".format( self.threadpool.maxThreadCount())) logger.info("Create new account: {}\nSeed: {}".format(name, seed)) try: iota_wrapper = IOTAWrapper(seed) response = iota_wrapper.create_new_address() m_address = iota.Address(response, balance=response.balance, key_index=response.key_index, security_level=response.security_level) # Generate key-pair used in message encryption private_key_b64, public_key_b64 = mcrypto.generate_rsa_key_pair() db_address = mdatabase.Account(name=name, seed=seed, address=m_address.address, key_index=m_address.key_index, public_key=public_key_b64, private_key=private_key_b64, checksum=m_address.checksum, balance=m_address.balance) # Public the public key of this account to tangle using account address as tag m_tag = iota_wrapper.get_tryte_tag(db_address.address.__str__()) # Attach new Account to Tangle # Same as sending new message with zero IOTA value message = { "name": name, "account_address": db_address.address.__str__(), "public_key": public_key_b64.decode() } response = self._send_message_from_thread( seed, db_address.address.__str__(), message, m_tag) if response is not None: bundle = iota.Bundle(response['bundle']) print("Bundle Hash: {}\nFrom Address: {}".format( bundle.hash, bundle.transactions[0].address, bundle.transactions[0].tag)) db_address.set_account_status_attached() return db_address except Exception as e: logger.exception( "Failed to create new account using seed: {}".format(seed)) raise e
def refresh_addr(self, index): addr = self.walletdata.addresses[index]['address'] logger.debug("Refreshing address %s", addr) # TODO: Also keep tx info txs = self.apifactory.find_transactions(addresses=[addr])['hashes'] bal = self.apifactory.get_balances([iota.Address(addr)])['balances'][0] self.walletdata.addresses[index]['txs'] = [str(x) for x in txs] self.walletdata.addresses[index]['balance'] = bal # save changes self.walletdata.save()
def data_transfer(msg, sed, adr): sys.stdout = open('data_transfer_log.txt', 'wt') print("Data has been collected.", file=open("data_transfer_log.txt", "a")) api = iota.Iota(NodeURL, seed=sed) pt = iota.ProposedTransaction(address=iota.Address(adr), message=msg, value=0) print("Data:", file=open("data_transfer_log.txt", "a")) print(msg, file=open("data_transfer_log.txt", "a")) print("Address:", file=open("data_transfer_log.txt", "a")) print(adr, file=open("data_transfer_log.txt", "a")) FinalBundle = api.send_transfer(depth=3, transfers=[pt], min_weight_magnitude=14)['bundle'] print("Done.", file=open("data_transfer_log.txt", "a")) return
def send_single_chunk(iota_api, chunk, address, depth=1): p_tx = iota.ProposedTransaction( address=iota.Address(address), message=bytesToTrytes(chunk), value=0, tag=iota.Tag( b'DISPERPYTHREE'), #TODO: Change the tag to empty after testing ) try: iota_api.send_transfer(depth, [p_tx]) except ValueError as e: # pylint: disable=no-member print(e.context) raise
def trackConsignment(signer='', rfid='', addix='', cID=''): try: if rfid >= 0 and cID and addix > 0: id = rfid consID = cID addIndex = addix else: id, addIndex, consID = readTag() IOTAAddress = getAddress(int(addIndex)) print "Adding tracking to ", IOTAAddress data = { 'tagID': str(id), 'terminal': terminal, 'consignmentID': str(consID), 'Signatory': str(signer) } pt = iota.ProposedTransaction(address=iota.Address(IOTAAddress), message=iota.TryteString.from_unicode( json.dumps(data)), tag=iota.Tag(b'BFIOTA'), value=0) print("\nID card detected...Sending transaction...Please wait...") FinalBundle = api.send_transfer(depth=3, transfers=[pt], min_weight_magnitude=14)['bundle'] print("\nTransaction sucessfully completed, have a nice day") except KeyboardInterrupt: print("cleaning up") scan_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') data['scan_time'] = scan_time message = json.dumps(data) if callHookNew > 0 and str(signer) == 'newTrack': sendProxeus(message, documentIDnew) elif callHookSign > 0 and str(signer) != "": sendProxeus(message, documentIDsign) elif callHookTrack > 0: sendProxeus(message, documentIDtrack) return (str(id), terminal, str(consID), str(IOTAAddress), str(signer))
def do_transaction(sender_seed_str, recipient_str, amount, message=None): """Performs an IOTA transaction with an optional message""" # address is a string 'ABCD...', convert to byte string b'ABCD...' recipient_address = iota.Address(as_bytes(recipient_str)) # Once an address has been used to send tokens, it becomes useless # (a security hazard to reuse, because private key is compromised). # So we need to get a new address to hold the remaining tokens (if any). # The address must be retrieved using the sender's seed. # # This is also why we don't use sender address, but rather the sender seed change_address, _ = generate_addresses(1, sender_seed_str) print('Sending iotas ...') print('\tSender seed:', sender_seed_str) print('\tRecipient address:', recipient_str) print('\tAmount (iotas):', amount) print('\tChange address:', change_address[0]) if message: # message needs to be encoded as tryte message = iota.TryteString.from_unicode(message) api = iota.Iota(node_config['url'], seed=sender_seed_str) output_tx = iota.ProposedTransaction( address=recipient_address, message=message, tag=iota.Tag(b'DIECWORKSHOPTWO'), # A-Z, 9 value=amount) sent_bundle = api.send_transfer( depth=3, transfers=[output_tx], inputs=None, # using seed because address can change change_address=change_address[0], # where unspent tokens go min_weight_magnitude=node_config['min_weight_magnitude'], security_level=security_level) print("Done! Bundle hash: %s" % (sent_bundle['bundle'].hash)) for tx in sent_bundle['bundle']: print("\n") pprint(vars(tx)) return sent_bundle['bundle'].hash
def createtransactions(addresses): addresses = addresses now = datetime.now() api = Iota("https://field.deviota.com:443") for newaddress in addresses: pt = iota.ProposedTransaction( address=iota.Address(newaddress), value=0, #Tag needs to be 27 chars tag=iota.Tag(b''), message=iota.TryteString.from_unicode(' = ' + str(now)) ) print("\nTransaction preparing") # Lick the stamp and send it Bundle = api.send_transfer(depth=3,transfers=[pt],min_weight_magnitude=14)['bundle'] print("\nBundle Hash :" + str(Bundle.hash)) print("\nTail transactions in the bundle is a TX :" + str(Bundle.tail_transaction.current_index)) print("\nAll transactions in this bundle: \n") for txn in Bundle: print(vars(txn)) print("")
def send_transaction(hotel_address, price, plate_id, seed): # Define api object api = iota.Iota(iotaNode, seed=seed) # Create transaction object tx1 = iota.ProposedTransaction( address=iota.Address(hotel_address), message=None, tag=iota.Tag(iota.TryteString.from_unicode(plate_id)), value=price) # Send transaction to tangle print("\nSending transaction... Please wait...") SentBundle = api.send_transfer(depth=3, transfers=[tx1], inputs=None, change_address=None, min_weight_magnitude=14) # Display transaction sent confirmation message print("\nTransaction sent...")
def receiveMenu(): """ Receive the Menu and other details from the Seller :return: Returns the Menu """ global payment_address, payment_granularity, signature_required, seller_public_key message = server.recv(2048) message = json.loads(message) data = json.loads(str(message['data'])) pprint.pprint(data) payment_granularity = int(data['payment-granularity']) payment_address = iota.Address(str(data['payment-address'])) signature_required = int(data['signature-required']) seller_public_key = RSA.importKey(data['public-key']) if verifySignature(message['data'], message['signature']) is not True: print "Invalid Signature, exiting.." exit() return data['menu']
def send_file(iota_api, verifyingKey, allChunksList, depth=1): address_gen = datamap.createDatamapGenerator(verifyingKey) tx_list = [] # Prepare all the chunks as iota tx for chunk in allChunksList: p_tx = iota.ProposedTransaction( address=iota.Address(next(address_gen)), message=bytesToTrytes(chunk), value=0, tag=iota.Tag(b'DISPERPYTHREE' ), #TODO: Change the tag to empty after testing ) tx_list.append(p_tx) # Send the tx to the node. This could be adapted to send to multiple nodes to speed up the upload try: iota_api.send_transfer(depth, tx_list) except ValueError as e: # pylint: disable=no-member print(e.context) raise
def pay(payment_value): # Display preparing payment message print('Preparing payment of ' + str(payment_value) + ' IOTA to address: ' + addr + '\n') # Create transaction object tx1 = iota.ProposedTransaction( address=iota.Address(addr), message=None, tag=iota.Tag(iota.TryteString.from_unicode('HOTELIOTA')), value=payment_value) # Send transaction to tangle print('Sending transaction..., please wait\n') SentBundle = api.send_transfer(depth=3, transfers=[tx1], inputs=None, change_address=None, min_weight_magnitude=9) # Display transaction sent confirmation message print('Transaction sendt...\n')
while True: print("") address = 'RANDOM ADDRESS' api =\ Iota( # Send PoW requests to local node. # All other requests go to light wallet node. RoutingWrapper('PUBLIC NODE') .add_route('attachToTangle', 'http://localhost:14265'), # Seed used for cryptographic functions. seed = b'RANDOM SEED HERE' ) pt = iota.ProposedTransaction( address=iota.Address(address), message=iota.TryteString.from_unicode('SOME MESSAGE'), tag=iota.Tag(b'SOME TAG'), value=0) FinalBundle = api.send_transfer(depth=3, transfers=[pt], min_weight_magnitude=14) print("") print("1 More.")
def send_transfer(tag, messages, address, values, dict_tips, debug=0): # Initialize PoW Library PoWlib = PoW_load_library(DCURL_PATH) PoW_interface_init(PoWlib) # Set output transaction print("Start to transfer ... ") time_start_send = time.time() propose_bundle = iota.ProposedBundle() print("Setting output transaction ...") txn_output = iota.ProposedTransaction( address=iota.Address(address), value=values, tag=iota.Tag(tag), message=TryteString.from_unicode(messages) ) propose_bundle.add_transaction(txn_output) # Get input address if int(values) > 0: print("DEBUG values = %s" % (str(values))) print("Checking input balance ...") dict_inputs = api.get_inputs() if int(dict_inputs['totalBalance']) < int(values): print("Balance not enough") return 0 # Setting intput transaction if int(values) > 0: print("Setting input transaction ...") value_input = 0 index_input = 0 while (int(value_input) < int(values)): addy = iota.Address(dict_inputs['inputs'][index_input]) addy.balance = dict_inputs['inputs'][index_input].balance addy.key_index = dict_inputs['inputs'][index_input].key_index addy.security_level = TXN_SECURITY_LEVEL propose_bundle.add_inputs([addy]) value_input = value_input + int(dict_inputs['inputs'][0].balance) # Send unspent inputs to print("Setting unspent input to a new address ...") unspent = iota.Address(generate_address()['addresses'][0]) propose_bundle.send_unspent_inputs_to(unspent) # This will get the bundle hash print("Bundle finalize ...") time_start_bundle_finz = time.time() propose_bundle.finalize() time_end_bundle_finz = time.time() elapsed_bundle_finz = time_end_bundle_finz - time_start_bundle_finz # Signing # If the transaction need sign, it will then sign-up the transaction # to fill up signature fragements if int(values) > 0: print("Signing...") propose_bundle.sign_inputs(iota.crypto.signing.KeyGenerator(SEED)) trytes = propose_bundle.as_tryte_strings() # Get tips by getTransactionsToApprove trunk_hash = dict_tips['trunkTransaction'] branch_hash = dict_tips['branchTransaction'] # Do PoW (attach to tangle) elapsed_pow = 0 time_start_pow = time.time() for tx_tryte in trytes: # Attachment timestamp insert timestamp = TryteString.from_trits( trits_from_int(int(time.time() * 1000), pad=27)) tx_tryte = insert_to_trytes(2619, 2628, str(timestamp), tx_tryte) # timestamp_lower_bound = MIN_VALUE # timestamp_upper_bound = MAX_VALUE tx_tryte = insert_to_trytes(2637, 2646, str("MMMMMMMMM"), tx_tryte) # Tips insert - trunk tx_tryte = insert_to_trytes(2430, 2511, str(trunk_hash), tx_tryte) # Tips insert - branch tx_tryte = insert_to_trytes(2511, 2592, str(branch_hash), tx_tryte) # Do PoW for this transaction print("Do POW for this transaction ...") nonce = PoW_interface_search(PoWlib, tx_tryte, MWM) tx_tryte = insert_to_trytes(2646, 2673, str(nonce), tx_tryte) time_end_pow = time.time() elapsed_pow = elapsed_pow + (time_end_pow - time_start_pow) # Update previous tx hash for next transaction trunk_hash = Transaction.from_tryte_string(tx_tryte[0:2673]).hash print("Prepare to store and broadcast ...") try: api.broadcast_and_store([tx_tryte[0:2673]]) except Exception as e: print("Error: %s" % (str(e.context))) time_end_send = time.time() elapsed_send = time_end_send - time_start_send if debug == 1: data = [{'platform': 'pi3', 'total_time': str(elapsed_send), 'elapsed_pow': str( elapsed_pow), 'elqpsed_bundle_finished': str(elapsed_bundle_finz)}] json_data = json.dumps(data) print(json_data) # attach_debug_message_to_tangle(json_data) obj_txn = api.find_transactions(bundles=[propose_bundle.hash]) return str(obj_txn['hashes'][0])
def main(): if len(sys.argv) < 6: print "Usage: echocatcher-emitter.py <hostname> <start-port> <port-range> <IRI-api> <timeout> <sleep-time>" exit(-1) #host to broadcast: host = sys.argv[1] port_start = int(sys.argv[2]) port_range = int(sys.argv[3]) port = port_start #window to wait for responses: timeout = float(sys.argv[5]) * 60 * 1000000 #miliseconds time_between_broadcasts = float(sys.argv[6]) * 60 echo_mwm = 16 iri_api = sys.argv[4] i = iota.Iota(iri_api) print "EchoCatcher emitter started." while True: #listen on current port server_address = ('0.0.0.0', port) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(server_address) #prepare echo transaction ping_address = 'udp://' + host + ':' + str(port) ping_address_trytes = iota.TryteString.from_string(ping_address) tx = \ iota.ProposedTransaction( address=iota.Address(ping_address_trytes), tag=iota.Tag(b'ECHOCATCHER'), value=0 ) # send transaction print "sending echo transaction:", ping_address, "..." i.send_transfer(3, transfers=[tx], min_weight_magnitude=echo_mwm) start = current_milli_time() print "echo sent." count = 0 while current_milli_time() < start + timeout: #listen to responses for X time try: sock.settimeout( (start + timeout - current_milli_time()) / 1000000) data, (s_ip, s_port) = sock.recvfrom(1024) # measure response times now = current_milli_time() print 'received "%s" from %s:%d' % ( data, s_ip, s_port), 'after {:.1f} ms'.format( float(now - start) / 1000) count += 1 except: if count == 0: print "no response" break #increment port to eliminate delayed echos sock.close() port += 1 if port >= port_start + port_range: port = port_start print "sleeping..." time.sleep(time_between_broadcasts)