Exemplo n.º 1
0
def addressGenerator(seed):
    api = Iota(
        iotaNode, seed
    )  # The iota nodes IP address must always be supplied, even if it actually isn't used in this case.
    gna_result = api.get_new_addresses(
        count=numberOfAddresses
    )  # This is the function to generate the address.
    addresses = gna_result['addresses']
    i = 0  #int for number of addresses
    #print("Checking seed: " + seed)
    while i < numberOfAddresses:
        address = [addresses[i]]
        #print("   checking address : " + str(address[0]))
        i += 1
        if address[
                0] == known_recieving_value:  # If the address is equal to the recieving address then.. (Address without checksum)
            print("Bruteforcer Finished")
            print("The seed is: " + seed)
            file = open("seed.txt", "w")  #Open file.
            file.write("Bingo. The seed is: " +
                       seed)  #print out bingo and the correct seed.
            file.close()  #Close the file to save changes.
            #if it finds the correct address stop the program.
    increment(
        seed
    )  #increase counter by 1 and check if seed needs to be saved into log.
def addressGenerator(seed, iota_node, n_addresses):
    api = Iota(iota_node, seed)
    gna_result = api.get_new_addresses(
        count=n_addresses
    )  # This is the actual function to generate the addresses
    addresses = gna_result['addresses']
    total = 0
    i = 0
    founds = []

    while i < n_addresses:
        address = [addresses[i]]
        balance = addressBalance(address, iota_node)
        print("Address " + str(address[0]) + " has a balance of: " +
              str(balance))
        total += balance
        i += 1
        if balance:
            founds.append(address)

    if total > 0:
        print("The above addresses have a total balance of " + str(total) +
              " Iota tokens!!!")
        return founds
    else:
        print("No balance on those addresses!")
        return False
Exemplo n.º 3
0
    def load_wallet(self, wallet):
        config = configparser.ConfigParser()
        config.read(wallet)
        iota_seed_e = config['wallet']['iotaSeed']
        iota_seed = self.key_f.decrypt(
            iota_seed_e.encode('utf-8')).decode('utf-8')

        api = Iota(self.node, iota_seed)
        inputs = api.get_inputs()

        addresses = inputs['inputs']
        config['wallet']['index'] = str(len(addresses))

        if len(addresses) == 0:
            print("No address found. Generating...")
            gna_result = api.get_new_addresses(count=1)
            addresses = gna_result['addresses']

        config['wallet']['activeAddress'] = str(addresses[-1])
        config['wallet']['totalBalance'] = str(inputs['totalBalance'])

        for i, address in enumerate(addresses):
            config['addresses']['Address ' + str(i)] = str(address)

        with open(wallet, 'w') as configfile:
            config.write(configfile)

        return api, inputs
Exemplo n.º 4
0
class Car:
    def __init__(self, seed):
        self.api = Iota('https://iotanode.us:443', seed)

    def getAddress(self, count=1):
        new_address = self.api.get_new_addresses(count=count)
        print(new_address)
        return new_address

    def sendiota(self, address, amount):
        self.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,
                    ),
                    # Amount of IOTA to transfer.
                    # This value may be zero.
                    value=amount,
                    # Optional tag to attach to the transfer.
                    tag=Tag(b'EXAMPLEK'),
                    # Optional message to include with the transfer.
                    message=TryteString.from_string('Hello!'),
                ),
            ],
        )

    def __getAPI(self):
        return self.api
Exemplo n.º 5
0
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
def checkAddresses(seed):
    # use IOTA api to get first n addresses of the seed
    api = Iota(iotaNode, seed)
    apiAdresses = api.get_new_addresses(count=numberOfAddresses)
    addresses = apiAdresses['addresses']

    # check if one of the addresses matches the public known transaction address
    i = 0
    while i < numberOfAddresses:
        address = str([addresses[i]][0])
        if (publicTransactionAddress.startswith(address)):
            if (numberOfAddresses == 1):
                print(
                    "\nAs we only checked one (i.e. the first) address of a seed, there can only be one result."
                )
                print(
                    "Please try to login with the following seed and check your balance:\n\n"
                    + seed + "\n")
                printDonation()
                sys.exit()
            else:
                print("\nTry to login with this seed (others may follow): " +
                      seed + "\n")
                seedCandidates.append(seed)
        i += 1
Exemplo n.º 7
0
def get_avl_address():

    api = Iota(node, b'NO9SEED9REQUIRED999999999999999999999999999')

    # Find the first unused address, starting with index 0:
    avl_address = api.get_new_addresses(index=0, count=None)

    address = bytes(avl_address['addresses'][0])
    return address
Exemplo n.º 8
0
def getNewAddress(seed):
    # 获取IOTA api函数接口
    api = Iota(ip, seed=seed, testnet=True)
    # 设置信息传输安全等级
    security_level = os.getenv('SECURITY_LEVEL', 1)
    # 获取可用的交易地址
    address = api.get_new_addresses(
        index=0, count=1, security_level=security_level)['addresses'][0]
    return str(address)
Exemplo n.º 9
0
    def get_addr(self):
        """Get an iota address"""
        if self.CONFIG['index'] is None:
            self.CONFIG['index'] = 0

        from iota import Iota
        try:
            api = Iota(self.CONFIG['node'], self.CONFIG['seed'], 'utf-8')
            d = api.get_new_addresses(index=self.CONFIG['index'], count=1)
            self.CONFIG['addr'] = str(d['addresses'][-1])
            self.debug("Address at index {}: {}".format(
                self.CONFIG['index'], self.CONFIG['addr']))
        except Exception as e:
            print(e)
            return False
        return True
Exemplo n.º 10
0
def addressGenerator():
    # Although generating addresses won't connect to the node
    api = Iota(node, seed)
    gna_result = api.get_new_addresses(index=index,
                                       count=numberOfAddresses,
                                       checksum=True)
    addresses = gna_result['addresses']
    i = 0
    sum = 0
    while i < numberOfAddresses:
        address = [addresses[i]]
        balance = addressBalance(address)
        print("Index " + str(index + i) + " address " + str(address[0]) +
              " has balance: " + str(balance))
        sum += balance
        i += 1
    print("Above addresses have total balance of " + str(sum) + " iota!")
Exemplo n.º 11
0
    def test_wireup(self):
        """
    Verify that the command is wired up correctly.

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

            api = Iota(self.adapter)

            # Don't need to call with proper args here.
            response = api.get_new_addresses('hashes')

            self.assertTrue(mocked_command.called)

            self.assertEqual(response, 'You found me!')
Exemplo n.º 12
0
def addressGenerator(seed):
    api = Iota(
        iotaNode, seed
    )  # The iota nodes IP address must always be supplied, even if it actually isn't used in this case.
    gna_result = api.get_new_addresses(
        count=numberOfAddresses
    )  # This is the actual function to generate the address.
    addresses = gna_result['addresses']
    total = 0
    i = 0
    while i < numberOfAddresses:
        address = [addresses[i]]
        balance = addressBalance(address)
        print("Address " + str(address[0]) + " has a balance of: " +
              str(balance))
        total += balance
        i += 1
    if total > 0:
        print("The above addresses have a total balance of " + str(total) +
              " Iota tokens!!!")
    else:
        print("No balance on those addresses!")
Exemplo n.º 13
0
def main(uri, index, count):
    # type: (Text, 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)

    # 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('')

    # Here's where all the magic happens!
    for addy in api.get_new_addresses(index, count):
        print(binary_type(addy).decode('ascii'))

    print('')
Exemplo n.º 14
0
 def generateAddress(self, seed, index):
     api_seed = Iota(iotaNodeUrl, seed)
     # Here index is used to identify the address(这里index用来标识是第几个地址)
     addresses = api_seed.get_new_addresses(index=index, count=1, security_level=2, checksum=True)
     address = addresses['addresses'][0]
     print('\nThe first available address for your seed: %s' % address)
Exemplo n.º 15
0
# coding=utf-8
from iota import Iota
from config_iota_wallet import NODE_URL, SEED

api = Iota(NODE_URL, SEED)
dict_addr = api.get_new_addresses(count=None, index=None)

print("New address: " + str(dict_addr['addresses']))
Exemplo n.º 16
0
from iota import Iota, Seed

# Generate a random seed, or use one you already have (for the devnet)
print('Generating a random seed...')
my_seed = Seed.random()
# my_seed = Seed(b'MYCUSTOMSEED')
print('Your seed is: ' + str(my_seed))

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

print('Generating the first unused address...')
# Generate the first unused address from the seed
response = api.get_new_addresses()

addy = response['addresses'][0]

print('Your new address is: ' + str(addy))
print('Go to https://faucet.devnet.iota.org/ and enter you address to receive free devnet tokens.')
Exemplo n.º 17
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)
Exemplo n.º 18
0
from iota import Iota
from iota import ProposedTransaction
from iota import Address
from iota import Tag
from iota import TryteString
from iota.crypto.types import Seed

node1 = 'https://nodes.comnet.thetangle.org:443'
node2 = 'http://localhost:14265'

seed = Seed.random()
print('Your seed is', seed)

api = Iota(node2, seed, testnet=True)
security_level = 2
address = api.get_new_addresses(index=0,
                                count=1,
                                security_level=security_level)['addresses'][0]

is_spent = api.were_addresses_spent_from([address])['states'][0]

if is_spent:
    print('Address %s is spent!' % address)
else:
    print('Your address is: %s' % address)
Exemplo n.º 19
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
Exemplo n.º 20
0
class IotaControl:

    # init and set startup vars
    def __init__(self, config, hjson, index):

        self.api = Iota(config.getNodeUrl(), config.getSeed())
        self.secLvl = config.getSecLvl()
        self.checksum = config.getChecksum()
        self.jspath = config.getJsonPath()
        self.json = hjson
        self.index = index

    # generate new address, check if it was spent from
    def generate_new_address(self):

        if os.path.isfile(self.jspath):
            self.index = self.json.get_last_index()
        else:
            self.index = 0

        new_add = self.api.get_new_addresses(index=self.index, count=1, security_level=self.secLvl,
                                             checksum=self.checksum)

        print('generating address with index: ', self.index)
        self.new_address = str(new_add['addresses'][0])

        self.check_spent()

    # check if address has spent before
    def check_spent(self):

        # get rid of the checksum to pass to were_addresses_spent_from
        self.address_to_check = [self.new_address[0:81]]

        sp = self.api.were_addresses_spent_from(self.address_to_check)
        self.spent = sp['states'][0]
        print('address has spent before: ', self.spent)

        self.write_to_file()

    # write to file
    def write_to_file(self):

        no = self.index
        spent = self.spent
        address = self.new_address

        if os.path.isfile(self.jspath):
            self.json.write_json(no, spent, address)
            self.index += 1
        else:
            self.json.construct_json(no, spent, address)
            self.index += 1

        if spent is True:

            self.index += 1
            self.generate_new_address()

        else:
            pass
Exemplo n.º 21
0
        # Display next unused address of seed stored on IOTA debit card
        elif ans == "5":

            # Get seed from IOTA debit card
            seed = read_seed()

            # Create an IOTA object
            api = Iota(iotaNode, seed)

            print(
                "\nGetting next available IOTA address. This may take some time..."
            )

            # Get next available address without any transactions
            result = api.get_new_addresses(index=0,
                                           count=None,
                                           security_level=2)

            addresses = result['addresses']

            addr = str(addresses[0].with_valid_checksum())

            print(
                "\nUse the following IOTA address when transfering new funds to IOTA debit card:"
            )
            print(addr)

        # Stop reading/writing to RFID tag
        MIFAREReader.MFRC522_StopCrypto1()

        # Make sure to stop reading for cards
"""
from iota import Address, ProposedTransaction, Tag, Transaction, Iota, TryteString, json
import pandas as pd
import json
import time
import iota
import threading

##### IOTA SETTINGS #####

SEED = 'PUTYOURSEEDHERE99999999999999999999999999999999999999999999999999'
api = Iota('http://173.212.218.8:14265/',
           SEED)  # POW node, SEED IS NEEDED TO DO THE SIGNING
tag = iota.Tag('PUTYOURTAGHERE')  # Tag for in the message.
address = api.get_new_addresses(
    0, 1)['addresses']  # Generates a list of 1 address

##### PANDAS DATA FRAME SET #####

data_frame = pd.DataFrame()

######


def send_to_iota(sensor_data, message):
    global data_frame

    data_decoded = sensor_data
    df1 = pd.DataFrame([data_decoded], columns=data_decoded.keys())
    data_frame = pd.concat([data_frame, df1])
    print(data_frame)
Exemplo n.º 23
0
password = getpass('Please supply a password for encryption:')

print('Encrypting data...')
# Encrypt data
# Note, that in Python 3, encrypt returns 'bytes'
cipher = encrypt(password, json_data)

# Encode to base64, output contains only ASCII chars
b64_cipher = b64encode(cipher)

print('Constructing transaction locally...')
# Convert to trytes
trytes_encrypted_data = TryteString.from_bytes(b64_cipher)

# Generate an address from your seed to post the transfer to
my_address = api.get_new_addresses(index=42)['addresses'][0]

# Tag is optional here
my_tag = Tag(b'CONFIDENTIALINFORMATION')

# Prepare a transaction object
tx = ProposedTransaction(
    address=my_address,
    value=0,
    tag=my_tag,
    message=trytes_encrypted_data,
)

print('Sending transfer...')
# Send the transaction to the network
response = api.send_transfer([tx])
Exemplo n.º 24
0
def generate_new_address(seed):
    # Iota instance
    api = Iota(NODE_URL, seed)
    address = api.get_new_addresses(count=None, index=None)

    return str(address["addresses"][0])
Exemplo n.º 25
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)
Exemplo n.º 26
0
def genAddrFromSeed(seed, num):
    api = Iota('http://localhost:14265', seed)
    gna_result = api.get_new_addresses(
        count=num)  # generates 1 address, starting with index 0
    result = gna_result['addresses']
    return (result)
Exemplo n.º 27
0
class IotaClient(object):
    """Python IOTA client wrapper"""
    def __init__(self, seed, provider, depth=5, min_weight_magnitude=14):
        self._api = Iota(provider, seed)
        self._depth = depth
        self._min_weight_magnitude = min_weight_magnitude
        self.address = self._get_address()

    @staticmethod
    def _compose_transaction(address, msg, tag, val):
        txn = \
            ProposedTransaction(
                address=Address(address),
                message=TryteString.from_unicode(msg),
                tag=Tag(tag),
                value=val
            )
        return txn

    def _get_address(self):
        address = self._api.get_new_addresses(0, 1)['addresses'][0]
        return str(address)

    def get_transactions_from_address(self, address):
        """
        Gets transaction object from address sorted on timestamp (from latest
        to earliest).

        :param address:
           Address to fetch transaction from

        """
        transactions = self._api.find_transactions(addresses=[address])
        transaction_hashes = transactions['hashes']

        if not transaction_hashes:
            raise ValueError("No transactions on address")

        trytes = self._api.get_trytes(transaction_hashes)['trytes']

        trytes_and_hashes = list(zip(trytes, transaction_hashes))

        transactions = list(
            map(lambda pair: Transaction.from_tryte_string(pair[0], pair[1]),
                trytes_and_hashes))

        sorted_transactions = sorted(transactions,
                                     key=lambda t: t.timestamp,
                                     reverse=True)

        return sorted_transactions

    def get_messages_from_address(self, address):
        """
        Gets messages (sorted by timestamp).
        Returns a dict with 'json_message' and 'timestamp keys'

        :param address:
           Address to fetch messages from

        """
        sorted_transactions = self.get_transactions_from_address(address)
        messages = list(
            map(
                lambda t: {
                    'json_message':
                    json.loads(Fragment.as_string(t.signature_message_fragment)
                               ),
                    'timestamp':
                    t.timestamp
                }, sorted_transactions))

        return messages

    @staticmethod
    def get_message(transaction):
        message = transaction['signature_message_fragment'].decode()
        json_message = json.loads(message)
        return json_message

    def send_transaction(self, address, msg, tag, val):
        txn = self._compose_transaction(Address(address), msg, tag, val)
        mwm = self._min_weight_magnitude
        depth = self._depth
        self._api.send_transfer(depth, [txn], None, None, mwm)
Exemplo n.º 28
0
class IotaCache(object):

    def __init__(self, uri=None, seed=None):
        if not uri:
            self.uri = "http://localhost:14700"
        else:
            self.uri = uri
        if not seed:
            self.seed = 'EBZYNR9YVFIOAZUPQOLRZXPPPIKRCJ9EJKVCXMYVLMNOCCOPYPJKCWUZNLJZZZZWTMVQUXZFYLVLZXJ9Q'
        else:
            self.seed = seed
        self.api = Iota(self.uri, self.seed, testnet=True)
        self.mwm = 1
        self.depth = 15

    def cache_txn_in_tangle_sdk(self, ipfs_addr, tag):
        api_response = self.api.get_new_addresses()
        addy = api_response['addresses'][0]
        address = binary_type(addy).decode('ascii')

        result = self.api.send_transfer(
            depth=self.depth,
            transfers=[
                ProposedTransaction(
                    address=Address(address),
                    value=0,
                    tag=Tag(tag),
                    message=TryteString.from_string(ipfs_addr),
                ),
            ],
            min_weight_magnitude=self.mwm,
        )
        return result

    def cache_txn_in_tangle_simple(self, data, tag):
        address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX"
        txns = self.api.get_transactions_to_approve(self.depth)
        tr = self.api.get_trytes([txns[u'branchTransaction']])
        txn = Transaction.from_tryte_string(tr[u'trytes'][0], txns[u'branchTransaction'])
        txn.trunk_transaction_hash = txns[u'trunkTransaction']
        txn.branch_transaction_hash = txns[u'branchTransaction']
        txn.tag = Tag(TryteString.from_string(tag))
        txn.signature_message_fragment = Fragment(TryteString.from_bytes(data))
        attach_trytes = attachToTangle(self.uri, txns[u'trunkTransaction'].__str__(), txns[u'branchTransaction'].__str__(), 1, txn.as_tryte_string().__str__())
        res = self.api.broadcast_and_store(attach_trytes[u'trytes'])
        return res

    def cache_txn_in_tangle_message(self, data, tag):
        #address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX"
        address = "14dD6ygPi5WXdwwBTt1FBZK3aD8uDem1FY"
        res = storeMessage(self.uri, address, data, tag)
        return res

    def get_balance(self, coin_type, account):
        address = "JVSVAFSXWHUIZPFDLORNDMASGNXWFGZFMXGLCJQGFWFEZWWOA9KYSPHCLZHFBCOHMNCCBAGNACPIGHVYX"
        res = getBalance(self.uri, address, coin_type, account)
        return res

    def get_approved_txns(self, tag):
        ret = []
        transactions = self.api.find_transactions(None, None, [tag], None)
        if len(transactions['hashes']) == 0:
            return ret
        tips = self.api.get_tips()
        states = self.api.get_inclusion_states(transactions['hashes'], tips['hashes'])
        i = 0
        for txn in transactions['hashes']:
            if states['states'][i] is True:
                ret.append(txn)
        return ret

    def get_non_consumed_txns(self, tag):
        ret = []
        txn_hashes_all = self.get_approved_txns(tag)
        if len(txn_hashes_all) == 0:
            return ret
        txn_trytes_all = self.api.get_trytes(txn_hashes_all)
        consumedSet = []
        txn_hashes_consumed = self.api.find_transactions(None, None, [tag+b"CONSUMED"], None)
        if len(txn_hashes_consumed['hashes']) != 0:
            txn_trytes_consumed = self.api.get_trytes(txn_hashes_consumed['hashes'])
            i=0
            for txnTrytes in txn_trytes_consumed['trytes']:
                txn = Transaction.from_tryte_string(txnTrytes, txn_hashes_consumed['hashes'][i])
                i+=1
                consumedSet.append(txn.signature_message_fragment)
        i=0
        for txnTrytes in txn_trytes_all['trytes']:
            txn = Transaction.from_tryte_string(txnTrytes, txn_hashes_all[i])
            i+=1
            if txn.signature_message_fragment not in consumedSet:
                msgTryte = txn.signature_message_fragment.decode()
                ret.append(msgTryte)

        return ret

    def set_txn_as_synced(self, ipfs_addr, tag):
        result = self.cache_txn_in_tangle_sdk(ipfs_addr, tag+b"CONSUMED")
        return result

    def add_neighbors(self, uris):
        res = addNeighbors(self.uri, uris)
        return res

    def get_block_content(self, hashes):
        res = getBlockContent(self.uri, hashes)
        return res

    def get_dag(self, dag_type):
        res = getDAG(self.uri, dag_type)
        return res

    def get_utxo(self, dag_type):
        res = getUTXO(self.uri, dag_type)
        return res

    def get_total_order(self):
        res = getTotalOrder(self.uri)
        return res
Exemplo n.º 29
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)
Exemplo n.º 30
0
import datetime
from operator import itemgetter

from iota import Iota, ProposedTransaction, Address, TryteString, Tag, Transaction
from iota.crypto.addresses import AddressGenerator
from iota.commands.extended.utils import get_bundles_from_transaction_hashes
import iota.commands.extended.get_latest_inclusion
from iota.json import JsonEncoder


# Takes a address (81 Characters) and converts it to an address with checksum (90 Characters)
def address_checksum(address):
    bytes_address = bytes(address)
    addy = Address(bytes_address)
    address = str(addy.with_valid_checksum())
    return address


#bitfinex uses cloudflare which blocks many requests; blocking may get triggered at address pregeneration
#uri = "http://iota.bitfinex.com/"
uri = "http://node01.iotatoken.nl:14265/"
index = int(sys.argv[2])
count = None
seed = sys.argv[1]
seed = seed.encode('ascii')
api = Iota(uri, seed)
api_response = api.get_new_addresses(index, count)
for addy in api_response['addresses']:
    print(address_checksum(binary_type(addy).decode('ascii')))
    #print(binary_type(addy).decode('ascii'))