コード例 #1
0
def gen_account_bundles_list(account_idx, seed):
    # api
    api = Iota('http://localhost:14265', seed)

    # account info
    account_data = api.get_account_data()
    bundles = account_data['bundles']

    account_bundles_list = \
"""
//!
//! Account 1 Detailed transactions
//!
"""

    for i in range(0, len(bundles)):
        bundle_idx = i + 1
        bundle = bundles[i]

        for j in range(0, len(bundle.transactions)):
            trx_idx = j + 1
            trx = bundle.transactions[j]

            account_bundles_list += \
"""
static const std::string ACCOUNT_%s_BUNDLE_%s_TRX_%s_TRYTES = "%s";
""" % (account_idx, bundle_idx, trx_idx, trx.as_tryte_string())

    return account_bundles_list
コード例 #2
0
def gen_account_info(account_idx, seed, nb_addrs):
    # api connection
    api = Iota('http://localhost:14265', seed)

    # account info
    account_data = api.get_account_data(stop=nb_addrs)
    fund = account_data['balance']
    addrs = account_data['addresses']
    addrs_fund = api.getBalances(addresses=addrs)['balances']

    # generate
    account_info = \
"""
//!
//! Account %d
//!
static const std::string ACCOUNT_%d_SEED = "%s";
static const int64_t     ACCOUNT_%d_FUND = %d;
""" % (account_idx, account_idx, seed, account_idx, fund)

    for i in range(0, len(addrs)):
        addr_idx = i + 1
        account_info += \
"""
static const std::string ACCOUNT_%d_ADDRESS_%d_HASH                  = "%s";
static const std::string ACCOUNT_%d_ADDRESS_%d_HASH_WITHOUT_CHECKSUM = "%s";
static const int64_t ACCOUNT_%d_ADDRESS_%d_FUND                      = %d;
""" % (account_idx, addr_idx, addrs[i].with_valid_checksum(), account_idx, addr_idx, addrs[i], account_idx, addr_idx, addrs_fund[i])

    return account_info + '\n'
コード例 #3
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_account_data.GetAccountDataCommand.__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_account_data()

            self.assertTrue(mocked_command.called)

            self.assertEqual(response, 'You found me!')
コード例 #4
0
ファイル: lottery.py プロジェクト: sfrias/Lottery
def main():
    i=1
    print "I start playing the IOTA lottery. Good luck."

    ##Infinite look how checks the randomly created seeds.

    while i>0:
        semilla = crea_seed() 

        ## CHANGE THIS - Here you need to include a Full IOTA Node instead localhost
        ## If you want to try quickly maybe It can be a good idea to install your own 
        ## Full Node  
        api = Iota('http://*****:*****@gmail.com", "PASSWORD")
            text = msg.as_string()
            server.sendmail(fromaddr, toaddr, text)
            server.quit()

        else:
            print semilla+ ": " + str(saldo)
コード例 #5
0
        'YCXCVQDFGWUKPUABPYNMVPAQUGUHYYLMWZQWRUIDIXGTDAOJKOUGRWDJUUOWGOHMVYLTZHGEZCZHBTMT9RM9XGRJUW'
    ]
}]

for account in accounts:
    # fetch seed
    seed = account['seed']
    fund = account['fund']
    addrs = account['addresses']
    # log
    print '[%s] Start' % (seed)
    # setup iota client
    api = Iota('http://localhost:14265', seed)
    # attach each address
    for address in addrs:
        # prepare trx
        trx = ProposedTransaction(address=Address(address),
                                  message=TryteString.from_string(
                                      "MSG%s%s" % (seed[:5], address[:5])),
                                  tag=Tag("TAG%s%s" % (seed[:5], address[:5])),
                                  value=0)
        # attach
        api.send_transfer(1, [trx])
    # ensure we can get the expected amount of funding for that account now
    api_fund = api.get_account_data(0)['balance']
    if api_fund == fund:
        print '[%s] Success' % (seed)
    else:
        print '[%s] Fail: expected %d IOTA, got %d IOTA' % (seed, fund,
                                                            api_fund)
コード例 #6
0
import json
from iota import Iota
from config import SEED, NODE_URL

# Iota instance
api = Iota(NODE_URL, SEED)

# Generate new address
print(api.get_account_data())
コード例 #7
0
        # Display balance of seed stored on IOTA debit card
        elif ans == "4":

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

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

            print(
                "\nChecking IOTA debit card balance. This may take some time..."
            )

            # Get balance for the IOTA debit card seed
            card_balance = api.get_account_data(start=0, stop=None)

            balance = card_balance['balance']

            print("\nIOTA debit card balance is: " + str(balance) + " IOTA")

        # 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(
コード例 #8
0
ファイル: 04c_get_acc_data.py プロジェクト: lzpap/pyota
from iota import Iota, Seed
from pprint import pprint
import time

# Put your seed from Tutorial 4.a here
my_seed = Seed(b'YOURSEEDFROMTHEPREVIOUSTUTORIAL99999999999999999999999999999999999999999999999999')

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

# Script actually runs until it finds balance
success = False

while not success:
    print('Checking account information on the Tangle...')
    # Gather addresses, balance and bundles
    response = api.get_account_data()

    # response['balance'] is an integer!
    if response['balance']:
        print('Found the following information based on your seed:')
        pprint(response)
        success = True
    else:
        print('Zero balance found, retrying in 30 seconds...')
        time.sleep(30)
コード例 #9
0
ファイル: iotaclient.py プロジェクト: oskyk/iota-tic-tac-toe
class IotaClient(object):
    def __init__(self):
        conf = ConfigParser()
        path = os.path.join(os.path.dirname(__file__), 'config/config.txt')
        conf.read(path)
        self.iota = Iota(conf.get('IOTA', 'node'), conf.get('IOTA', 'seed'))
        self.generator = AddressGenerator(self.iota.seed)
        self.match_making_addr = self.generator.get_addresses(1)
        self.memcached = base.Client(('127.0.0.1', 11211))

    def get_addr(self, addr_index):
        try:
            addr = pickle.loads(self.memcached.get(str(addr_index) + 'addr'))
        except TypeError:
            addr = self.generator.get_addresses(int(addr_index))[0]
            self.memcached.set(str(addr_index) + 'addr', pickle.dumps(addr))
        return addr

    def send_msg(self, addr_index, msg):
        addr = self.get_addr(addr_index)
        pt = [
            ProposedTransaction(addr,
                                0,
                                message=TryteString.from_string(
                                    json.dumps(msg)))
        ]
        msg_hash = str(
            self.iota.send_transfer(
                depth=1, transfers=pt)['bundle'].transactions[0].hash)
        self.add_cached_msg(addr_index, msg, msg_hash)
        return msg_hash

    def get_msgs(self, addr_index, msg_type=None):
        msgs = self.memcached.get(str(addr_index))
        try:
            msgs = json.loads(msgs.decode())
        except (AttributeError, TypeError):
            self.memcached.set(str(addr_index), '[]', expire=300)
            msgs = self.get_iota_msgs(addr_index)
            self.memcached.set(str(addr_index), json.dumps(msgs), expire=300)
        if msg_type is not None:
            msgs = list(filter(lambda msg: msg['type'] == msg_type, msgs))
        return msgs

    def get_iota_msgs(self, addr_index):
        account_data = self.iota.get_account_data(int(addr_index))
        msgs = []
        for bundle in account_data['bundles']:
            msgs.append(json.loads(bundle.get_messages()[0]))
            msgs[-1]['tx_hash'] = str(bundle.transactions[0].hash)
        return msgs

    def add_cached_msg(self, addr_index, msg, msg_hash):
        msgs = self.get_msgs(addr_index)
        if any(msg['tx_hash'] == msg_hash for msg in msgs):
            return
        msgs.append(msg)
        msgs[-1]['tx_hash'] = msg_hash
        self.memcached.set(str(addr_index), json.dumps(msgs), expire=300)

    def save_move(self, addr_index, player, x, y):
        return self.send_msg(addr_index, {
            'type': 'move',
            'player': player,
            'x': x,
            'y': y
        })

    def get_moves(self, addr_index):
        return self.get_msgs(addr_index, msg_type='move')

    def open_match(self):
        match_id = randint(100, 1e9)
        self.memcached.set('open', str(match_id))
        return match_id

    def get_open_match(self):
        try:
            return int(self.memcached.get('open'))
        except TypeError:
            return None

    def close_match(self):
        self.memcached.delete('open')

    def get_match(self):
        match_open = self.get_open_match()
        if match_open:
            self.close_match()
            return match_open, 1
        else:
            return self.open_match(), 0
コード例 #10
0
ファイル: tangle.py プロジェクト: yillkid/light-backend
def get_account_data(seed):
    api = Iota(NODE_URL, seed)
    return api.get_account_data()
コード例 #11
0
ファイル: trashCash.py プロジェクト: TertiusN/trashCash
def get_balances():
    api = Iota(node, iota_seed)
    iotaBalance = api.get_account_data()['balance']
    return iotaBalance
コード例 #12
0
from iota import TryteString

# test data in correct format
testdata = "{\"uid\":\"E24F43FFFE44C2C6\",\"lic\": \"LB-AB-1234\",\"ts\":1606904502}"
#testdata = json.loads(testdata)

# testseed
seed = 'CVBCQHX9MUZZBEAZGOO9GYHWYBEZRMTWNXKBQHNSFETKUPHKHRGUYWLTSGXYAQEVLNI9XTQPTZAGOIUZH'

# devine that we use the devnet
api = Iota('https://nodes.devnet.iota.org:443', seed, testnet=True)

#print(api.get_new_addresses())

# check balance of account
balance = api.get_account_data()
print(balance)
#addresses = []
#addresses.append('SVCSKJPIIAOOSAAYMS9HKQVSIRVCKGOFNVQRTEXJNBFMCYFDIEWWYXBWZQDSKNJCVXCQGS9GUJLBHEAVBNS9UNPGFB')
#balances = api.get_balances(addresses, None)
#print(balances)

# address for output transaction
address = 'OCARSUKVZEZJUKSQU9RIKLANCKHDGCZGELJUUISZTAWQAUXSHHD9RJTKKM9ZMDNDZYFKEBKHEXHBPFAED'

tx = ProposedTransaction(address=Address(address),
                         value=10,
                         message=TryteString.from_unicode(testdata))

result = api.send_transfer(transfers=[tx])
print('Bundle: ')
コード例 #13
0
class Wallet:
    """docstring for Wallet"""
    def __init__(self, uri: str, seed: Optional[str] = None) -> None:
        self._iota_api = Iota(uri, seed)
        self._account: _Account

    @property
    def account(self) -> _Account:
        try:
            return self._account
        except AttributeError:
            # We get an attibute error if we check this property before ever
            # calling refresh_account.
            self.refresh_account()
            return self._account

    @property
    def addresses(self) -> List[Address]:
        return self.account.addresses

    @property
    def balance(self) -> int:
        return self.account.balance

    @property
    def bundles(self) -> Dict[str, Iterable[Bundle]]:
        return {
            'confirmed': self.account.confirmed_bundles,
            'unconfirmed': self.account.unconfirmed_bundles,
            'duplicate': self.account.duplicate_bundles,
        }

    def _is_above_max_depth(self, transaction: Transaction) -> bool:
        current_millis = time.time() * 1000
        max_age = 11 * 60 * 1000  # 11 minutes
        diff = current_millis - cast(float, transaction.attachment_timestamp)
        return (0 < diff < max_age)

    def _is_promotable(self, bundle: Bundle) -> bool:
        return (self._is_above_max_depth(bundle.tail_transaction)
                and self._iota_api.helpers.is_promotable(
                    bundle.tail_transaction.hash))

    def _promote(self, bundle: Bundle) -> Bundle:
        tail_hash = bundle.tail_transaction.hash
        response = self._iota_api.get_latest_inclusion([tail_hash])
        if response['states'][tail_hash]:
            raise BundleAlreadyPromoted()

        response = self._iota_api.promote_transaction(transaction=tail_hash,
                                                      depth=DEPTH)
        return response['bundle']

    def _reattach(self, bundle: Bundle) -> Bundle:
        response = self._iota_api.replay_bundle(
            bundle.tail_transaction.hash,
            DEPTH,
        )
        return Bundle.from_tryte_strings(response['trytes'])

    def create_new_address(self) -> Address:
        response = self._iota_api.get_new_addresses(count=None)
        address = response['addresses'][0]

        # Attach the address
        self._iota_api.send_transfer(
            depth=DEPTH,
            transfers=[ProposedTransaction(address, value=0)],
        )

        return address

    def refresh_account(self) -> None:
        response = self._iota_api.get_account_data(inclusion_states=True)
        addresses = response['addresses']
        balance = response['balance']
        bundles = response['bundles']

        self._account = _Account(addresses, balance, bundles)

    def retry_unconfirmed_bundles(self, *bundles: Bundle) -> None:
        if len(bundles) == 0:
            bundles = tuple(self.bundles['unconfirmed'])
        for bundle in bundles:
            print(f'Retrying bundle: {bundle.hash}')
            if not self._is_promotable(bundle):
                bundle = self._reattach(bundle)
                while True:
                    time.sleep(2)
                    if self._is_promotable(bundle):
                        break
            for attempt in range(5):
                try:
                    promote_bundle = self._promote(bundle)
                except BundleAlreadyPromoted:
                    break
                else:
                    print(
                        f'Promotion attempt ({attempt}): Bundle {promote_bundle.hash}'
                    )

    def send(self, address: str, value: int) -> None:
        print(f'Sending {value} iota to {address}...')
        response = self._iota_api.send_transfer(
            depth=DEPTH,
            transfers=[ProposedTransaction(Address(address), value=value)])
        bundle = response['bundle']
        print(f'Iota sent! Bundle hash: {bundle.hash}')
コード例 #14
0
# Clear any fingerprints currently stored in the reader
f.clearDatabase()

# Get seed where fingerprints are stored
MySeed = raw_input("\nWrite or paste seed here: ")

# Define full node to be used when retrieving fingerprints from the tangle
iotaNode = "https://nodes.thetangle.org:443"

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

print("\nRetrieving fingerprint characteristics from the tangle..")

# Get seed account data from the tangle
accdata = api.get_account_data(start=0, stop=None)

print("\nUploading fingerprint characteristics to the reader..")

# Get all bundles related to the seed
bundles = accdata['bundles']

# Define bundle counter
i = 0

# For each bundle...
for bundle in bundles:

    # Get Bundle message
    msg = bundle.get_messages()
コード例 #15
0
from iota.crypto.types import Seed
from iota import Iota
import json, sys

with open('config.json', 'r') as f:
    data = json.load(f)
    url = data['url']

my_seed = 'GVCLZGQGVIFAFFHIFPFAYWJQLRYHNNUBKNNXIAPHMLOSIAWQTEZUALGAEMGGZRHVBKFHOQUMRZFTUNTH9'

if len(sys.argv) == 2:
    my_seed = sys.argv[1]

api = Iota(adapter=url, seed=my_seed)

acount_data = api.get_account_data(start=0)
print(acount_data)
コード例 #16
0
except InvalidUri:
    print('Invalid adapter: %s' % args['--adapter'], file=sys.stderr)
    sys.exit(-1)
except ValueError as e:
    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']: