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 storeJson(file): receiver_address = generateAddress()[0] sender_address = generateAddress()[1] print('receiver address = ', receiver_address) print('sender address = ', sender_address) sender_account = api.get_account_data(start=0) print("sender balance = " + str(sender_account["balance"])) # We store the json file into message part of the transaction message = JsontoTrytes(file) proposedTransaction = ProposedTransaction( address=Address(receiver_address), value=0, message=message) # Execution of the transaction transfer = api.send_transfer( depth=depth, transfers=[proposedTransaction], inputs=[Address(sender_address, key_index=0, security_level=2)]) transactionHash = [] for transaction in transfer["bundle"]: transactionHash.append(transaction.hash) print(transaction.address, transaction.hash) print(api.get_latest_inclusion(transactionHash))
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 test_fail_transfers_contents_invalid(self): """ ``transfers`` is an array, but it contains invalid values. """ self.assertFilterErrors( { 'changeAddress': Address(self.trytes_1), 'multisigInput': MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ), 'transfers': [ None, 42, # This one's valid, actually; just making sure that the # filter doesn't cheat. ProposedTransaction( address=Address(self.trytes_3), value=42, ), Address(self.trytes_3), ], }, { 'transfers.0': [f.Required.CODE_EMPTY], 'transfers.1': [f.Type.CODE_WRONG_TYPE], 'transfers.3': [f.Type.CODE_WRONG_TYPE], }, )
def test_pass_changeAddress_multisig_address(self): """ ``changeAddress`` is allowed to be a MultisigAddress. """ change_addy = \ MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_1 ) filter_ = self._filter({ 'changeAddress': change_addy, 'multisigInput': MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ), 'transfers': [ ProposedTransaction( address=Address(self.trytes_3), value=42, ), ], }) self.assertFilterPasses(filter_) self.assertIs(filter_.cleaned_data['changeAddress'], change_addy)
def test_add_inputs_security_level(self): """ Each input's security level determines the number of transactions we will need in order to store the entire signature. """ # noinspection SpellCheckingInspection self.bundle.add_transaction( ProposedTransaction( address=Address( b'TESTVALUE9DONTUSEINPRODUCTION99999XE9IVG' b'EFNDOCQCMERGUATCIEGGOHPHGFIAQEZGNHQ9W99CH', ), value=84, ), ) self.bundle.add_inputs([ self.input_4_bal_eq_42_sl_2, self.input_5_bal_eq_42_sl_3, ]) self.bundle.finalize() # Each input's security level determines how many transactions will # be needed to hold all of its signature fragments: # 1 spend + 2 fragments for input 0 + 3 fragments for input 1 self.assertEqual(len(self.bundle), 6)
def payout(self, address, amount): inputs = [] inpq = self.db.query("SELECT * FROM addresses WHERE spent=FALSE AND \ balance > 0 ORDER BY idx ASC") needed = amount for inp in inpq: needed -= inp.balance inputs.append(Address(inp.address, key_index=inp.idx, security_level=2, balance=inp.balance)) if needed <= 0: break # do we have change? if needed < 0 and not amount == 0: chaddr = self.get_change_address() elif needed == 0: chaddr = None else: # not enough balance! return None return self.api.prepare_transfer([ ProposedTransaction(Address(address), amount) ], inputs=inputs, change_address=chaddr)
def test_add_signature_or_message(self): """ Add a fragment to a transaction. """ # Add a transaction self.bundle.add_transaction( ProposedTransaction( address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF' b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'), message=TryteString.from_unicode('This should be overwritten'), value=0, )) custom_msg = \ 'The early bird gets the worm, but the custom-msg gets into the bundle.' custom_fragment = Fragment.from_unicode(custom_msg) # Before finalization, the method adds to message field... self.bundle.add_signature_or_message([custom_fragment]) self.assertEqual(self.bundle._transactions[0].message, custom_fragment) # ... because upon finalization, this is translated into # signature_message_fragment field. self.bundle.finalize() self.assertEqual( self.bundle._transactions[0].signature_message_fragment, custom_fragment) # Do we have the right text inside? self.assertEqual(self.bundle.get_messages()[0], custom_msg)
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 send(self, address: str, value: int) -> None: print(f'Sending {value} iota to {address}...') response = self._iota_api.send_transfer( depth=DEPTH, transfers=[ProposedTransaction(Address(address), value=value)]) bundle = response['bundle'] print(f'Iota sent! Bundle hash: {bundle.hash}')
def create_and_attach_transaction(api, value_transaction, arg_list, *reference): """ Create a transaction and attach it to the tangle. :param api: The api target you would like to make the call to :param value_transaction: A bool to determine if this transaction is a value or zero value transaction :param arg_list: The argument list (dictionary) for the transaction :return sent: The return value for the attachToTangle call (contains the attached transaction trytes) """ transaction = ProposedTransaction(**arg_list) if value_transaction: inputs = api.get_inputs(start=0, stop=10, threshold=0) prepared_transaction = api.prepare_transfer( transfers=[transaction], inputs=[inputs['inputs'][0]], change_address=Address(static.TEST_EMPTY_ADDRESS)) else: prepared_transaction = api.prepare_transfer(transfers=[transaction]) gtta = api.get_transactions_to_approve(depth=3) trunk = str(gtta['trunkTransaction']) if reference: branch = reference[0] else: branch = str(gtta['branchTransaction']) sent = api.attach_to_tangle(trunk, branch, prepared_transaction['trytes'], 9) return sent
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 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 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 test_add_signature_or_message_too_long_fragments(self): """ Trying to add too many fragments to a bundle, when there aren't enough transactions to hold them. """ # Add 3 transactions to the bundle. for i in ['A', 'B', 'C']: self.bundle.add_transaction(ProposedTransaction( address = Address( 'TESTVALUE' + i + 'DONTUSEINPRODUCTION99999QARFLF' 'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX' ), message= TryteString.from_unicode('This should be overwritten'), value = 0, )) fragment1 = Fragment.from_unicode('This is the first fragment.') # 4 fragments, 3 txs in bundle fragments = [fragment1] * 4 with self.assertRaises(ValueError): self.bundle.add_signature_or_message(fragments) # Length is okay, but overflow because of offset fragments = [fragment1] * 3 with self.assertRaises(ValueError): self.bundle.add_signature_or_message(fragments,start_index=1)
def test_add_inputs_error_already_finalized(self): """ Attempting to add inputs to a bundle that is already finalized. """ # Add 1 transaction so that we can finalize the bundle. # noinspection SpellCheckingInspection self.bundle.add_transaction( ProposedTransaction( address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999XE9IVG' b'EFNDOCQCMERGUATCIEGGOHPHGFIAQEZGNHQ9W99CH', ), value = 0, ), ) self.bundle.finalize() with self.assertRaises(RuntimeError): # Even though no inputs are provided, it's still an error; you # shouldn't even be calling ``add_inputs`` once the bundle is # finalized! self.bundle.add_inputs([])
def test_add_signature_or_message_invalid_start_index(self): """ Attempting to add fragments to a bundle, but `start_index` is invalid. """ # Add 3 transactions to the bundle. for i in ['A', 'B', 'C']: self.bundle.add_transaction(ProposedTransaction( address = Address( 'TESTVALUE' + i + 'DONTUSEINPRODUCTION99999QARFLF' 'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX' ), message = TryteString.from_unicode('This should be overwritten'), value = 0, )) fragment1 = Fragment.from_unicode('This is the first fragment.') with self.assertRaises(ValueError): self.bundle.add_signature_or_message([fragment1], start_index=-1) with self.assertRaises(ValueError): self.bundle.add_signature_or_message([fragment1], start_index=3) with self.assertRaises(TypeError): self.bundle.add_signature_or_message([fragment1], 'not an int')
def test_sign_input_at_error_index_not_input(self): """ The specified index references a transaction that is not an input. """ # Add a transaction so that we can finalize the bundle. # noinspection SpellCheckingInspection self.bundle.add_transaction(ProposedTransaction( address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF' b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX' ), value = 42, )) self.bundle.add_inputs([self.input_0_bal_eq_42]) self.bundle.finalize() private_key =\ KeyGenerator(self.seed).get_key_for(self.input_0_bal_eq_42) with self.assertRaises(ValueError): # You can't sign the spend transaction, silly! self.bundle.sign_input_at(0, private_key)
def test_sign_input_at_error_already_signed(self): """ Attempting to sign an input that is already signed. """ # Add a transaction so that we can finalize the bundle. # noinspection SpellCheckingInspection self.bundle.add_transaction( ProposedTransaction( address=Address(b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF' b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX'), value=42, )) self.bundle.add_inputs([self.input_0_bal_eq_42]) self.bundle.finalize() # The existing signature fragment doesn't have to be valid; it just # has to be not empty. self.bundle[1].signature_message_fragment = Fragment(b'A') private_key =\ KeyGenerator(self.seed).get_key_for(self.input_0_bal_eq_42) with self.assertRaises(ValueError): self.bundle.sign_input_at(1, private_key)
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_fail_transfers_wrong_type(self): """ ``transfers`` is not an array. """ self.assertFilterErrors( { 'changeAddress': Address(self.trytes_1), 'multisigInput': MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ), # ``transfers`` must be an array, even if there's only one # transaction. 'transfers': ProposedTransaction( address=Address(self.trytes_3), value=42, ), }, { 'transfers': [f.Array.CODE_WRONG_TYPE], }, )
def test_fail_transfers_contents_invalid(self): """ ``transfers`` is a non-empty array, but it contains invalid values. """ self.assertFilterErrors( { 'transfers': [ None, # This value is valid; just adding it to make sure the filter # doesn't cheat! ProposedTransaction(address=Address(self.trytes2), value=42), { 'address': Address(self.trytes2), 'value': 42 }, ], 'depth': 100, 'minWeightMagnitude': 18, 'seed': Seed(self.trytes1), }, { 'transfers.0': [f.Required.CODE_EMPTY], 'transfers.2': [f.Type.CODE_WRONG_TYPE], }, )
def test_fail_multisigInput_multiple(self): """ ``multisigInput`` is an array. This is not valid; a bundle may only contain a single multisig input. """ self.assertFilterErrors( { 'changeAddress': Address(self.trytes_1), 'multisigInput': [ MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ), MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ) ], 'transfers': [ ProposedTransaction( address=Address(self.trytes_3), value=42, ), ], }, { 'multisigInput': [f.Type.CODE_WRONG_TYPE], }, )
def send_message(address, depth, message, tag, uri, value): # Ensure seed is not displayed in cleartext. seed = iota_seed # 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), ), ], ) tx_hash = bundle['bundle'].transactions[0].hash return tx_hash
def test_error_insufficient_inputs(self): """ The multisig input does not contain sufficient IOTAs to cover the spends. """ self.adapter.seed_response( command=GetBalancesCommand.command, response={ 'balances': [42], 'duration': 86, }, ) with self.assertRaises(ValueError): self.command( transfers=[ ProposedTransaction( address=Address(self.trytes_1), value=101, ), ], multisigInput=MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ), )
def generate_transaction_and_attach(step, node): arg_list = step.hashes world.config['nodeId'] = node world.config['apiCall'] = 'attachToTangle' options = {} api = api_utils.prepare_api_call(node) api_utils.prepare_options(arg_list, options) addresses = options.get('address') value = options.get('value') transaction = ProposedTransaction(address=Address(addresses[0]), value=value) bundle = ProposedBundle() bundle.add_transaction(transaction) bundle.finalize() trytes = str(bundle[0].as_tryte_string()) gtta = api.get_transactions_to_approve(depth=3) branch = str(gtta['branchTransaction']) trunk = str(gtta['trunkTransaction']) sent = api.attach_to_tangle(trunk, branch, [trytes], 9) world.responses['attachToTangle'] = {} world.responses['attachToTangle'][node] = sent logger.info('Transaction Sent') setattr(static_vals, "TEST_STORE_TRANSACTION", sent.get('trytes'))
def pay(self, data): try: json_data = data['json_data'] json_string = json.dumps(json_data) trytes = TryteString.from_string(json_string) # Send Transfer sent_transfer = self.api.send_transfer( depth=3, transfers=[ ProposedTransaction( address=Address(data['to_address']), value=data['amount'], tag=Tag(data['tag']), message=trytes, ), ]) bo = sent_transfer['bundle'] return { 'status': 200, 'transaction_hash': bo.as_json_compatible()[0]['hash_'], 'message': 'Successfully Sent!' } except Exception as pe: # print('pe:', pe) return { 'status': 400, 'error': '', # 'balance': str(pe.context['total_balance']), 'message': str(pe).split('(')[0] }
def test_sign_input_at_error_not_finalized(self): """ Cannot sign inputs because the bundle isn't finalized yet. """ # Add a transaction so that we can finalize the bundle. self.bundle.add_transaction(ProposedTransaction( address = Address( b'TESTVALUE9DONTUSEINPRODUCTION99999QARFLF' b'TDVATBVFTFCGEHLFJBMHPBOBOHFBSGAGWCM9PG9GX' ), value = 42, )) self.bundle.add_inputs([self.input_0_bal_eq_42]) # Oops; did we forget something? # self.bundle.finalize() private_key =\ KeyGenerator(self.seed).get_key_for(self.input_0_bal_eq_42) with self.assertRaises(RuntimeError): self.bundle.sign_input_at(1, private_key)
def test_fail_unexpected_parameters(self): """ Request contains unexpected parameters. """ self.assertFilterErrors( { 'changeAddress': Address(self.trytes_1), 'multisigInput': MultisigAddress( digests=[self.digest_1, self.digest_2], trytes=self.trytes_2, ), 'transfers': [ ProposedTransaction( address=Address(self.trytes_3), value=42, ), ], # Oh come on! 'foo': 'bar', }, { 'foo': [f.FilterMapper.CODE_EXTRA_KEY], }, )
async def _execute(self, request: dict) -> dict: depth: int = request['depth'] min_weight_magnitude: int = request['minWeightMagnitude'] transaction: TransactionHash = request['transaction'] cc_response = await CheckConsistencyCommand(self.adapter )(tails=[transaction]) if cc_response['state'] is False: raise BadApiResponse( 'Transaction {transaction} is not promotable. ' 'Info: {reason}'.format(transaction=transaction, reason=cc_response['info'])) spam_transfer = ProposedTransaction( address=Address(b''), value=0, ) return await SendTransferCommand(self.adapter)( seed=spam_transfer.address, depth=depth, transfers=[spam_transfer], minWeightMagnitude=min_weight_magnitude, reference=transaction, )