def execute(self, api, **arguments): # type: (Iota, ...) -> int debug_requests = arguments['debug_requests'] pow_uri = arguments['pow_uri'] # If ``pow_uri`` is specified, route POW requests to a separate # node. if pow_uri: pow_adapter = resolve_adapter(pow_uri) api.adapter =\ RoutingWrapper(api.adapter)\ .add_route('attachToTangle', pow_adapter)\ .add_route('interruptAttachingToTangle', pow_adapter) # If ``debug_requests`` is specified, log HTTP requests/responses. if debug_requests: # Inject a logger into the IOTA HTTP adapter. basicConfig(level=DEBUG, stream=stderr) logger = getLogger(__name__) logger.setLevel(DEBUG) api.adapter.set_logger(logger) # Turn on debugging for the underlying HTTP library. http_client.HTTPConnection.debuglevel = 1 try: self._start_repl(api) except KeyboardInterrupt: pass return 0
def __init__(self, seed): """ Initializes the iota api Routes attachToTangle calls to local node Parameters: seed: The account seed """ self.iota_api = Iota( RoutingWrapper(node_address).add_route('attachToTangle', 'http://localhost:14265'), seed) #Find the first address with non-zero balance self.starting_input = Database().get_head_index() address_index = Database().get_address_index() if address_index != 0: for i in range(self.starting_input, address_index): address = self.iota_api.get_new_addresses( self.starting_input, 1)['addresses'] balance = self.iota_api.get_balances(address)['balances'][0] if balance != 0: break else: self.starting_input += 1 Database().incriment_head_index()
def test_routing(self): """ Routing commands to different adapters. """ default_adapter = MockAdapter() pow_adapter = MockAdapter() wrapper = (RoutingWrapper(default_adapter).add_route( 'attachToTangle', pow_adapter).add_route('interruptAttachingToTangle', pow_adapter)) default_adapter.seed_response('getNodeInfo', {'id': 'default1'}) pow_adapter.seed_response('attachToTangle', {'id': 'pow1'}) pow_adapter.seed_response('interruptAttachingToTangle', {'id': 'pow2'}) self.assertDictEqual( wrapper.send_request({'command': 'attachToTangle'}), {'id': 'pow1'}, ) self.assertDictEqual( wrapper.send_request({'command': 'interruptAttachingToTangle'}), {'id': 'pow2'}, ) # Any commands that aren't routed go to the default adapter. self.assertDictEqual( wrapper.send_request({'command': 'getNodeInfo'}), {'id': 'default1'}, )
def __init__(self, seed): """ Initializes the iota api Routes attachToTangle calls to local node Parameters: seed: The account seed """ self.iota_api = Iota( RoutingWrapper(node_address).add_route('attachToTangle', 'http://localhost:14265'), seed) #Find the first address with non-zero balance self.starting_input = 0 address_index = Database().get_address_index() if address_index != 0: used_addresses = self.iota_api.get_new_addresses( 0, address_index)['addresses'] balances = [] for i in range(0, len(used_addresses), 500): balances = balances + self.iota_api.get_balances( used_addresses[i:i + 500])['balances'] for i in range(0, len(balances)): if balances[i] != 0: self.starting_input = i break
def __init__(self,seed,prod=True): self.address_index = 1 if prod: self.init_db() self.iota_api = Iota( RoutingWrapper(node_address) .add_route('attachToTangle','http://localhost:14265'),seed)
def create_api(self, seed, route_pow) -> Iota: """Creates an Iota object to interact with the tangle :param seed: The seed of the device :param route_pow: Boolean to state whether PoW is outsourced :return: An Iota object """ try: if route_pow is True: self.api = \ Iota( RoutingWrapper(self.iota_node) .add_route('attachToTangle', self.pow_node) .add_route('interruptAttachingToTangle', self.pow_node), seed=seed ) else: self.api = Iota(self.iota_node, seed) # Uncomment to test node after creating an API # self.test_node() return self.api except ConnectionRefusedError as e: print(e) print("Ensure all nodes are working correctly before connecting")
def execute(self, api: Iota, **arguments: Any) -> int: debug_requests = arguments['debug_requests'] pow_uri = arguments['pow_uri'] # If ``pow_uri`` is specified, route POW requests to a separate # node. if pow_uri: pow_adapter = resolve_adapter(pow_uri) api.adapter = RoutingWrapper(api.adapter) api.adapter.add_route('attachToTangle', pow_adapter) api.adapter.add_route('interruptAttachingToTangle', pow_adapter) # If ``debug_requests`` is specified, log HTTP requests/responses. if debug_requests: # Inject a logger into the IOTA HTTP adapter. # This will turn on logging for underlying httpx client as well basicConfig(level=DEBUG, stream=stderr) logger = getLogger(__name__) logger.setLevel(DEBUG) api.adapter.set_logger(logger) try: self._start_repl(api) except KeyboardInterrupt: pass return 0
def __init__(self,seed): """ Initializes the iota api Routes attachToTangle calls to local node Parameters: seed: The account seed """ self.iota_api = Iota( RoutingWrapper(node_address) .add_route('attachToTangle','http://localhost:14265'),seed)
def iota_transaction(light_id): response = requests.post( 'http://127.0.0.1:8080/request_light_address', json=light_id ) # request an address for the corresponding light that is arriving service_addr = response.json()['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', 'http://localhost:14265'), # Seed used for cryptographic functions. seed = b'CABREEMIRYLXLSWDLPUKFAMWMVBJYUIYQFBQGEE9BSCBCVOXXSTAXISQXGUIDPWZENEIYJNSXCGNHLRXG' ) # Example of sending a transfer using the adapter. send_transfer_response = api.send_transfer( depth=1, #100 transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address(service_addr), # Amount of IOTA to transfer. # This value may be zero. value=0, # Optional tag to attach to the transfer. tag=Tag(b'9999999999999999'), # Optional message to include with the transfer. message=TryteString.from_string('transaction made'), ), ], ) bundle = send_transfer_response['bundle'] for i in range(len(bundle.transactions)): transaction = bundle.transactions[i] if transaction.address == service_addr: # transaction.address is the address associated with this transaction TRANSACTION_ID = str( transaction.hash ) # the transaction hash is used to uniquely identify the transaction on the Tangle; the value is generated by taking a hash of the raw transaction trits # we assume in the code here that a single transaction was made to the recipient's address; otherwise, the code must be modified so that multiple TRANSACTION_IDs are stored print('{}. Transaction ID: {}'.format(i + 1, TRANSACTION_ID)) else: TRANSACTION_ID = 'This transaction was not intended for the client.' print('{}. {}'.format(i + 1, TRANSACTION_ID)) response = {} response['transaction_id'] = TRANSACTION_ID # string final = requests.post( 'http://127.0.0.1:8080/request_transaction_read', json=response ) # request an address for the corresponding light that is arriving
def main(uri, testnet, pow_uri, debug_requests): # type: (Text, bool, Text, bool) -> None seed = secure_input( 'Enter seed and press return (typing will not be shown).\n' 'If no seed is specified, a random one will be used instead.\n') if isinstance(seed, text_type): seed = seed.encode('ascii') adapter_ = resolve_adapter(uri) # If ``pow_uri`` is specified, route POW requests to a separate node. if pow_uri: pow_adapter = resolve_adapter(pow_uri) adapter_ =\ RoutingWrapper(adapter_)\ .add_route('attachToTangle', pow_adapter)\ .add_route('interruptAttachingToTangle', pow_adapter) # If ``debug_requests`` is specified, log HTTP requests/responses. if debug_requests: basicConfig(level=DEBUG, stream=stderr) logger = getLogger(__name__) logger.setLevel(DEBUG) adapter_.set_logger(logger) iota = Iota(adapter_, seed=seed, testnet=testnet) # To speed up certain operations, install an address cache. AddressGenerator.cache = MemoryAddressCache() _banner = ( 'IOTA API client for {uri} ({testnet}) initialized as variable `iota`.\n' 'Type `help(iota)` for help.'.format( testnet='testnet' if testnet else 'mainnet', uri=uri, )) start_shell(iota, _banner)
def rule_followed(): if request.method == 'POST': data_in = request.json index = int(data_in['Vehicle Index']) + 2 cell = 'K' + str(index) print(cell) client_address_value = sheet.acell(cell).value iotaAPIWithLocalPoW = Iota( RoutingWrapper('https://nodes.thetangle.org:443').add_route( 'attachToTangle', 'http://localhost:14265'), seed= b'XUFCORFPGGCXJNSROYIFWWZGGRNUGIZARFZUIDZJOGPPMAFRGRLATGTMDSQDUBLRWMAGWRUHAOSFMSRHJ' ) # Sends an empty transfer using the adapter. send_transfer_response = iotaAPIWithLocalPoW.send_transfer( depth=1, transfers=[ ProposedTransaction( address=Address( client_address_value), # recipient of the transfer value= 0, # amount of IOTA to transfer; this value may be zero tag=Tag(b'999999999999999999999999999' ), # optional tag to attach to the transfer message=TryteString.from_string( 'This is a test message.' ), # optional message to include with the transfer ), ], ) bundle = send_transfer_response['bundle'] print('Number of transactions associated with this bundle: {}'.format( len(bundle.transactions))) for i in range(len(bundle.transactions)): transaction = bundle.transactions[i] if transaction.address == client_address_value: # transaction.address is the address associated with this transaction TRANSACTION_ID = str( transaction.hash ) # the transaction hash is used to uniquely identify the transaction on the Tangle; the value is generated by taking a hash of the raw transaction trits # we assume in the code here that a single transaction was made to the recipient's address; otherwise, the code must be modified so that multiple TRANSACTION_IDs are stored print('{}. Transaction ID: {}'.format(i + 1, TRANSACTION_ID)) else: TRANSACTION_ID = 'This transaction was not intended for the client.' print('{}. {}'.format(i + 1, TRANSACTION_ID)) response = {} response['transaction_id'] = TRANSACTION_ID # string return jsonify(response)
def test_routing(self): """ Routing commands to different adapters. """ default_adapter = MockAdapter() pow_adapter = MockAdapter() wrapper = (RoutingWrapper(default_adapter) .add_route('attachToTangle', pow_adapter) .add_route('interruptAttachingToTangle', pow_adapter) ) print_var_type_n_val(var001 = wrapper, pointer = "#ZERTYSDdfg236")#ZERTYSDdfg236 # Value: # # <iota.adapter.wrappers.RoutingWrapper object at 0x000001E406CE30B8> # Type: <class 'iota.adapter.wrappers.RoutingWrapper'> default_adapter.seed_response('getNodeInfo', {'id': 'default1'}) print_var_type_n_val(var001 = wrapper, pointer = "#2345gfdsSDFG")#2345gfdsSDFG # Value: # # <iota.adapter.wrappers.RoutingWrapper object at 0x000001E406CE30B8> # Type: <class 'iota.adapter.wrappers.RoutingWrapper'> pow_adapter.seed_response('attachToTangle', {'id': 'pow1'}) print_var_type_n_val(var001 = wrapper, pointer = "#34TgfdXCVBgfd111111")#34TgfdXCVBgfd111111 # Value: # # <iota.adapter.wrappers.RoutingWrapper object at 0x000001E406CE30B8> # Type: <class 'iota.adapter.wrappers.RoutingWrapper'> pow_adapter.seed_response('interruptAttachingToTangle', {'id': 'pow2'}) self.assertDictEqual( wrapper.send_request({'command': 'attachToTangle'}), {'id': 'pow1'}, ) self.assertDictEqual( wrapper.send_request({'command': 'interruptAttachingToTangle'}), {'id': 'pow2'}, ) # Any commands that aren't routed go to the default adapter. self.assertDictEqual( wrapper.send_request({'command': 'getNodeInfo'}), {'id': 'default1'}, )
def test_routing_wrapper(self): """ Test if local_pow feature works with RoutingWrapper. """ # Note that we need correct return value to pass the # response filter. with patch('pow.ccurl_interface.attach_to_tangle', MagicMock(return_value=self.bundle)) as mocked_ccurl: # We are trying to redirect `attach_to_tangle` calls to localhost # with a RoutingWrapper. However, if local_pow=true, the pow # request will not reach the adapter, but will be directed to # ccurl interface. api = Iota(RoutingWrapper('http://12.34.56.78:14265').add_route( 'attachToTangle', 'http://localhost:14265'), local_pow=True) result = api.attach_to_tangle(self.trunk, self.branch, self.bundle, self.mwm) self.assertTrue(mocked_ccurl.called) self.assertEqual(result['trytes'], self.bundle)
def __init__(self, Seed, IOTA_Instance=""): Configuration.__init__(self) try: Optimal_Node = Return_Fastest_Node()["Send"] if Optimal_Node == 999.0: Optimal_Node = Return_Fastest_Node()["Receive"] config.Node = Optimal_Node except: config.Node = "http://localhost:14265" if config.Node == "http://localhost:14265": self.IOTA_Api = Iota(RoutingWrapper(str(config.Node)).add_route( 'attachToTangle', 'http://localhost:14265'), seed=Seed) else: self.IOTA_Api = Iota(config.Node, seed=Seed) if IOTA_Instance != "": self.IOTA_Api = IOTA_Instance self.Seed_Copy = Seed
def send(msg): DEPTH = msg.depth REC_ADDRESS = msg.address VALUE = msg.sending_value TAG = msg.tag MSG = msg.message api =\ Iota( RoutingWrapper(NODE_ROUTING) .add_route('attachToTangle', NODE_POW), seed = SEED ) transaction = api.send_transfer( depth=DEPTH, transfers=[ ProposedTransaction( address=Address(REC_ADDRESS), value=VALUE, tag=Tag(TAG), message=TryteString.from_string(MSG), ), ], )
def batch_transfer(filename, node_uri, seed, amount_of_seeds=100, amount_per_seed=10000, batch_size=25, depth=3, tag='GIFT', message='', pow_node_uri=None): needed_funds = amount_of_seeds * amount_per_seed print('You are about to spend %s iota spread out over %s addresses.' % (needed_funds, amount_of_seeds)) print('Checking your seeds balance...') if pow_node_uri: router = RoutingWrapper(node_uri) router.add_route('attachToTangle', pow_node_uri) api = Iota(router, seed) else: api = Iota(node_uri, seed) inputs = api.get_inputs() balance = inputs['totalBalance'] if balance < needed_funds: print( "You don't have enough funds available on your SEED, please make sure your seed has at least %si available!" % needed_funds) return print( 'You have enough available to transfer the %si, Generating %d seeds and addresses now...' % (needed_funds, amount_of_seeds)) seedlist = [] for i in range(amount_of_seeds): random_seed = ''.join( [choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ9') for x in range(81)]) gen = AddressGenerator(random_seed) new_addr = gen.get_addresses(0, 1, 2)[0] seedlist.append((random_seed, new_addr)) print('.', sep='', end='', flush=True) print('\n') with open(filename, 'w') as fh: writer = csv.writer(fh) writer.writerow(['Seed', 'Address', 'Iota']) for gseed, gaddr in seedlist: writer.writerow([gseed, gaddr, amount_per_seed]) print('All seeds and addresses are now available in %s!' % filename) amount_of_bundles = (amount_of_seeds // batch_size) + 1 if amount_of_seeds % batch_size == 0: amount_of_bundles -= 1 print( 'We will generate and send %d bundles containing %d transactions per bundle max, this can take a while...' % (amount_of_bundles, batch_size)) from_addr = None for i in range(amount_of_bundles): sliced = seedlist[i * batch_size:(i + 1) * batch_size] print('Starting transfer of bundle %d containing %d seeds...' % (i + 1, len(sliced))) transfers = [] for gseed, gaddr in sliced: transfers.append( ProposedTransaction( address=gaddr, value=amount_per_seed, tag=Tag(tag), message=TryteString.from_string(message), )) bundle = api.send_transfer(depth=depth, transfers=transfers) for tx in bundle['bundle'].transactions: if tx.current_index == tx.last_index: print('Remainder:', tx.current_index, tx.address, tx.value) from_addr = tx.address if amount_per_seed == 0: continue print( 'Waiting for the TX to confirm and the remainder address (%s) to fill...' % tx.address) while True: balances = api.get_balances([tx.address], 100) if balances['balances'][0] > 0: break else: print('...', sep='', end='', flush=True) sleep(5) print('\n') print('Transfer complete.') print('All done!')
import iota from iota import * from iota.adapter.wrappers import RoutingWrapper 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("")
""" Reattaching with RoutingWrapper """ from iota import Iota from iota.adapter.wrappers import RoutingWrapper # a list of public nodes can be found here: http://iota.dance/nodes PUBLIC_NODE = 'http://176.9.3.149:14265' LOCAL_NODE = 'http://localhost:14265' API = Iota( RoutingWrapper(PUBLIC_NODE).add_route('attachToTangle', LOCAL_NODE).add_route( 'interruptAttachingToTangle', LOCAL_NODE)) bundle_hash = input('Paste bundle hash: ') """ API.replay_bundle does not accept a bundle hash as argument. You have to pass the transaction hash with a currentIndex of 0 (= the first transaction or "tail transaction" of a bundle). That's why we have to get the transaction hashes of the bundle with API.find_transactions. Then we have to find out which of the returned transactions has a currentIndex of 0. """ print('Fetching transaction hashes...') transaction_hashes = API.find_transactions(bundles=[bundle_hash])['hashes'] print('Received transaction hashes.')
# coding=utf-8 """ Simple example using the RoutingWrapper to route API requests to different nodes. See: https://github.com/iotaledger/documentation/blob/iota.lib.py/1.2.x/source/includes/_adapters.md#routingwrapper """ from iota import Iota, ProposedTransaction, Address, Tag, TryteString from iota.adapter.wrappers import RoutingWrapper api = \ Iota( # Send PoW requests to local node. # All other requests go to light wallet node. RoutingWrapper('http://service.iotasupport.com:14265').add_route('attachToTangle', 'http://localhost:14265'), # Seed used for cryptographic functions. seed=b'SEED9GOES9HERE' ) # Example of sending a transfer using the adapter. bundle = api.send_transfer( depth=100, transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address( # b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' # b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR' ), # Amount of IOTA to transfer. # This value may be zero.
def __init__(self, Seed): Configuration.__init__(self) self.IOTA_Api = Iota(RoutingWrapper(str(self.Node)).add_route( 'attachToTangle', 'http://localhost:14265'), seed=Seed)
'Compostable Cup Bin Project-abe8f907feca.json', scope) client = gspread.authorize(creds) wksp = client.open('Compostable Cups List').sheet1 return (wksp) sheet = setup() for i in range(10, 11): start = time.time() try: 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', 'http://localhost:14265'), # Seed used for cryptographic functions. seed = b'CABREEMIRYLXLSWDLPUKFAMWMVBJYUIYQFBQGEE9BSCBCVOXXSTAXISQXGUIDPWZENEIYJNSXCGNHLRXG' ) # Example of sending a transfer using the adapter. bundle = api.send_transfer( depth=1, #100 transfers=[ ProposedTransaction( # Recipient of the transfer. address=Address( b'XXCPQKGFDFRLFXVUSZJTUKFPTJZKWKZHMZITQMCAEDOVUJYLXIYJGHEOLSDIGYDTUHUKVSC9YZZZDDOSC' ),
def test_router_aliasing(self): """ The router will try to re-use existing adapter instances. """ wrapper1 = RoutingWrapper('http://localhost:14265') adapter_default = wrapper1.adapter # The router will try to minimize the number of adapter instances # that it creates from URIs. wrapper1\ .add_route('alpha', 'http://localhost:14265')\ .add_route('bravo', 'http://localhost:14265')\ # Two routes with the same URI => same adapter instance. self.assertIs( wrapper1.get_adapter('bravo'), wrapper1.get_adapter('alpha'), ) # "127.0.0.1" != "localhost", so separate adapters created. wrapper1.add_route('charlie', 'http://127.0.0.1:14265') self.assertIsNot( wrapper1.get_adapter('charlie'), wrapper1.get_adapter('alpha'), ) # Providing an adapter instance bypasses the whole setup. wrapper1.add_route('delta', HttpAdapter('http://localhost:14265')) self.assertIsNot( wrapper1.get_adapter('delta'), wrapper1.get_adapter('alpha'), ) # The default adapter is always kept separate, even if it URI # matches a routing adapter. self.assertIsNot( wrapper1.get_adapter('foo'), wrapper1.get_adapter('alpha'), ) # Aliased adapters are not shared between routers. wrapper2 = RoutingWrapper(adapter_default) wrapper2.add_route('echo', 'http://localhost:14265') self.assertIsNot( wrapper2.get_adapter('echo'), wrapper1.get_adapter('alpha'), )
import iota from iota import * from iota.adapter.wrappers import RoutingWrapper while True: print("") address = 'RANDOM 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'RANDOM SEED' ) FinalBundle = api.replay_bundle(transaction='OLD TRANSACTION ADDRESS', depth=3, min_weight_magnitude=14) print("") print("1 More.")
def test_router_aliasing(self): """ The router will try to re-use existing adapter instances. """ wrapper1 = RoutingWrapper('http://localhost:14265') print_var_type_n_val(var001 = wrapper1, pointer = "#2345trezGH-(")#2345trezGH-( # Value: # # <iota.adapter.wrappers.RoutingWrapper object at 0x0000024C271B17B8> # Type: <class 'iota.adapter.wrappers.RoutingWrapper'> adapter_default = wrapper1.adapter print_var_type_n_val(var001 = adapter_default, pointer = "#SDFGnbvc1234098QSDnbe")#SDFGnbvc1234098QSDnbe # Value: # # <iota.adapter.HttpAdapter object at 0x0000024C25E7AB70> # Type: <class 'iota.adapter.HttpAdapter'> # The router will try to minimize the number of adapter instances # that it creates from URIs. wrapper1\ .add_route('alpha', 'http://localhost:14265')\ .add_route('bravo', 'http://localhost:14265')\ print_var_type_n_val(var001 = wrapper1, pointer = "#2345trezGH2345YTRE")#2345trezGH2345YTRE # Value: # # <iota.adapter.wrappers.RoutingWrapper object at 0x000001601AD6FD68> # Type: <class 'iota.adapter.wrappers.RoutingWrapper'> # Two routes with the same URI => same adapter instance. self.assertIs( wrapper1.get_adapter('bravo'), wrapper1.get_adapter('alpha'), ) # "127.0.0.1" != "localhost", so separate adapters created. wrapper1.add_route('charlie', 'http://127.0.0.1:14265') self.assertIsNot( wrapper1.get_adapter('charlie'), wrapper1.get_adapter('alpha'), ) # Providing an adapter instance bypasses the whole setup. wrapper1.add_route('delta', HttpAdapter('http://localhost:14265')) self.assertIsNot( wrapper1.get_adapter('delta'), wrapper1.get_adapter('alpha'), ) # The default adapter is always kept separate, even if it URI # matches a routing adapter. self.assertIsNot( wrapper1.get_adapter('foo'), wrapper1.get_adapter('alpha'), ) # Aliased adapters are not shared between routers. wrapper2 = RoutingWrapper(adapter_default) wrapper2.add_route('echo', 'http://localhost:14265') self.assertIsNot( wrapper2.get_adapter('echo'), wrapper1.get_adapter('alpha'), )