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 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 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 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 prepareTransaction(message=None, value=0): transaction = iota.ProposedTransaction( address=payment_address, value=value, # TODO: put the actual value message=iota.TryteString.from_string("Data Invoice"), tag=iota.Tag(b"SDPPBUYER") ) return sendTransaction(transaction)
def test_save_tag(self): key = iota.Tag('EXAMPLE') value = [iota.TransactionHash('FOO'), iota.TransactionHash('BAR')] self.provider.save(key, value, 'tag') v = self.provider.get(key, 'tag') self.assertEqual(list(v), value) value = [iota.TransactionHash('THISWILLOVERRIDETHEVALUE')] self.provider.save(key, value, 'tag') v = self.provider.get(key, 'tag') self.assertEqual(list(v), value)
def prepareTransaction(value=0, message=None): """ Prepares the transaction to be made through the distributed ledger :param message: Message for the payment :param value: Amount of cryptocurrencies to be sent :return: Transaction ID/ Address/ Transaction hash """ if message: message = iota.TryteString.from_string(message) tag = iota.Tag(b"SDPPSELLER") transaction = iota.ProposedTransaction(address=invoice_address, value=value, message=message, tag=tag) return sendTransaction(transaction)
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 test_get_tag(self): key = iota.Tag(b'EXAMPLEPYTHONLIB') value = list(self.provider.get(key, 'tag')) expect = [ TransactionHash(b'GTXDTJVUTVSNHYFPJUOWFKTGQTCMNKZPJDJXSWVQWTXYRDZAVZTX9KFBRIMRQEQLMCMVAUKMZWMHA9999'), TransactionHash(b'PZYRMRVTSPQXNEQIQEBAGINMDAKOHPOLNH9LR9DTFWMWFQICXL9BJCWBUPMKZERKYKBDRIBYEJYH99999'), TransactionHash(b'UNUK99RCIWLUQ9WMUT9MPQSZCHTUMGN9IWOCOXWMNPICCCQKLLNIIE9UIFGKZLHRI9QAOEQXQJLL99999') ] for v in value: self.assertIn(v, expect) # Bad with self.assertRaises(TypeError): self.assertIsNone(self.provider.get(iota.TryteString('FOOBAR'), 'tag')) with self.assertRaises(TypeError): self.provider.get('', 'tag')
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 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')
address = 'ADDRESS' api =\ Iota( # Send PoW requests to local node. # All other requests go to light wallet node. RoutingWrapper('https://nodes.thetangle.org:443') .add_route('attachToTangle', 'https://nodes.thetangle.org:443'), # Seed used for cryptographic functions. seed = b'YOUR SEED HERE' ) pt = iota.ProposedTransaction( address=iota.Address(address), message=iota.TryteString.from_unicode('MESSAGE'), tag=iota.Tag(b'TAG'), value=0) FinalBundle = api.send_transfer(depth=2, transfers=[pt], min_weight_magnitude=14) Number += 1 print("") print Number, "Transactions." except: print('Error\n')
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)
myseed = iota.crypto.types.Seed.random() pprint('Generated seed is:') pprint(myseed) #Generate two addresses addres_generator = iota.crypto.addresses.AddressGenerator(myseed) addys = addres_generator.get_addresses(1, count=2) pprint('Generated addresses are:') pprint(addys) NowIs = datetime.now() # get a actual date & time - just to have some meaningfull info # preparing transactions pt = iota.ProposedTransaction(address = iota.Address(addys[0]), # 81 trytes long address message = iota.TryteString.from_unicode('Hey hey, trying to figure this thing out. This is tx1, now is %s' % (NowIs)), tag = iota.Tag(b'LOCALATTACHINTERFACE99999'), # Up to 27 trytes value = 0) pt2 = iota.ProposedTransaction(address = iota.Address(addys[1]), # 81 trytes long address message = iota.TryteString.from_unicode('Hey hey, trying to figure this thing out. This is tx2, now is %s' % (NowIs)), tag = iota.Tag(b'LOCALATTACHINTERFACE99999'), # Up to 27 trytes value = 0) # besides the given attributes, library also adds a transaction timestamp # preparing bundle that consists of both transactions prepared in the previous example pb = iota.ProposedBundle(transactions=[pt2,pt]) # list of prepared transactions is needed at least # generate bundle hash using sponge/absorb function + normalize bundle hash + copy bundle hash into each transaction / bundle is finalized pb.finalize() #bundle is finalized, let's print it
# Check if enough funds to pay for service # if balance < blinks: # print("Not enough funds available on IOTA debit card") # exit() URL = "http://192.168.1.6:5000/getAmount" PARAMS = {'id':id} r = requests.post(url = URL, data = PARAMS) print(r.text) amount = r.text if(balance < amount) print("Not enought amount") continue # Create new transaction tx1 = iota.ProposedTransaction( address = iota.Address(hotel_address), message = None, tag = iota.Tag(b'HOTEL9IOTA'), value = amount) # 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, security_level=1) # Display transaction sent confirmation message print("\nTransaction sent...You may proceed") # Loop executes every 10 seconds to checks if transaction is confirmed # while transaction_confirmed == False: # print("\nChecking balance to see if transaction is confirmed...") # currentbalance = checkbalance(hotel_address) # if currentbalance > lastbalance: # print("\nTransaction is confirmed") # blinkLED(blinks)
import iota from pprint import pprint from pow import ccurl_interface # Generate seed myseed = iota.crypto.types.Seed.random() # Generate two addresses addres_generator = iota.crypto.addresses.AddressGenerator(myseed) addys = addres_generator.get_addresses(1, count=2) # Preparing transactions pt = iota.ProposedTransaction(address=iota.Address(addys[0]), tag=iota.Tag(b'LOCALATTACHINTERFACE99999'), value=0) pt2 = iota.ProposedTransaction(address=iota.Address(addys[1]), tag=iota.Tag(b'LOCALATTACHINTERFACE99999'), value=0) # Preparing bundle that consists of both transactions prepared in the previous example pb = iota.ProposedBundle(transactions=[pt2, pt]) # Generate bundle hash pb.finalize() # Declare an api instance api = iota.Iota("https://nodes.thetangle.org:443") # Get tips to be approved by your bundle gta = api.get_transactions_to_approve(
pass ## Converts read image to characteristics and stores it in charbuffer 1 f.convertImage(0x01) ## Downloads the characteristics of template loaded in charbuffer 1 mychar = f.downloadCharacteristics(0x01) # Convert list of characteristics to string mystring = json.dumps(mychar) # Define new IOTA transaction pt = iota.ProposedTransaction( address=iota.Address(addr), message=iota.TryteString.from_unicode(mystring), tag=iota.Tag(b'HOTELIOTA'), value=0) # Print waiting message print("\nSending transaction...Please wait...") # Send transaction to the tangle FinalBundle = api.send_transfer(depth=3, transfers=[pt], min_weight_magnitude=14)['bundle'] # Print confirmation message print("\nTransaction completed.") print("\nAddress used for the transaction was:") print(addr)
import iota # Original IOTA python library import iota_fees # Just import this module and you are ready to set fees on transactions # # This sample shows how the iota-fees module allows for setting transaction fees, # in order to make IOTA a fully accepted crypto currency and to increase acceptance # of your business towards customers. # # Connect to IOTA node api = iota.Iota('http://localhost:14265/') # Create sample transfer transfer = [ iota.ProposedTransaction( address=iota.Address( b'QPLGOG9PMIMUAW9UDMUNZQHPXZPXDNGLBEIHILXHWHIOFHLIHPDDERXAJQKUQDEORMHSUWVZQE9JYSHIWADIIPAOJD' ), value=100, tag=iota.Tag(b'EXAMPLE'), message=iota.TryteString.from_string('Hello!'), ), ] # Send transfer api.send_transfer( depth=100, transfers=transfer, fees=1000000 # The fee to send along with the transfer can be set )
print("You voted NO") break print("\nThank you, now hold your ID card near the reader") id, text = reader.read() data = { 'tagID': str(id), 'tagText': str(text), 'project': project, 'casted_vote': casted_vote } pt = iota.ProposedTransaction(address=iota.Address(IOTAAddr), message=iota.TryteString.from_unicode( json.dumps(data)), tag=iota.Tag(b'VOTERFIDMIAMI'), 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 recorded") break finally: GPIO.cleanup()
from iota import Iota from iota import TryteString headers = {'X-IOTA-API-Version': '1'} getTips = {"command": "getTips"} def call_iota_api(f): r = requests.post("http://140.116.247.117:14265", data=json.dumps(f), headers=headers) return r.text SEED = 'BXOM9LUNLPSEXBRJV9UUNLHSUHABEOGHQOGNBNBUEYSGOFZOEPYKEYRSFTXBOEJLUODUQXXGQ9NWQBSGH' api = Iota('http://140.116.247.117:14265', b'BXOM9LUNLPSEXBRJV9UUNLHSUHABEOGHQOGNBNBUEYSGOFZOEPYKEYRSFTXBOEJLUODUQXXGQ9NWQBSGH') gna_result = api.get_new_addresses(count=2) bundle = ProposedBundle() tag = iota.Tag('TESTINGPYTHON') pt = iota.ProposedTransaction( address=iota.Address('9TPHVCFLAZTZSDUWFBLCJOZICJKKPVDMAASWJZNFFBKRDDTEOUJHR9JVGTJNI9IYNVISZVXARWJFKUZWC'), value=0, tag=tag, message=iota.TryteString('HELLO') ) bundle.add_transaction(pt) addy = gna_result["addresses"][0] addy.balance = 0 addy.key_index = 0 bundle.add_inputs([ addy ])
def send_transfer(tag, message, address, values, dict_tips): ## Set output transaction print("Start to sransfer ... ") propose_bundle = iota.ProposedBundle() print("Setting output transaction ...") txn_output = iota.ProposedTransaction(address=iota.Address(address), value=values, tag=iota.Tag(tag), message=iota.TryteString(message)) propose_bundle.add_transaction(txn_output) # Get input address if int(values) > 0: print "DEBUG values = " + 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 = 1 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(gen_a_address()['addresses'][0]) propose_bundle.send_unspent_inputs_to(unspent) # This will get the bundle hash print("Bundle finalize ...") propose_bundle.finalize() ## 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['branchTransaction'] branch_hash = dict_tips['trunkTransaction'] # Do PoW (attach to tangle) for tx_tryte in trytes: # TODO: Timestamp # timestamp = None # timestamp_lower_bound = None # timestamp_upper_bound = None # 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 = '' with tempfile.TemporaryFile() as tempf: proc = subprocess.Popen( ['python', 'tx_search_nonce.py', str(tx_tryte), str(14)], stdout=tempf) proc.wait() tempf.seek(0) nonce = tempf.read().rstrip() tx_tryte = insert_to_trytes(2646, 2673, str(nonce), tx_tryte) print "Prepare to broadcast ..." try: api.broadcast_transactions([tx_tryte[0:2673]]) except Exception as e: print "Error: " + str(e.context) return propose_bundle.hash
print("") address = 'Random Adress Here' api =\ Iota( # Send PoW requests to local node. # All other requests go to light wallet node. RoutingWrapper('https://nodes.thetangle.org:443') .add_route('attachToTangle', 'https://nodes.thetangle.org:443'), # Seed used for cryptographic functions. seed = b'Random Seed Here' ) pt = iota.ProposedTransaction(address = iota.Address(address), message = iota.TryteString.from_unicode('Your Text Here'), tag = iota.Tag(b'Your Tag Here'), 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])
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 MakePreparingTransaction(self, TargetAddress, StringMessage, tag='KEVIN999IS999HANDSOME', Ivalue=0): TargetAddress = str.encode(TargetAddress) pt = iota.ProposedTransaction(address = iota.Address(TargetAddress),message = iota.TryteString.from_unicode(StringMessage),tag = iota.Tag(str.encode(tag)),value=Ivalue) return pt