From 1318039f888caeee8def746b8c24985ca1a9d9b8 Mon Sep 17 00:00:00 2001 From: Phoenix Zerin Date: Sat, 23 Jun 2018 11:12:45 +1200 Subject: [PATCH] [#145] Reformatted examples for PEP-8. --- examples/address_generator.py | 205 ++++++++-------- examples/hello_world.py | 65 ++--- examples/mam_js_send.py | 418 +++++++++++++++++---------------- examples/multisig.py | 129 +++++----- examples/routingwrapper_pow.py | 61 ++--- examples/sandbox.py | 73 +++--- examples/send_transfer.py | 59 ++--- 7 files changed, 504 insertions(+), 506 deletions(-) diff --git a/examples/address_generator.py b/examples/address_generator.py index 01043e6..3bb7876 100644 --- a/examples/address_generator.py +++ b/examples/address_generator.py @@ -4,128 +4,133 @@ """ from __future__ import absolute_import, division, print_function, \ - unicode_literals + unicode_literals from argparse import ArgumentParser from getpass import getpass as secure_input from sys import argv from typing import Optional, Text -from iota import __version__, Iota +from six import binary_type, moves as compat, text_type + +from iota import Iota, __version__ from iota.crypto.addresses import AddressGenerator from iota.crypto.types import Seed -from six import binary_type, moves as compat, text_type def main(uri, index, count, security, checksum): - # type: (Text, int, Optional[int], Optional[int], bool) -> None - seed = get_seed() + # type: (Text, int, Optional[int], Optional[int], bool) -> None + seed = get_seed() - # Create the API instance. - # Note: If ``seed`` is null, a random seed will be generated. - api = Iota(uri, seed) + # Create the API instance. + # Note: If ``seed`` is null, a random seed will be generated. + api = Iota(uri, seed) - # If we generated a random seed, then we need to display it to the - # user, or else they won't be able to use their new addresses! - if not seed: - print('A random seed has been generated. Press return to see it.') - output_seed(api.seed) + # If we generated a random seed, then we need to display it to the + # user, or else they won't be able to use their new addresses! + if not seed: + print('A random seed has been generated. Press return to see it.') + output_seed(api.seed) - print('Generating addresses. This may take a few minutes...') - print('') + print('Generating addresses. This may take a few minutes...') + print('') - # Here's where all the magic happens! - api_response = api.get_new_addresses(index, count, security, checksum) - for addy in api_response['addresses']: - print(binary_type(addy).decode('ascii')) + # Here's where all the magic happens! + api_response = api.get_new_addresses(index, count, security, checksum) + for addy in api_response['addresses']: + print(binary_type(addy).decode('ascii')) - print('') + print('') def get_seed(): - # type: () -> binary_type - """ - Prompts the user securely for their seed. - """ - print( - 'Enter seed and press return (typing will not be shown). ' - 'If empty, a random seed will be generated and displayed on the screen.' - ) - seed = secure_input('') # type: Text - return seed.encode('ascii') + # type: () -> binary_type + """ + Prompts the user securely for their seed. + """ + print( + 'Enter seed and press return (typing will not be shown). ' + 'If empty, a random seed will be generated and displayed on the screen.' + ) + seed = secure_input('') # type: Text + return seed.encode('ascii') def output_seed(seed): - # type: (Seed) -> None - """ - Outputs the user's seed to stdout, along with lots of warnings - about security. - """ - print( - 'WARNING: Anyone who has your seed can spend your IOTAs! ' - 'Clear the screen after recording your seed!' - ) - compat.input('') - print('Your seed is:') - print('') - print(binary_type(seed).decode('ascii')) - print('') - - print( - 'Clear the screen to prevent shoulder surfing, ' - 'and press return to continue.' - ) - print('https://en.wikipedia.org/wiki/Shoulder_surfing_(computer_security)') - compat.input('') + # type: (Seed) -> None + """ + Outputs the user's seed to stdout, along with lots of warnings + about security. + """ + print( + 'WARNING: Anyone who has your seed can spend your IOTAs! ' + 'Clear the screen after recording your seed!' + ) + compat.input('') + print('Your seed is:') + print('') + print(binary_type(seed).decode('ascii')) + print('') + + print( + 'Clear the screen to prevent shoulder surfing, ' + 'and press return to continue.' + ) + print('https://en.wikipedia.org/wiki/Shoulder_surfing_(computer_security)') + compat.input('') if __name__ == '__main__': - parser = ArgumentParser( - description = __doc__, - epilog = 'PyOTA v{version}'.format(version=__version__), - ) - - parser.add_argument( - '--uri', - type = text_type, - default = 'http://localhost:14265/', - - help = - 'URI of the node to connect to ' - '(defaults to http://localhost:14265/).', - ) - - parser.add_argument( - '--index', - type = int, - default = 0, - help = 'Index of the key to generate.', - ) - - parser.add_argument( - '--count', - type = int, - default = None, - - help = - 'Number of addresses to generate. ' - 'If not specified, the first unused address will be returned.' - ) - - parser.add_argument( - '--security', - type = int, - default = AddressGenerator.DEFAULT_SECURITY_LEVEL, - help = 'Security level to be used for the private key / address. ' - 'Can be 1, 2 or 3', - ) - - parser.add_argument( - '--with-checksum', - action = 'store_true', - default = False, - dest = 'checksum', - help = 'List the address with the checksum.', - ) - - main(**vars(parser.parse_args(argv[1:]))) + parser = ArgumentParser( + description=__doc__, + epilog='PyOTA v{version}'.format(version=__version__), + ) + + parser.add_argument( + '--uri', + type=text_type, + default='http://localhost:14265/', + + help=( + 'URI of the node to connect to ' + '(defaults to http://localhost:14265/).' + ), + ) + + parser.add_argument( + '--index', + type=int, + default=0, + help='Index of the key to generate.', + ) + + parser.add_argument( + '--count', + type=int, + default=None, + + help=( + 'Number of addresses to generate. ' + 'If not specified, the first unused address will be returned.' + ), + ) + + parser.add_argument( + '--security', + type=int, + default=AddressGenerator.DEFAULT_SECURITY_LEVEL, + help=( + 'Security level to be used for the private key / address. ' + 'Can be 1, 2 or 3' + ), + ) + + parser.add_argument( + '--with-checksum', + action='store_true', + default=False, + dest='checksum', + help='List the address with the checksum.', + ) + + main(**vars(parser.parse_args(argv[1:]))) diff --git a/examples/hello_world.py b/examples/hello_world.py index e1a2667..bf24d34 100644 --- a/examples/hello_world.py +++ b/examples/hello_world.py @@ -5,7 +5,7 @@ """ from __future__ import absolute_import, division, print_function, \ - unicode_literals + unicode_literals from argparse import ArgumentParser from pprint import pprint @@ -19,36 +19,39 @@ def main(uri): - # type: (Text) -> None - api = StrictIota(uri) - - try: - node_info = api.get_node_info() - except ConnectionError as e: - print("Hm. {uri} isn't responding. Is the node running?".format(uri=uri)) - print(e) - except BadApiResponse as e: - print("Looks like {uri} isn't very talkative today ):".format(uri=uri)) - print(e) - else: - print('Hello {uri}!'.format(uri=uri)) - pprint(node_info) + # type: (Text) -> None + api = StrictIota(uri) + + try: + node_info = api.get_node_info() + except ConnectionError as e: + print( + "Hm. {uri} isn't responding; is the node running?".format(uri=uri) + ) + print(e) + except BadApiResponse as e: + print("Looks like {uri} isn't very talkative today ):".format(uri=uri)) + print(e) + else: + print('Hello {uri}!'.format(uri=uri)) + pprint(node_info) if __name__ == '__main__': - parser = ArgumentParser( - description = __doc__, - epilog = 'PyOTA v{version}'.format(version=__version__), - ) - - parser.add_argument( - '--uri', - type = text_type, - default = 'http://localhost:14265/', - - help = - 'URI of the node to connect to ' - '(defaults to http://localhost:14265/).', - ) - - main(**vars(parser.parse_args(argv[1:]))) + parser = ArgumentParser( + description=__doc__, + epilog='PyOTA v{version}'.format(version=__version__), + ) + + parser.add_argument( + '--uri', + type=text_type, + default='http://localhost:14265/', + + help=( + 'URI of the node to connect to ' + '(defaults to http://localhost:14265/).' + ), + ) + + main(**vars(parser.parse_args(argv[1:]))) diff --git a/examples/mam_js_send.py b/examples/mam_js_send.py index 71a3a8c..23039eb 100644 --- a/examples/mam_js_send.py +++ b/examples/mam_js_send.py @@ -1,6 +1,6 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function, \ - unicode_literals + unicode_literals import codecs import json @@ -14,223 +14,225 @@ from iota import Bundle, Iota, TransactionTrytes from iota.bin import IotaCommandLineApp -from iota.json import JsonEncoder from iota.crypto.addresses import AddressGenerator from iota.filters import Trytes +from iota.json import JsonEncoder class IotaMamExample(IotaCommandLineApp): - """ - Shows how to integrate the ``mam.client.js`` Javascript library into a - Python script, until MAM functionality is implemented in PyOTA. - - In order to execute this script, you must install Node and the - ``mam.client.js`` library. - - See https://github.com/iotaledger/mam.client.js for more information. - """ - def execute(self, api, **arguments): - # type: (Iota, ...) -> int - channel_key_index = arguments['channel_key_index'] # type: int - count = arguments['count'] # type: int - depth = arguments['depth'] # type: int - dry_run = arguments['dry_run'] # type: bool - mam_encrypt_path = arguments['mam_encrypt_path'] # type: Text - min_weight_magnitude = arguments['min_weight_magnitude'] # type: int - message_encoding = arguments['message_encoding'] # type: Text - message_file = arguments['message_file'] # type: Optional[Text] - security_level = arguments['security_level'] # type: int - start = arguments['start'] # type: int - - if message_file: - with codecs.open(message_file, 'r', message_encoding) as f_: # type: codecs.StreamReaderWriter - message = f_.read() - - else: - self.stdout.write( - 'Enter message to send. Press Ctrl-D on a blank line when done.\n\n', - ) - - message = self.stdin.read().strip() - self.stdout.write('\n') - - # Generating the encrypted message may take a little while, so we - # should provide some feedback to the user so that they know that - # their input is being processed (this is especially important if - # the user typed in their message, so that they don't press ^D - # again, thinking that the program didn't register the first one). - self.stdout.write('Encrypting message...\n') - - proc =\ - run( - args = [ - # mam_encrypt.js - mam_encrypt_path, - - # Required arguments - binary_type(api.seed), - message, - - # Options - '--channel-key-index', text_type(channel_key_index), - '--start', text_type(start), - '--count', text_type(count), - '--security-level', text_type(security_level), - ], - - check = True, - stdout = PIPE, - stderr = self.stderr, - ) - - # The output of the JS script is a collection of transaction - # trytes, encoded as JSON. - filter_ =\ - f.FilterRunner( - starting_filter = - f.Required - | f.Unicode - | f.JsonDecode - | f.Array - | f.FilterRepeater( - f.ByteString(encoding='ascii') - | Trytes(result_type=TransactionTrytes) + """ + Shows how to integrate the ``mam.client.js`` Javascript library into + a Python script, until MAM functionality is implemented in PyOTA. + + In order to execute this script, you must install Node and the + ``mam.client.js`` library. + + See https://github.com/iotaledger/mam.client.js for more + information. + """ + + def execute(self, api, **arguments): + # type: (Iota, ...) -> int + channel_key_index = arguments['channel_key_index'] # type: int + count = arguments['count'] # type: int + depth = arguments['depth'] # type: int + dry_run = arguments['dry_run'] # type: bool + mam_encrypt_path = arguments['mam_encrypt_path'] # type: Text + min_weight_magnitude = arguments['min_weight_magnitude'] # type: int + message_encoding = arguments['message_encoding'] # type: Text + message_file = arguments['message_file'] # type: Optional[Text] + security_level = arguments['security_level'] # type: int + start = arguments['start'] # type: int + + if message_file: + with codecs.open(message_file, 'r', message_encoding) as f_: + message = f_.read() + + else: + self.stdout.write( + 'Enter message to send. ' + 'Press Ctrl-D on a blank line when done.\n\n', + ) + + message = self.stdin.read().strip() + self.stdout.write('\n') + + # Generating the encrypted message may take a little while, so + # we should provide some feedback to the user so that they know + # that their input is being processed (this is especially + # important if the user typed in their message, so that they + # don't press ^D again, thinking that the program didn't + # register the first one). + self.stdout.write('Encrypting message...\n') + + proc = run( + args=[ + # mam_encrypt.js + mam_encrypt_path, + + # Required arguments + binary_type(api.seed), + message, + + # Options + '--channel-key-index', text_type(channel_key_index), + '--start', text_type(start), + '--count', text_type(count), + '--security-level', text_type(security_level), + ], + + check=True, + stdout=PIPE, + stderr=self.stderr, + ) + + # The output of the JS script is a collection of transaction + # trytes, encoded as JSON. + filter_ = f.FilterRunner( + f.Required | f.Unicode | f.JsonDecode | f.Array | f.FilterRepeater( + f.ByteString(encoding='ascii') | Trytes(TransactionTrytes), + ), + + incoming_data=proc.stdout, + ) + + if not filter_.is_valid(): + self.stderr.write( + 'Invalid output from {mam_encrypt_path}:\n' + '\n' + 'Output:\n' + '{output}\n' + '\n' + 'Errors:\n' + '{errors}\n'.format( + errors=pformat(filter_.get_errors(with_context=True)), + mam_encrypt_path=mam_encrypt_path, + output=proc.stdout, + ), + ) + + return 2 + + transaction_trytes = ( + filter_.cleaned_data + ) # type: List[TransactionTrytes] + + bundle = Bundle.from_tryte_strings(transaction_trytes) + + if dry_run: + self.stdout.write('Transactions:\n\n') + self.stdout.write(json.dumps(bundle, cls=JsonEncoder, indent=2)) + else: + api.send_trytes( + depth=depth, + trytes=transaction_trytes, + min_weight_magnitude=min_weight_magnitude, + ) + + self.stdout.write('Message broadcast successfully!\n') + self.stdout.write( + 'Bundle ID: {bundle_hash}\n'.format( + bundle_hash=bundle.hash, + ), + ) + + return 0 + + def create_argument_parser(self): + # type: () -> ArgumentParser + parser = super(IotaMamExample, self).create_argument_parser() + + parser.add_argument( + 'mam_encrypt_path', + + help='Path to `mam_encrypt.js` script.', + ) + + parser.add_argument( + '--channel-key-index', + default=0, + dest='channel_key_index', + type=int, + + help='Index of the key used to establish the channel.', + ) + + parser.add_argument( + '--start', + default=0, + type=int, + + help='Index of the first key used to encrypt the message.', + ) + + parser.add_argument( + '--count', + default=1, + type=int, + + help='Number of keys to use to encrypt the message.', + ) + + parser.add_argument( + '--security-level', + default=AddressGenerator.DEFAULT_SECURITY_LEVEL, + type=int, + + help='Number of iterations to use when generating keys.', + ) + + parser.add_argument( + '--message-file', + dest='message_file', + + help=( + 'Path to file containing the message to send. ' + 'If not provided, you will be prompted for the message ' + 'via stdin.' ), + ) + + parser.add_argument( + '--message-encoding', + dest='message_encoding', + default='utf-8', + + help='Encoding used to interpret message.', + ) - incoming_data = proc.stdout, - ) - - if not filter_.is_valid(): - self.stderr.write( - 'Invalid output from {mam_encrypt_path}:\n' - '\n' - 'Output:\n' - '{output}\n' - '\n' - 'Errors:\n' - '{errors}\n'.format( - errors = pformat(filter_.get_errors(with_context=True)), - mam_encrypt_path = mam_encrypt_path, - output = proc.stdout, - ), - ) - - return 2 - - transaction_trytes = filter_.cleaned_data # type: List[TransactionTrytes] - - bundle = Bundle.from_tryte_strings(transaction_trytes) - - if dry_run: - self.stdout.write('Transactions:\n\n') - self.stdout.write(json.dumps(bundle, cls=JsonEncoder, indent=2)) - else: - api.send_trytes( - depth = depth, - trytes = transaction_trytes, - min_weight_magnitude = min_weight_magnitude, - ) - - self.stdout.write('Message broadcast successfully!\n') - self.stdout.write( - 'Bundle ID: {bundle_hash}\n'.format( - bundle_hash = bundle.hash, - ), - ) - - return 0 - - def create_argument_parser(self): - # type: () -> ArgumentParser - parser = super(IotaMamExample, self).create_argument_parser() - - parser.add_argument( - 'mam_encrypt_path', - - help = 'Path to `mam_encrypt.js` script.', - ) - - parser.add_argument( - '--channel-key-index', - default = 0, - dest = 'channel_key_index', - type = int, - - help = 'Index of the key used to establish the channel.', - ) - - parser.add_argument( - '--start', - default = 0, - type = int, - - help = 'Index of the first key used to encrypt the message.', - ) - - parser.add_argument( - '--count', - default = 1, - type = int, - - help = 'Number of keys to use to encrypt the message.', - ) - - parser.add_argument( - '--security-level', - default = AddressGenerator.DEFAULT_SECURITY_LEVEL, - type = int, - - help = 'Number of iterations to use when generating keys.', - ) - - parser.add_argument( - '--message-file', - dest = 'message_file', - - help = - 'Path to file containing the message to send. ' - 'If not provided, you will be prompted for the message via stdin.', - ) - - parser.add_argument( - '--message-encoding', - dest = 'message_encoding', - default = 'utf-8', - - help = 'Encoding used to interpret message.', - ) - - parser.add_argument( - '--depth', - default = 3, - type = int, - - help = 'Depth at which to attach the resulting transactions.', - ) - - parser.add_argument( - '--min-weight-magnitude', - dest = 'min_weight_magnitude', - type = int, + parser.add_argument( + '--depth', + default=3, + type=int, - help = - 'Min weight magnitude, used by the node to calibrate PoW. ' - 'If not provided, a default value will be used.', - ) + help='Depth at which to attach the resulting transactions.', + ) - parser.add_argument( - '--dry-run', - action = 'store_true', - default = False, - dest = 'dry_run', - - help = - 'If set, resulting transactions will be sent to stdout instead of' - 'broadcasting to the Tangle.', - ) + parser.add_argument( + '--min-weight-magnitude', + dest='min_weight_magnitude', + type=int, + + help=( + 'Min weight magnitude, used by the node to calibrate PoW. ' + 'If not provided, a default value will be used.' + ), + ) + + parser.add_argument( + '--dry-run', + action='store_true', + default=False, + dest='dry_run', + + help=( + 'If set, resulting transactions will be sent to stdout ' + 'instead of broadcasting to the Tangle.' + ), + ) - return parser + return parser if __name__ == '__main__': - IotaMamExample().main() + IotaMamExample().main() diff --git a/examples/multisig.py b/examples/multisig.py index dcd0d41..ac1baba 100644 --- a/examples/multisig.py +++ b/examples/multisig.py @@ -11,12 +11,12 @@ """ from __future__ import absolute_import, division, print_function, \ - unicode_literals + unicode_literals from typing import List from iota import Address, Bundle, BundleValidator, ProposedTransaction, Tag, \ - TransactionTrytes, TryteString + TransactionTrytes, TryteString from iota.crypto.types import Digest, PrivateKey, Seed from iota.multisig import MultisigIota from iota.multisig.types import MultisigAddress @@ -36,75 +36,67 @@ # Create digest 1 of 3. # # noinspection SpellCheckingInspection -api_1 =\ - MultisigIota( - adapter = 'http://localhost:14265', +api_1 = MultisigIota( + adapter='http://localhost:14265', - seed = - Seed( + seed=Seed( b'TESTVALUE9DONTUSEINPRODUCTION99999XKMYQP' b'OIFGQSMIIWCQVMBSOKZASRQOFSIUSSHNDKVL9PJVS', - ), - ) + ), +) -gd_result =\ - api_1.get_digests( +gd_result = api_1.get_digests( # Starting key index. - index = 0, + index=0, # Number of digests to generate. - count = 1, + count=1, # Security level of the resulting digests. # Must be a value between 1 (faster) and 3 (more secure). - security_level = 3, - ) + security_level=3, +) # ``get_digests`` returns a dict which contains 1 or more digests, # depending on what value we used for ``count``. -digest_1 = gd_result['digests'][0] # type: Digest +digest_1 = gd_result['digests'][0] # type: Digest ## # Create digest 2 of 3. # # noinspection SpellCheckingInspection -api_2 =\ - MultisigIota( - adapter = 'http://localhost:14265', +api_2 = MultisigIota( + adapter='http://localhost:14265', - seed = - Seed( + seed=Seed( b'TESTVALUE9DONTUSEINPRODUCTION99999DDWDKI' b'FFBZVQHHINYDWRSMGGPZUERNLEAYMLFPHRXEWRNST', - ), - ) + ), +) # You can use any starting index that you want. # For maximum security, each index should be used only once. gd_result = api_2.get_digests(index=42, count=1, security_level=3) -digest_2 = gd_result['digests'][0] # type: Digest +digest_2 = gd_result['digests'][0] # type: Digest ## # Create digest 3 of 3. # # noinspection SpellCheckingInspection -api_3 =\ - MultisigIota( - adapter = 'http://localhost:14265', +api_3 = MultisigIota( + adapter='http://localhost:14265', - seed = - Seed( + seed=Seed( b'TESTVALUE9DONTUSEINPRODUCTION99999JYFRTI' b'WMKVVBAIEIYZDWLUVOYTZBKPKLLUMPDF9PPFLO9KT', - ), - ) + ), +) # It is not necessary for every digest to have the same security level. gd_result = api_3.get_digests(index=8, count=1, security_level=2) -digest_3 = gd_result['digests'][0] # type: Digest - +digest_3 = gd_result['digests'][0] # type: Digest """ Step 2: Collect the digests and create a multisig address. @@ -116,13 +108,13 @@ need to ensure that the same order is used to sign inputs! """ -cma_result =\ - api_1.create_multisig_address(digests=[digest_1, digest_2, digest_3]) +cma_result = api_1.create_multisig_address( + digests=[digest_1, digest_2, digest_3], +) # For consistency, every API command returns a dict, even if it only # has a single value. -multisig_address = cma_result['address'] # type: MultisigAddress - +multisig_address = cma_result['address'] # type: MultisigAddress """ Step 3: Prepare the bundle. @@ -137,44 +129,41 @@ """ # noinspection SpellCheckingInspection -pmt_result =\ - api_1.prepare_multisig_transfer( +pmt_result = api_1.prepare_multisig_transfer( # These are the transactions that will spend the IOTAs. # You can divide up the IOTAs to send to multiple addresses if you # want, but to keep this example focused, we will only include a # single spend transaction. - transfers = [ - ProposedTransaction( - address = - Address( - b'TESTVALUE9DONTUSEINPRODUCTION99999NDGYBC' - b'QZJFGGWZ9GBQFKDOLWMVILARZRHJMSYFZETZTHTZR', - ), - - value = 42, - - # If you'd like, you may include an optional tag and/or - # message. - tag = Tag(b'KITTEHS'), - message = TryteString.from_string('thanx fur cheezburgers'), - ), + transfers=[ + ProposedTransaction( + address=Address( + b'TESTVALUE9DONTUSEINPRODUCTION99999NDGYBC' + b'QZJFGGWZ9GBQFKDOLWMVILARZRHJMSYFZETZTHTZR', + ), + + value=42, + + # If you'd like, you may include an optional tag and/or + # message. + tag=Tag(b'KITTEHS'), + message=TryteString.from_string('thanx fur cheezburgers'), + ), ], # Specify our multisig address as the input for the spend # transaction(s). # Note that PyOTA currently only allows one multisig input per - # bundle (although the protocol does not impose a limit). - multisig_input = multisig_address, + # bundle (although the protocol itself does not impose a limit). + multisig_input=multisig_address, # If there will be change from this transaction, you MUST specify # the change address! Unlike regular transfers, multisig transfers - # will NOT automatically generate a change address; that wouldn't - # be fair to the other participants! - change_address = None, - ) - -prepared_trytes = pmt_result['trytes'] # type: List[TransactionTrytes] + # will NOT automatically generate a change address; that wouldn't be + # fair to the other participants! + change_address=None, +) +prepared_trytes = pmt_result['trytes'] # type: List[TransactionTrytes] """ Step 4: Sign the inputs. @@ -205,15 +194,15 @@ # ``get_digests`` method, in order to generate the correct value to # sign the input! gpk_result = api_1.get_private_keys(index=0, count=1, security_level=3) -private_key_1 = gpk_result['keys'][0] # type: PrivateKey +private_key_1 = gpk_result['keys'][0] # type: PrivateKey private_key_1.sign_input_transactions(bundle, 1) gpk_result = api_2.get_private_keys(index=42, count=1, security_level=3) -private_key_2 = gpk_result['keys'][0] # type: PrivateKey +private_key_2 = gpk_result['keys'][0] # type: PrivateKey private_key_2.sign_input_transactions(bundle, 4) gpk_result = api_3.get_private_keys(index=8, count=1, security_level=2) -private_key_3 = gpk_result['keys'][0] # type: PrivateKey +private_key_3 = gpk_result['keys'][0] # type: PrivateKey private_key_3.sign_input_transactions(bundle, 7) # Once we've applied the signatures, convert the Bundle back into tryte @@ -229,11 +218,11 @@ """ validator = BundleValidator(bundle) if not validator.is_valid(): - raise ValueError( - 'Bundle failed validation:\n{errors}'.format( - errors = '\n'.join((' - ' + e) for e in validator.errors), - ), - ) + raise ValueError( + 'Bundle failed validation:\n{errors}'.format( + errors='\n'.join((' - ' + e) for e in validator.errors), + ), + ) """ Step 5: Broadcast the bundle. diff --git a/examples/routingwrapper_pow.py b/examples/routingwrapper_pow.py index 758f41d..d9f75ee 100644 --- a/examples/routingwrapper_pow.py +++ b/examples/routingwrapper_pow.py @@ -1,43 +1,44 @@ # 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 +Simple example using the RoutingWrapper to route API requests to +different nodes. + +References: + +- https://pyota.readthedocs.io/en/develop/adapters.html#routingwrapper """ -from iota import * +from iota import Address, Iota, ProposedTransaction, 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'), +# Send PoW requests to local node. +# All other requests go to light wallet node. +router = RoutingWrapper('http://service.iotasupport.com:14265') +router.add_route('attachToTangle', 'http://localhost:14265') - # Seed used for cryptographic functions. - seed = b'SEED9GOES9HERE' - ) +api = Iota(router, seed=b'SEED9GOES9HERE') # Example of sending a transfer using the adapter. +# noinspection SpellCheckingInspection bundle = api.send_transfer( - depth = 100, - transfers = [ - ProposedTransaction( - # Recipient of the transfer. - address = - Address( - #b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' - #b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR' - ), + depth=100, - # Amount of IOTA to transfer. - # This value may be zero. - value = 1, + transfers=[ + ProposedTransaction( + # Recipient of the transfer. + address=Address( + # b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' + # b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR' + ), - # Optional tag to attach to the transfer. - tag = Tag(b'ADAPT'), + # Amount of IOTA to transfer. + # This value may be zero. + value=1, - # Optional message to include with the transfer. - message = TryteString.from_string('Hello!'), - ), - ], + # Optional tag to attach to the transfer. + tag=Tag(b'ADAPT'), + + # Optional message to include with the transfer. + message=TryteString.from_string('Hello!'), + ), + ], ) diff --git a/examples/sandbox.py b/examples/sandbox.py index 348834f..b4201bc 100644 --- a/examples/sandbox.py +++ b/examples/sandbox.py @@ -1,55 +1,52 @@ # coding=utf-8 from __future__ import absolute_import, division, print_function, \ - unicode_literals + unicode_literals -from iota import * +from iota import Address, Iota, ProposedTransaction, Tag, TryteString from iota.adapter.sandbox import SandboxAdapter - -# Create the API object. -iota =\ - Iota( +# Create the API client. +api = Iota( # To use sandbox mode, inject a ``SandboxAdapter``. - adapter = SandboxAdapter( - # URI of the sandbox node. - uri = 'https://sandbox.iota.org/api/v1/', + adapter=SandboxAdapter( + # URI of the sandbox node. + uri='https://sandbox.iota.org/api/v1/', - # Access token used to authenticate requests. - # Contact the node maintainer to get an access token. - auth_token = 'auth token goes here', + # Access token used to authenticate requests. + # Contact the node maintainer to get an access token. + auth_token='auth token goes here', ), # Seed used for cryptographic functions. # If null, a random seed will be generated. - seed = b'SEED9GOES9HERE', - ) + seed=b'SEED9GOES9HERE', +) # Example of sending a transfer using the sandbox. # For more information, see :py:meth:`Iota.send_transfer`. # noinspection SpellCheckingInspection -iota.send_transfer( - depth = 100, - - # One or more :py:class:`ProposedTransaction` objects to add to the - # bundle. - transfers = [ - ProposedTransaction( - # Recipient of the transfer. - address = - Address( - b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' - b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR' +api.send_transfer( + depth=100, + + # One or more :py:class:`ProposedTransaction` objects to add to the + # bundle. + transfers=[ + ProposedTransaction( + # Recipient of the transfer. + address=Address( + b'TESTVALUE9DONTUSEINPRODUCTION99999FBFFTG' + b'QFWEHEL9KCAFXBJBXGE9HID9XCOHFIDABHDG9AHDR' + ), + + # Amount of IOTA to transfer. + # This value may be zero. + 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, Tangle!'), ), - - # Amount of IOTA to transfer. - # This value may be zero. - 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, Tangle!'), - ), - ], + ], ) diff --git a/examples/send_transfer.py b/examples/send_transfer.py index 91b92b9..6d2ee8f 100644 --- a/examples/send_transfer.py +++ b/examples/send_transfer.py @@ -2,44 +2,45 @@ """ Example script that shows how to use PyOTA to send a transfer to an address. """ -from iota import * +from iota import Address, Iota, ProposedTransaction, Tag, TryteString -SEED1 = b"THESEEDOFTHEWALLETSENDINGGOESHERE999999999999999999999999999999999999999999999999" -ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = b"RECEIVINGWALLETADDRESSGOESHERE9WITHCHECKSUMANDSECURITYLEVELB999999999999999999999999999999" +SEED1 = b"THE9SEED9OF9THE9WALLET9SENDING9GOES9HERE" + +ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2 = ( + b"RECEIVING9WALLET9ADDRESS9GOES9HERE9WITH9CHECKSUM9AND9SECURITY9LEVEL9B" +) # Create the API instance. -api =\ - Iota( +api = Iota( # URI of a locally running node. 'http://localhost:14265/', # Seed used for cryptographic functions. - seed = SEED1 - ) + seed=SEED1, +) # For more information, see :py:meth:`Iota.send_transfer`. api.send_transfer( - depth = 100, - - # One or more :py:class:`ProposedTransaction` objects to add to the - # bundle. - transfers = [ - ProposedTransaction( - # Recipient of the transfer. - address = - Address( - ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2, + depth=100, + + # One or more :py:class:`ProposedTransaction` objects to add to the + # bundle. + transfers=[ + ProposedTransaction( + # Recipient of the transfer. + address=Address( + ADDRESS_WITH_CHECKSUM_SECURITY_LEVEL_2, + ), + + # Amount of IOTA to transfer. + # This value may be zero. + value=1, + + # Optional tag to attach to the transfer. + tag=Tag(b'EXAMPLE'), + + # Optional message to include with the transfer. + message=TryteString.from_string('Hello!'), ), - - # Amount of IOTA to transfer. - # This value may be zero. - value = 1, - - # Optional tag to attach to the transfer. - tag = Tag(b'EXAMPLE'), - - # Optional message to include with the transfer. - message = TryteString.from_string('Hello!'), - ), - ], + ], )