def add_txn_to_queue(request_data): request_command = json.loads(request_data) node_url = request_command['node_url'] address = request_command['address'] tag = request_command['tag'] messages = request_command['messages'] values = request_command['values'] bundle_hash = "" prepared_transferes = [] api = Iota(node_url, SEED) txn = \ ProposedTransaction( address = Address(address), message = TryteString.from_string(messages), tag = Tag(tag), value = int(values), ) prepared_transferes.append(txn) try: bundle_hash = api.send_transfer( depth = 7, transfers = prepared_transferes, min_weight_magnitude = 14 ) except Exception as e: print(e) return 0 print(bundle_hash['bundle'].hash) append_log(bundle_hash['bundle'].hash, LOG_HISTORY_TXN) return 0
def main(): api = Iota("http://localhost:14265") # For more information, see :py:meth:`Iota.send_transfer`. ti = time.time() a = api.send_transfer( depth=3, transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address( "RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999" ), value=0, # Optional tag to attach to the transfer. tag=Tag(b'KITTEHS'), # Optional message to include with the transfer. message=TryteString.from_unicode('thx fur cheezburgers'), ), ], min_weight_magnitude=1) k = 0 for k in a["bundle"]: print(k)
def write_data_to_tangle(data): # Iota instance api = Iota(NODE_URL, SEED) # Txn description txn = ProposedTransaction( address = Address(receiver_address), message = TryteString.from_string(json.dumps(data)), tag = Tag(txn_tag), value = value, ) # Send transaction prepared_transferes = [] bundle = "" prepared_transferes.append(txn) try: bundle = api.send_transfer( depth = DEPTH, transfers = prepared_transferes, min_weight_magnitude = MIN_WEIGHT_MAGNITUDE ) except Exception as e: print(e) return e print(bundle['bundle'].hash) return {"status":200, "bundle":bundle['bundle'].hash}
def sendTX(msg): ''' PURPOSE: send transaction to the Tangle INPUT: address from a seed different than the one in this script OUTPUT: TX to devnet ''' seed = 'SEED99999999999999999999999999999999999999999999999999999999999999999999999999999' address = 'ADDRESS9FROM9DIFFERENT9SEED999999999999999999999999999999999999999999999999999999' api = Iota('https://nodes.devnet.iota.org:443', seed) tx = ProposedTransaction(address=Address(address), message=TryteString.from_unicode(msg), tag=Tag('YOURTAG'), value=0) try: tx = api.prepare_transfer(transfers=[tx]) except Exception as e: print("Check prepare_transfer ", e) raise try: result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9) except: print("Check send_trytes")
def from_tryte_string(cls, trytes): # type: (TrytesCompatible) -> Transaction """ Creates a Transaction object from a sequence of trytes. """ tryte_string = TransactionTrytes(trytes) hash_ = [0] * HASH_LENGTH # type: MutableSequence[int] sponge = Curl() sponge.absorb(tryte_string.as_trits()) sponge.squeeze(hash_) return cls( hash_ = TransactionHash.from_trits(hash_), signature_message_fragment = Fragment(tryte_string[0:2187]), address = Address(tryte_string[2187:2268]), value = int_from_trits(tryte_string[2268:2295].as_trits()), tag = Tag(tryte_string[2295:2322]), timestamp = int_from_trits(tryte_string[2322:2331].as_trits()), current_index = int_from_trits(tryte_string[2331:2340].as_trits()), last_index = int_from_trits(tryte_string[2340:2349].as_trits()), bundle_hash = BundleHash(tryte_string[2349:2430]), trunk_transaction_hash = TransactionHash(tryte_string[2430:2511]), branch_transaction_hash = TransactionHash(tryte_string[2511:2592]), nonce = Hash(tryte_string[2592:2673]), )
def send_message(address, depth, message, tag, uri, value): # Ensure seed is not displayed in cleartext. seed = 'NO9SEED9REQUIRED999999999999999999999999999' # Create the API instance. api = Iota(uri, seed) print 'Starting transfer please wait...\n' # For more information, see :py:meth:`Iota.send_transfer`. bundle = api.send_transfer( depth=depth, # One or more :py:class:`ProposedTransaction` objects to add to the # bundle. transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address(address), # Amount of IOTA to transfer. # By default this is a zero value transfer. value=value, # Optional tag to attach to the transfer. tag=Tag(tag), # Optional message to include with the transfer. message=TryteString.from_string(message), ), ], ) print 'Transfer complete. TX hash: ', bundle['bundle'].transactions[0].hash
def issue_milestone(address, api, index, *reference_transaction): txn1 = ProposedTransaction(address=Address(address), value=0) txn2 = ProposedTransaction(address=Address(address), value=0) bundle = ProposedBundle() bundle.add_transaction(txn1) bundle.add_transaction(txn2) bundle[0]._legacy_tag = Tag(converter.int_to_trytestring(index, 9)) bundle_logic.finalize(bundle) tips = api.get_transactions_to_approve(depth=3) trunk = tips['trunkTransaction'] if reference_transaction: branch = reference_transaction[0] else: branch = tips['branchTransaction'] bundle_trytes = bundle.as_tryte_strings() milestone = api.attach_to_tangle(trunk, branch, bundle_trytes, 9) api.broadcast_and_store(milestone['trytes']) return milestone
def main(address, depth, message, tag, uri, value): # Ensure seed is not displayed in cleartext. seed = get_seed() # Create the API instance. api = Iota(uri, seed) if not seed: print('A random seed has been generated. Press return to see it.') output_seed(api.seed) print('Starting transfer.') # For more information, see :py:meth:`Iota.send_transfer`. api.send_transfer( depth=depth, # One or more :py:class:`ProposedTransaction` objects to add to the # bundle. transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address(address), # Amount of IOTA to transfer. # By default this is a zero value transfer. value=value, # Optional tag to attach to the transfer. tag=Tag(tag), # Optional message to include with the transfer. message=TryteString.from_string(message), ), ], ) print('Transfer complete.')
def main(): # Ensure seed is not displayed in cleartext. #seed = get_seed() # Create the API instance. while(1): api = Iota("http://localhost:14265") #if not seed: # print('A random seed has been generated. Press return to see it.') # output_seed(api.seed) #print('Starting transfer.') # For more information, see :py:meth:`Iota.send_transfer`. api.send_transfer( depth=3, # One or more :py:class:`ProposedTransaction` objects to add to the # bundle. transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address("RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999"), # Amount of IOTA to transfer. # By default this is a zero value transfer. value=0, # Optional tag to attach to the transfer. tag=Tag(b'KITTEHS'), # Optional message to include with the transfer. message=TryteString.from_unicode('thx fur cheezburgers'), ), ], min_weight_magnitude=1 )
def tangle_and_verify(message_id, userdata, message_data): if not userdata or not message_id: return recv_addr = userdata.get('address_to_send', '').encode() iota_obj = userdata.get('iota_obj', None) depth_value = userdata.get('depth', 3) verify_server = userdata.get('verify_server', None) try: txn_1 = ProposedTransaction(address=Address(recv_addr,), value=0, tag=Tag(TryteString.from_unicode(message_id)), message=TryteString.from_unicode(message_data)) _transactions = [txn_1, ] iota_obj.send_transfer(depth=depth_value, transfers=_transactions) print("\n .. Saved Message with ID %s succesfully to the Tangle \n" %(message_id,)) except Exception: print("\n .. Could not save to Tangle -- Message ID : {0}, " \ "Data : {1} \n".format(message_id, message_data)) return try: msg_to_send = "{id}/".format(id=message_id) verify_server.sendall(msg_to_send.encode('utf-8')) except Exception: print("Something went wrong! Couldn't send data for Msg ID = %s to our " \ "verify server" %(message_id,))
def sendToAddress(self, message, address, depth, tag, value): api = Iota("http://iota.av.it.pt:14265") # Sample Data # address = b'RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999RQXIUOZMD' # depth = 3 # tag = b'IOTAPASS' # value = 0 # For more information, see :py:meth:`Iota.send_transfer`. try: api.send_transfer( depth=depth, # One or more :py:class:`ProposedTransaction` objects to add to the # bundle. transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address(address), # Amount of IOTA to transfer. # By default this is a zero value transfer. value=value, # Optional tag to attach to the transfer. tag=Tag(tag), # Optional message to include with the transfer. message=TryteString.from_string(message), ), ], ) return True except: return False
def test_single_transaction(self): """ Getting a bundle that contains a single transaction. """ transaction = \ Transaction( current_index=0, last_index=0, tag=Tag(b''), timestamp=1484960990, value=0, attachment_timestamp=1484960990, attachment_timestamp_lower_bound=12, attachment_timestamp_upper_bound=0, # These values are not relevant for 0-value transactions. nonce=Nonce(b''), signature_message_fragment=Fragment(b''), # This value is computed automatically, so it has to be real. hash_=TransactionHash( b'XPJIYZWPF9LBCYZPNBFARDRCSUGJGF9TWZT9K9PX' b'VYDFPZOZBGXUCKLTJEUCFBEKQQ9VCSQVQDMMJQAY9', ), address=Address( b'TESTVALUE9DONTUSEINPRODUCTION99999OCSGVF' b'IBQA99KGTCPCZ9NHR9VGLGADDDIEGGPCGBDEDDTBC', ), bundle_hash=BundleHash( b'TESTVALUE9DONTUSEINPRODUCTION99999DIOAZD' b'M9AIUHXGVGBC9EMGI9SBVBAIXCBFJ9EELCPDRAD9U', ), branch_transaction_hash=TransactionHash( b'TESTVALUE9DONTUSEINPRODUCTION99999BBCEDI' b'ZHUDWBYDJEXHHAKDOCKEKDFIMB9AMCLFW9NBDEOFV', ), trunk_transaction_hash=TransactionHash( b'TESTVALUE9DONTUSEINPRODUCTION999999ARAYA' b'MHCB9DCFEIWEWDLBCDN9LCCBQBKGDDAECFIAAGDAS', ), ) self.adapter.seed_response('getTrytes', { 'trytes': [transaction.as_tryte_string()], }) response = self.command(transaction=transaction.hash) bundle = response['bundles'][0] # type: Bundle self.assertEqual(len(bundle), 1) self.maxDiff = None self.assertDictEqual( bundle[0].as_json_compatible(), transaction.as_json_compatible(), )
def __init__(self, address, value, tag=None, message=None, timestamp=None): # type: (Address, int, Optional[Tag], Optional[TryteString], Optional[int]) -> None if not timestamp: timestamp = get_current_timestamp() super(ProposedTransaction, self).__init__( address = address, tag = Tag(b'') if tag is None else tag, timestamp = timestamp, value = value, # These values will be populated when the bundle is finalized. bundle_hash = None, current_index = None, hash_ = None, last_index = None, signature_message_fragment = None, # These values start out empty; they will be populated when the # node does PoW. branch_transaction_hash = TransactionHash(b''), nonce = Hash(b''), trunk_transaction_hash = TransactionHash(b''), ) self.message = TryteString(b'') if message is None else message
def transfer(address, tag, message, value): recipient_address = address sender_message = message sender_tag = tag prepared_transferes = [] api = Iota(URL_NODE, SEED) sender_tag = bytes(sender_tag) transfer_value = int(value) txn = \ ProposedTransaction( address = Address( recipient_address ), message = TryteString.from_string(sender_message), tag = Tag(sender_tag), value = transfer_value, ) prepared_transferes.append(txn) dict_raw_trytes_tx = api.prepare_transfer(prepared_transferes) len_tx = len(dict_raw_trytes_tx['trytes']) for index in range(len_tx): print str(dict_raw_trytes_tx['trytes'][index]) return True
def test_init_error_too_long(self): """ Attempting to create a tag longer than 27 trytes. """ with self.assertRaises(ValueError): # 28 chars = no va. Tag(b'COLOREDCOINS9999999999999999')
def main(): # Ensure seed is not displayed in cleartext. seed = 'SEED99999999999999999999999999999999999999999999999999999999999999999999999999999' # Create the API instance. api = Iota("http://localhost:14265", seed) t1 = time.time() print('Starting transfer.') # For more information, see :py:meth:`Iota.send_transfer`. api.send_transfer( depth=3, # One or more :py:class:`ProposedTransaction` objects to add to the # bundle. transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address( 'RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999' ), # Amount of IOTA to transfer. # By default this is a zero value transfer. value=42, # Optional tag to attach to the transfer. tag=Tag(b'EXAMPLE'), # Optional message to include with the transfer. message=TryteString.from_string('Hello World!'), ), ], min_weight_magnitude=9, security_level=2) print('Transfer complete.', time.time() - t1)
def test_init_automatic_pad(self): """ Tags are automatically padded to 27 trytes. """ tag = Tag(b'COLOREDCOINS') self.assertEqual(binary_type(tag), b'COLOREDCOINS999999999999999')
def test_pass_compatible_types(self): """ The request contains values that can be converted to the expected types. """ filter_ = self._filter({ 'bundles': [ self.trytes1.encode('ascii'), BundleHash(self.trytes2), ], 'addresses': [ self.trytes1.encode('ascii'), Address(self.trytes2), ], 'tags': [ self.trytes1.encode('ascii'), Tag(self.trytes3), ], 'approvees': [ self.trytes1.encode('ascii'), TransactionHash(self.trytes3), ], }) self.assertFilterPasses(filter_) self.assertDictEqual( filter_.cleaned_data, { # Raw trytes are extracted to match the IRI's JSON protocol. 'bundles': [ text_type(BundleHash(self.trytes1)), text_type(BundleHash(self.trytes2)), ], 'addresses': [ text_type(Address(self.trytes1)), text_type(Address(self.trytes2)), ], 'tags': [ text_type(Tag(self.trytes1)), text_type(Tag(self.trytes3)), ], 'approvees': [ text_type(TransactionHash(self.trytes1)), text_type(TransactionHash(self.trytes3)), ], }, )
def test_anchor_building_blocks(self): message = 'Some data proof to lock on the chain' self.mock_adapter.seed_response('send_transfer', response={'message': 'test'}) address = Address('JUST9A9MOCK9ADDRESS99999999') tag = Tag('JUST9A9MOCK9TAG99999999') test_client.anchor_building_block(self.api, address, tag, message)
def prepare_transaction_arguments(arg_list): for key in arg_list: if key == 'address': arg_list[key] = Address(arg_list[key]) elif key == 'tag': arg_list[key] = Tag(arg_list[key]) elif key == 'message': arg_list[key] = TryteString.from_unicode(arg_list[key])
def tx_to_tangle(api, address_in, data_in, tag_in='', value_in=0): result = api.send_transfer(transfers=[ ProposedTransaction(address=address_in, message=TryteString.from_unicode(data_in), tag=Tag(tag_in.encode()), value=value_in) ]) return result
def test_pass_all_parameters(self): """ The request contains valid values for all parameters. """ # Raw trytes are extracted to match the IRI's JSON protocol. request = { 'bundles': [ text_type( TransactionHash(self.trytes1) # # self.trytes1 = 'RBTC9D9DCDQAEASBYBCCKBFA' ), text_type(TransactionHash(self.trytes2)), ], 'addresses': [ text_type(Address(self.trytes1)), text_type(Address(self.trytes2)), ], 'tags': [ text_type(Tag(self.trytes1)), text_type( Tag(self.trytes3) # # self.trytes3 = '999999999999999999999999999' ), ], 'approvees': [ text_type(TransactionHash(self.trytes1)), text_type(TransactionHash(self.trytes3)), ], } print_var_type_n_val( var001=request, pointer="#XXXXCVBVCZZZzzzer12345") #XXXXCVBVCZZZzzzer12345 # Value: # # {'bundles': ['RBTC9D9DCDQAEASBYBCCKBFA999999999999999999999999999999999999999999999999999999999', 'CCPCBDVC9DTCEAKDXC9D9DEARCWCPCBDVCTCEAHDWCTCEAKDCDFD9DSCSA99999999999999999999999'], 'addresses': ['RBTC9D9DCDQAEASBYBCCKBFA999999999999999999999999999999999999999999999999999999999', 'CCPCBDVC9DTCEAKDXC9D9DEARCWCPCBDVCTCEAHDWCTCEAKDCDFD9DSCSA99999999999999999999999'], 'tags': ['RBTC9D9DCDQAEASBYBCCKBFA999', '999999999999999999999999999'], 'approvees': ['RBTC9D9DCDQAEASBYBCCKBFA999999999999999999999999999999999999999999999999999999999', '999999999999999999999999999999999999999999999999999999999999999999999999999999999']} # Type: <class 'dict'> filter_ = self._filter(request) #here001 print_var_type_n_val(var001=filter_, pointer="#WXCVRDFGTFGHV") #WXCVRDFGTFGHV # Value: # # FindTransactionsRequestFilter(FilterChain(Type(Mapping, allow_subclass=True) | FilterMapper(addresses=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | AddressNoChecksum() | Unicode(encoding='ascii')))), approvees=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | Trytes() | Unicode(encoding='ascii')))), bundles=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | Trytes() | Unicode(encoding='ascii')))), tags=FilterChain(Array(Sequence, allow_subclass=True) | FilterRepeater(FilterChain(Required(allow_none=False) | Trytes() | Unicode(encoding='ascii'))))))) # Type: <class 'filters.handlers.FilterRunner'> self.assertFilterPasses(filter_) self.assertDictEqual(filter_.cleaned_data, request)
def send(trak_id, lat, lon): dict_message = {"trak_id": trak_id, "lat": lat, "lon": lon} message = TryteString.from_unicode(str(dict_message)) tx = ProposedTransaction(address=Address(address), message=message, tag=Tag(b'KUBERFLETE9999999'), value=0) result = api.send_transfer(transfers=[tx]) return result
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 send_transaction(value, address, private_key, api, UID): print("Envoie des reponse ...") message = cast_message(value, private_key) tx = ProposedTransaction(address=Address(address), value=10, tag=Tag(UID), message=message) result = api.send_transfer(transfers=[tx])
def test_finalize_insecure_bundle(self): """ When finalizing, the bundle detects an insecure bundle hash. References: - https://github.com/iotaledger/iota.lib.py/issues/84 """ # noinspection SpellCheckingInspection bundle =\ ProposedBundle([ ProposedTransaction( address =\ Address( '9XV9RJGFJJZWITDPKSQXRTHCKJAIZZY9BYLBEQUX' 'UNCLITRQDR9CCD99AANMXYEKD9GLJGVB9HIAGRIBQ', ), tag = Tag('PPDIDNQDJZGUQKOWJ9JZRCKOVGP'), timestamp = 1509136296, value = 0, ), ]) bundle.finalize() # The resulting bundle hash is insecure (contains a [1, 1, 1]), so # the legacy tag is manipulated until a secure hash is generated. # noinspection SpellCheckingInspection self.assertEqual(bundle[0].legacy_tag, Tag('ZTDIDNQDJZGUQKOWJ9JZRCKOVGP')) # The proper tag is left alone, however. # noinspection SpellCheckingInspection self.assertEqual(bundle[0].tag, Tag('PPDIDNQDJZGUQKOWJ9JZRCKOVGP')) # The bundle hash takes the modified legacy tag into account. # noinspection SpellCheckingInspection self.assertEqual( bundle.hash, BundleHash( 'NYSJSEGCWESDAFLIFCNJFWGZ9PCYDOT9VCSALKBD' '9UUNKBJAJCB9KVMTHZDPRDDXC9UFJQBJBQFUPJKFC', ) )
def send_request(value, address, private_key, api, UID): message = cast_message(value, private_key) tx = ProposedTransaction(address=Address(address), value=10, tag=Tag(UID), message=message) result = api.send_transfer(transfers=[tx]) print('Bundle: ') print(result['bundle'].tail_transaction.hash)
def send_funds(self): tx = ProposedTransaction( address=Address(self.owner), message=TryteString.from_unicode('IOTAPay Device V1'), tag=Tag('IOTAPAYTRANSACTION'), value=self.summary ) tx = self.api.prepare_transfer(transfers=[tx], inputs=self.value_addresses, change_address=self.owner) result = self.api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=14) print('Transaction with:', self.summary, 'iota sent to the tangle!')
def pay(amount, reciever, message): proposedTrx = ProposedTransaction(address=Address(reciever), value=0, tag=Tag("AACHELORTEST"), message=TryteString.from_string(message)) proposedBundle = ProposedBundle([proposedTrx]) preparedBundle = api.prepare_transfer(proposedBundle) publishedBundle = api.send_transfer(depth=3, transfers=proposedBundle) return publishedBundle
def on_message(client, userdata, msg): """ receiving data""" try: sensors = msg.payload sensors = json.loads(sensors.decode('utf-8')) except e: print("Check the message: ",e) logfile = open("enviro.csv", "a") print(sensors["timestamp"], ",",\ sensors["device_name"], ",",\ sensors["device_owner"], ",",\ sensors["city"], ",",\ sensors["lng"], ",",\ sensors["lat"], ",",\ sensors["lux"], ",",\ sensors["rgb"], ",",\ sensors["accel"], ",",\ sensors["heading"], ",",\ sensors["temperature"], ",",\ sensors["pressure"], file=logfile) logfile.close() api = Iota('https://nodes.devnet.iota.org:443') address = 'H9TJVEEAOAI9ADCFSRIKOYHNLVDIRDIIREXQUJNBIWBSINJIJXXDTPTRDOZRRSCUOLZAXVZNRHDCWVSVD' tx = ProposedTransaction( address=Address(address), #message=TryteString.from_unicode(sensors), message=TryteString.from_unicode(json.dumps(sensors)), tag=Tag('ENVIROPHATIII'), value=0 ) print(tx) try: tx = api.prepare_transfer(transfers=[tx]) except: print("PREPARE EXCEPTION",tx) try: result = api.send_trytes(tx['trytes'], depth=3, min_weight_magnitude=9) except: print("EXCEPTION", result) print("\nTimestamp: ", sensors["timestamp"]) print("Device: ", sensors["device_name"]) print("Device owner email: ", sensors["device_owner"]) print("Device location: ", sensors["city"], " at longitude: ", sensors["lng"], " and latitude: ", sensors["lat"]) print("Light: ", sensors["lux"]) print("RGB: ", sensors["rgb"]) print("Accelerometer: ", sensors["accel"]) print("Heading: ", sensors["heading"]) print("Temperature: ", sensors["temperature"]) print("Pressure: ", sensors["pressure"]) return sensors