コード例 #1
0
ファイル: balance.py プロジェクト: ethernity-live/IOTAFaucet
class balance():
    def __init__(self):
        self.seed = seed
        self.IOTA_connection = Iota(IOTA_node_URI_conf, seed=seed)
        self.mysql_connection = MySQLdb.Connection(host=mysql_conf_hostname,
                                                   user=mysql_conf_user,
                                                   passwd=mysql_conf_passwd,
                                                   db=mysql_conf_db)
        self.cursor = self.mysql_connection.cursor()
        self.cursor.execute('select trancount from tranCount')
        self.trancount = int(self.cursor.fetchone()[0])
        addresses = self.getAddresses(addressCount=self.trancount)
        balance = self.getBalance(addresses)
        iota_to_be_delivered = balance * int(percentage_conf) / 100
        print 'balance is: ', balance
        print 'percentage for Faucet: ', percentage_conf
        print 'iota to be delivered: ', iota_to_be_delivered

    #Get balances for a list of addresses
    def getBalance(self, addresses):
        balances = self.IOTA_connection.get_balances(addresses)
        balance = sum(balances['balances'])
        return balance

    def getAddresses(self, addressCount):
        addresses = self.IOTA_connection.get_new_addresses(
            count=self.trancount)
        addresses_aux = [str(address) for address in addresses['addresses']]
        #print len(addresses_aux)
        return addresses_aux
コード例 #2
0
def address_balance(iota_node, address):
    """
    Sends a request to the IOTA node and gets the current confirmed balance

    :param iota_node:
    :param address:
    :return:
    """
    api = Iota(iota_node)
    gna_result = api.get_balances([address])
    balance = gna_result['balances']
    return balance[0]
コード例 #3
0
def check_balances(config, addresses, old_balances, first_run=False):
    config_uri = config.get('main', 'uri')
    report_body = ''
    txtmsg = ''
    api = Iota(config_uri)
    response = None

    try:
        print('Connecting to tangle via {uri}.'.format(uri=config_uri))
        response = api.get_balances(addresses)
    except ConnectionError as e:
        print('{uri} is not responding.'.format(uri=config_uri))
        print(e)
    except BadApiResponse as e:
        print('{uri} is not responding properly.'.format(uri=config_uri))
        print(e)

    if response is None:
        exit(0)

    a = 0
    change_detected = False
    for addy in addresses:
        obaa = old_balances[addy.address]
        rba = response['balances'][a]
        if obaa != rba and not first_run:
            change_detected = True
            report_body = ('%s The balance at address %s has changed'
                           ' from %i to %i.\n' %
                           (report_body, addy.address, obaa, rba))
            txtmsg = ('%s Balance at %s changed from %i to %i.\n' %
                      (txtmsg, addy.address[0:8], obaa, rba))
        elif not first_run:
            report_body = report_body + 'No changes detected.'
        elif first_run:
            report_body = report_body + 'Address: %s Balance: %i\n' % (
                addy.address, rba)
        old_balances[addy.address] = rba
        a += 1

    if config.getboolean('twilio', 'active') and change_detected:
        twilio_alert(config, txtmsg)

    if config.getboolean('email', 'active') and change_detected:
        email_alert(config, report_body)

    if config.getboolean('beep', 'active') and change_detected:
        beep_alert()

    if config.getboolean('msgbox', 'active') and change_detected:
        msgbox_alert(report_body)

    print(report_body)
コード例 #4
0
class IOTAController():
    def __init__(self, seed):
        self.seed = seed
        self.IOTA_connection = Iota(IOTA_node_URI_conf, seed = seed)

    def MakePayment(self, members, amountToBePaid):
        total_reputation = int(sum(int(member[1]) for member in members))
        #print total_reputation, ', total_reputation'
        IOTA_per_rep_score = amountToBePaid / (total_reputation * 1.00)
        #print amountToBePaid
        for member in members:
            #print member, ', member'
            try:
                if self.isValid(member[0]):
                    #print IOTA_per_rep_score
                    IOTA_to_be_paid = int(IOTA_per_rep_score * int(member[1]))
                    print 'IOTA to be paid: ', IOTA_to_be_paid
                    #print IOTA_to_be_paid
                    #print member[0], IOTA_to_be_paid
                    self.sendTransfer(address = str(member[0]), value = IOTA_to_be_paid, depth = 100)
            except TypeError:
                continue

    def sendTransfer(self, address, value, depth = 100):
        address = str(address)
        value = int(value)
        self.IOTA_connection.send_transfer(
            depth = depth,
            transfers = [
                ProposedTransaction(
                    address = Address(address),
                    value = value,
                ),
            ],
        )

    #Get balances for a list of addresses
    def getBalance(self, addresses):
        balances = self.IOTA_connection.get_balances(addresses)
        balance = sum(balances['balances'])
        return balance

    #Check whether an address is valid
    def isValid(self, address):
        #check whether an IOTA address is valid
        try:
            Address(address)
            return True
        except ValueError, TypeError:
            return False
コード例 #5
0
ファイル: get_balances_test.py プロジェクト: watertim/iota.py
    def test_wireup(self):
        """
        Verify that the command is wired up correctly. (sync)

        The API method indeed calls the appropiate command.
        """
        with patch(
                'iota.commands.core.get_balances.GetBalancesCommand.__call__',
                MagicMock(return_value=async_return(
                    'You found me!'))) as mocked_command:

            api = Iota(self.adapter)

            response = api.get_balances('addresses')

            self.assertTrue(mocked_command.called)

            self.assertEqual(response, 'You found me!')
コード例 #6
0
    def check_balance(self):
        iota_dict = {}
        addresses = []

        for input_address in self.config_addresses:
            if len(input_address) != Hash.LEN:
                print('Address %s is not %d characters. Skipping.' %
                      (input_address, Hash.LEN))
                print('Make sure it does not include the checksum.')
                continue

            addy = Address(input_address)
            addresses.append(addy)

        if len(addresses) == 0:
            print('No valid addresses found, exiting.')
        else:
            config_uri = self.config.get('iota_wallet', 'uri')
            api = Iota(config_uri)
            response = None

            try:
                print('Connecting to tangle via {uri}.'.format(uri=config_uri))
                response = api.get_balances(addresses)
            except ConnectionError as e:
                print('{uri} is not responding.'.format(uri=config_uri))
                print(e)
            except BadApiResponse as e:
                print(
                    '{uri} is not responding properly.'.format(uri=config_uri))
                print(e)

            if response:
                iota_dict = {
                    "IOTA": {
                        address: response['balances'][i]
                        for i, address in enumerate(addresses)
                    }
                }

        return iota_dict
コード例 #7
0
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!')
コード例 #8
0
class Escrow:
    def __init__(self, node='https://nodes.thetangle.org:443', seed=None):
        #Get Seed
        if seed is None:
            self.seed = self.getSeed()
        else:
            self.seed = seed

        #Setup API
        self.api = Iota(node, self.seed)

    #Generates a seed for escrow account
    def getSeed(self):
        #If no seed, create one
        if not os.path.isfile('seed.txt'):
            path = pathlib.Path(__file__).parent.absolute()
            seed = ''.join([random.choice(LETTERS) for i in range(81)])
            open('seed.txt', 'w+').write(seed)
            logging.info("Placed new seed in seed.txt")
        return open('seed.txt').read().strip().encode('utf-8')

    #Creates an escrow holding address
    def createEscrow(self):
        try:
            self.holdingAddress = self.api.get_new_addresses(
                count=None, checksum=True)['addresses'][0]
        except iota.adapter.BadApiResponse as e:
            logging.warning("Bad response from server retrying.")
            return self.createEscrow()
        return self.holdingAddress

    #Waits for a transactions with a refund address
    def getRefundAddress(self):
        #This is the escrow address
        address = self.holdingAddress
        try:
            #Get Hashes from ledger
            txHashes = self.api.find_transactions(addresses=[
                address,
            ])['hashes']
            #If no hashes, user has not submitted an address yet.
            if len(txHashes) == 0:
                return None
            else:
                #Check messages for a valid address
                txs = self.api.get_transaction_objects(
                    txHashes)['transactions']
                for tx in txs:
                    msg = tx.signature_message_fragment.decode()
                    try:
                        self.deposit = Address(msg.strip())
                        return self.deposit
                    except:
                        pass
                logging.warning("Invalid address recieved")
        except requests.exceptions.ConnectionError as e:
            #Sometimes the public nodes will reject a request
            print("Error contacting server; retrying")
            return self.getRefundAddress()

    #Cli version of escrow
    def startCli(self, collateral, fee=0, delay=120, deposit=None):
        #Create holding address
        self.createEscrow()
        self.fee = fee
        self.collateral = collateral
        #Wait for a deposit address to be entered
        if self.requestDeposit(collateral, deposit, delay):
            while not self.checkCondition():
                sleep(3)
        self.finalizeEscrow()

    #Wait for escrow address to recieve collateral
    def requestDeposit(self, collateral, deposit=None, duration=120):
        #For CLI prompt a deposit address
        if deposit is None:
            self.deposit = input("What is the deposit address: ")
        print(
            f"You have {duration/60:.1f} min to deposit {collateral} IOTA to {self.holdingAddress}"
        )

        #Wait for escrow to recive collateral funds.
        count = 0
        while count < duration:
            time.sleep(1)
            balance = self.getBalance(self.holdingAddress)
            if balance >= collateral:
                print("Successfully deposited into escrow", balance)
                return True
        return False

    #Condition to release escrow
    def checkCondition(self):
        #Setup a check condition
        #For example RFID or some ledger condition
        return True

    #Refund user their collateral, remoing the fee
    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 getBalance(self, address):
        try:
            response = self.api.get_balances(addresses=[address])['balances']
            return response[0]
        except requests.exceptions.ConnectionError as e:
            logging.info("Error contacting server; retrying")
            return self.getBalance(self, address)

    #Record the amount of revenue recieved
    def addRevenue(self, money, filename='revenue.txt'):
        if not os.path.isfile(filename):
            open(filename, 'w+').write('0')
        current = int(open(filename).read().strip())
        current += money
        open(filename, 'w+').write(str(current))

    #Get the current amount of revenue
    def getRevenue(self, filename="revenue.txt"):
        if not os.path.isfile(filename): return 0
        return int(open(filename).read().strip())

    #Send revenue to an address
    def sendRevenue(self, outputAddress):
        revenue = self.getRevenue()
        logger.info(f"Currently have {revenue} revenue.")
        message = "Output fees from escrow."
        txs = [
            ProposedTransaction(address=Address(outputAddress),
                                value=revenue,
                                message=TryteString.from_unicode(message)),
        ]
        try:
            logger.info("Sending transfer to node.")
            bundle = self.api.send_transfer(transfers=txs)['bundle']
        except iota.adapter.BadApiResponse as e:
            print("Bad api resonse retrying")
            return self.sendRevenue(outputAddress)
        print(bundle.transactions[0].hash)
コード例 #9
0
class Iotapay:
    def __init__(self, provider, seed, address=None):
        self.seed = seed
        self.provider = provider
        self.api = Iota(self.provider, self.seed)

    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 get_balance(self, data):
        try:
            if 'address' in data:
                balance_result = self.api.get_balances([data['address']])
                balance = balance_result['balances'][0]
            else:
                gna_result = self.api.get_new_addresses(
                    index=0, count=50)  # generate 50 addresses.
                addresses = gna_result['addresses']
                balance_result = self.api.get_balances(addresses)
                balance = 0
                for i in range(len(balance_result['balances'])):
                    balance = balance + balance_result['balances'][i]
            return {
                'status': 200,
                'balance': balance,
                'message': 'Successfully Retrieved!'
            }
        except Exception as pe:
            # print('pe:', pe)
            return {
                'status': 400,
                'error': '',
                # 'balance': str(pe.context['total_balance']),
                # 'message': str(pe).split('(')[0]
            }

    def collect(self, data):
        print('send request to collect payment.')
        return

    def generate_invoice(self, data):
        print('generate invoice.')
        return
コード例 #10
0
# -*- coding: utf-8 -*-

#füge lokales Verzeichnis hinzu indem pyota installiert wurde
import sys
sys.path.append("/home/pi/.local/lib/python2.7/site-packages")

#importe Iota-Bibliothek um die API anzusprechen
from iota import Iota

import logging

#lokal gespeicherter seed
seed = "DSPOAXMVSC99IUIVJXTIBZFATVFKTCLLJYOLAGSMFJGFXAWEB9GNTQWEDVRYHKIOQF9T9IZY9IVPKTSZK"

url = "https://field.deviota.com:443"

api = Iota(url, seed)
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
api.adapter.set_logger(logger)

gna_result = api.get_new_addresses(count=20)
addresses = gna_result['addresses']
print(addresses)

print("Check Balance...")
gb_result = api.get_balances(addresses)
コード例 #11
0
class MyIOTA:
    def __init__(self, node, seed):
        self.node = node
        self.seed = seed
        self.api = False
        self._update = False
        self.transfers = []
        self._debug = False

        self.wallet = self.get_filename()

        self.addr_dict = {}

        self.min_weight_magnitude = 14

        self.api = Iota(self.node, self.seed)

        self.USED = True
        self.NOT_USED = False

    def Address(self, addr_string):
        return Address(addr_string)

    def get_addr_dict(self):
        return self.addr_dict

    def set_addr_dict(self, addr, value, used):
        self.addr_dict[addr] = (value, used)

    def s_addr(self, addr, n=3):
        s_addr = str(addr)
        l = len(s_addr)

        return s_addr[:n] + '...' + s_addr[l - n:]

    def get_filename(self):
        h = hashlib.sha256()
        h.update(self.seed)
        filename = h.hexdigest()[:20] + '.txt'

        return filename

    def init_wallet(self):
        filename = self.wallet

        # file exists
        if os.path.isfile(filename):
            filefd = open(filename, 'r+')

            self.debug(
                'Wallet file {0} exists. Opening it...'.format(filename))

            for line in filefd:
                line = line.rstrip('\n')

                addr, index, value, used = line.split(',')

                self.debug('reading from file: {0},{1},{2}'.format(
                    self.s_addr(addr, 3), value, used))

                used = used == 'True'

                addr = Address(addr, key_index=int(index), security_level=2)
                self.addr_dict[addr] = (int(index), int(value), used)

            filefd.close()
        else:
            filefd = open(filename, 'w')
            self.debug('Wallet file {0} doesnt exist. Creating it...'.format(
                filename))
            filefd.close()

    def is_empty_wallet(self):
        return len(self.addr_dict) == 0

    def get_fund_inputs(self, inputs):
        total_fund = 0

        for addr in inputs:
            index, value, used = self.addr_dict[addr]

            # TODO: abs. is this right?
            total_fund += abs(value)

        return total_fund

    def write_updates(self):
        filefd = open(self.wallet, 'w')

        self.debug('Writing (updating) wallet...')

        for addr in self.addr_dict:
            v = self.addr_dict[addr]

            line = 'Writing: {0},{1},{2},{3}\n'.format(self.s_addr(addr), v[0],
                                                       v[1], v[2])
            self.debug(line)

            filefd.write('{0},{1},{2},{3}\n'.format(addr, v[0], v[1], v[2]))

        filefd.close()

    def update_wallet(self, input_fund, inputs, change_addr):
        copy_dict = self.addr_dict.copy()

        for addr in inputs:
            v = self.addr_dict[addr]
            #self.debug('Spending {0} from input {1}'.format(self.s_addr(addr), v))

            # Negative fund and used address
            new_value = (v[0], -v[1], not v[2])

            self.debug('Updating input address {0} to: {1}'.format(
                self.s_addr(addr), new_value))

            self.addr_dict[addr] = new_value

        change_fund = self.get_fund_inputs(inputs) - input_fund

        v = self.addr_dict[change_addr]
        change_value = (v[0], change_fund, self.NOT_USED)

        self.debug('Updating change address {0} to: {1}'.format(
            self.s_addr(change_addr), change_value))

        self.addr_dict[change_addr] = change_value

        self.write_updates()

    def enable_debug(self):
        self._debug = True

    def debug(self, msg):
        if self._debug:
            print '[+] Debug: ', msg

    def get_node_info(self):
        return self.api.get_node_info()

    def make_addr_list(self, start_index, n):
        self.iota_assert(start_index >= 0 and n > 0,
                         'must be positive numbers. N should be at least 1.')

        result = self.api.get_new_addresses(index=start_index, count=n)
        addresses = result['addresses']

        for i in range(n):
            addr = addresses[i]
            value = self.get_addr_balance(addr)

            # TODO: Why always False
            self.addr_dict[addr] = (i, value, False)

        self.write_updates()

    def get_addr_balance(self, addr):
        # TODO: addr is a list with just one element
        result = self.api.get_balances([addr])

        balance = result['balances']

        return (balance[0])

    def prepare_transfer(self,
                         transfer_value,
                         dest_addr,
                         tag='DEFAULT',
                         msg='DEFAULT'):
        # TODO: verify address (checksum)
        # TODO: use mi, gi, etc

        msg = TryteString.from_string(msg)

        txn = ProposedTransaction(
            address=Address(dest_addr),
            message=msg,
            tag=Tag(tag),
            value=transfer_value,
        )

        return txn

    def find_transactions(self):
        addr_list = []
        for e in self.addr_dict.items():
            addr = e[0]

            addr_list.append(addr)

        return self.api.findTransactions(addresses=addr_list)['hashes']

    def get_bundle(self, trans):
        return self.api.getBundles(transaction=trans)

    def get_latest_inclusion(self, addrl):
        return self.api.get_latest_inclusion(hashes=addrl)

    def get_total_fund(self):
        total_fund = 0

        for addr in self.addr_dict.items():
            # key and value from dict
            k, v = addr

            index, value, used = v

            #if not used:
            total_fund += value

        return total_fund

    def get_number_of_address(self):
        return len(self.addr_dict)

    def is_all_addr_used(self):
        for addr in self.addr_dict:
            for e in self.addr_dict.items():
                addr, v = e
                index, value, used = v

                if used == False:
                    return True

    def get_more_addr(self, n=10):
        start_index = self.get_number_of_address()

        self.debug('Getting more addresses...please wait...')

        self.make_addr_list(start_index, n)

    def send_transfer(self,
                      input_fund,
                      inputs,
                      outputs,
                      change_addr,
                      savetofile=True):
        # TODO: How to send MANY transactions.
        self.debug('Sending {0} transactions, please wait...'.format(
            len(outputs)))

        self.api.send_transfer(inputs=inputs,
                               transfers=outputs,
                               depth=7,
                               change_address=change_addr,
                               min_weight_magnitude=self.min_weight_magnitude)

        self.debug('Sent.')
        if self.is_all_addr_used():
            # We do an update to wallet file here.
            self.get_more_addr(n=10)

        if savetofile:
            self.update_wallet(input_fund, inputs, change_addr)

    def get_bundles(self, hasht):
        return self.api.get_bundles(hasht)

    def get_trytes(self, hashl):
        return self.api.get_trytes(hashl)['trytes'][0]

    def get_transaction_from_trytes(self, trytes):
        txn = Transaction.from_tryte_string(trytes)

        return txn

    def get_transaction_fields(self, txn):
        #confirmed = str(txn.is_confirmed)
        timestamp = str(txn.timestamp)
        address = str(txn.address)
        value = str(txn.value)
        message = str(txn.signature_message_fragment)
        #message   = str(txn.message)
        tag = str(txn.tag)

        return (timestamp, address, value, tag, message)

    def get_info_transactions(self, transactions_hashes):
        txn_tuples = []

        for h in transactions_hashes:
            trytes = self.get_trytes([h])
            txn = self.get_transaction_from_trytes(trytes)

            # Get confirmed flag
            li_result = self.get_latest_inclusion([bytes(h)])
            confirmed_t = li_result['states'][h]

            (_, addr_t, value_t, tag_t,
             msg_t) = self.get_transaction_fields(txn)

            txn_tuples.append((confirmed_t, addr_t, value_t, tag_t, msg_t))

        return txn_tuples

    def get_any_valid_addr(self):
        #TODO: verify
        #return self.addr_dict.keys()[0]

        for e in self.addr_dict.items():
            addr, v = e
            index, value, used = v

            if not used:
                return addr

        return None

    def get_inputs(self, fund):
        # TODO: Zero fund
        fund_sum = 0
        addr_list = []
        change_addr = None

        # Zero fund transactions. We return any addr and any change_addr
        if fund == 0:
            # TODO: What if it conflicts with one another?
            addr_list.append(self.get_any_valid_addr())
            change_addr = self.get_any_valid_addr()

            return (addr_list, change_addr)

        for e in self.addr_dict.items():
            addr, v = e
            index, value, used = v

            if fund_sum < fund:
                #if value > 0 and not used:
                if value > 0 and used == self.NOT_USED:
                    fund_sum += value
                    self.debug(
                        'Found request: {0}. Found address {1} with fund {2}.'.
                        format(fund, self.s_addr(addr), value))
                    addr_list.append(addr)

        for e in self.addr_dict.items():
            addr, v = e
            index, value, used = v

            if used == self.NOT_USED and addr not in addr_list:
                change_addr = addr

                self.debug('Using {0} as change addr.'.format(
                    self.s_addr(addr)))
                break
        return (addr_list, change_addr)

        #else:
        #    # TODO
        #    self.iota_assert(True, 'No change addr available.')

    def iota_assert(self, condition, msg):
        if not condition:
            print 'Error: ', msg
            sys.exit(-1)
コード例 #12
0
from iota import Iota, Address
import time

# Put your address from Tutorial 4.a here
my_address = Address(b'YOURADDRESSFROMTHEPREVIOUSTUTORIAL')

# Declare an API object
api = Iota(adapter='https://nodes.devnet.iota.org:443', testnet=True)

# Script actually runs until you load up your address
success = False

while not success:
    print('Checking balance on the Tangle for a specific address...')
    # API method to check balance
    response = api.get_balances(addresses=[my_address])

    # response['balances'] is a list!
    if response['balances'][0]:
        print('Found the following information for address ' +
              str(my_address) + ':')
        print('Balance: ' + str(response['balances'][0]) + 'i')
        success = True
    else:
        print('Zero balance found, retrying in 30 seconds...')
        time.sleep(30)
コード例 #13
0
def addressBalance(address, iota_node):
    api = Iota(iota_node)
    gb_result = api.get_balances(address)
    balance = gb_result['balances']
    return (balance[0])
コード例 #14
0
ファイル: car.py プロジェクト: ShawnXiao105/iotanet
def address_balance(address):
    api = Iota(iota_node)
    gna_result = api.get_balances([address])
    balance = gna_result['balances']
    return balance[0]
コード例 #15
0
# IOTA address to be checked for new light funds
# IOTA addresses can be created using the IOTA Wallet
address1 = [
    Address(
        b'ZUBGJ9ZE9WKYTMNZPLUTOIVYQGVEGEJNLOU9ERSXFJIVEPVIYOAWFFNEGATOUTWNZPHVPMICJERCTNMT9SEPUMG9WD'
    )
]
address2 = [
    Address(
        b'EJVZLHIMMVMGLVGQICRBMP9OQTHDDBLFVMTHOBXWXJJTTNFCLZDFOJRXDRTW9SNR9RUNJEGSIWZJCE9PZLHYCDOMEY'
    )
]

# URL to IOTA fullnode used when checking balance
iotaNode = "https://field.carriota.com:443"
# Create an IOTA object
api = Iota(iotaNode, "")
print("Checking balance")
gb_result1 = api.get_balances(address1)
iotabalance1 = gb_result1['balances']

gb_result2 = api.get_balances(address2)
iotabalance2 = gb_result2['balances']

Balance1 = Balance(address1, iotabalance1)
Balance2 = Balance(address2, iotabalance2)

print(Balance1.address)
print(Balance2.iotabalance)
コード例 #16
0
    print('Invalid seed: %s - %s' % (args['--seed'], e.args[0]),
          file=sys.stderr)
    sys.exit(-1)

try:
    number = int(args['--number'])
except ValueError as e:
    print(e.args[0], file=sys.stderr)
    sys.exit(-1)

print('Fetching %d addresses...' % number)
addresses = api.get_account_data(0, number)['addresses']
print('Fetched addresses.')

print('Fetching balances...')
balances = api.get_balances(addresses)['balances']
print('Fetched balances.')

trim = None
total_balance = 0

for index, address, balance in zip(range(0, number), addresses, balances):
    total_balance += balance
    if trim is None and total_balance != 0:
        trim = index
    # format: [<index>] - <address><checksum>: <balance>
    if args['--list-addresses']:
        if args['--indices']:
            print('[%d] - ' % index, end='')
        if args['--checksums']:
            address = address.with_valid_checksum()