コード例 #1
0
def create_account(role):
    """ Create new account """
    RECEIVER_PRIVATE_KEY, RECEIVER_ADDRESS = account.generate_account()
    amount = 0
    algo_amount = 301000
    message = ''
    if role == 'player':
        amount = 1500
        message = 'Your account has been created with 1,500 Monopoly Money. Scan QR code.'

    elif role == 'banker':
        amount = 20000
        message = 'Your account has been created with 20,000 Monopoly Money. Scan QR code. '

    # Send 0.301 Algo to new account (for opt-in and transaction fees)
    algo_transaction(SENDER_ADDRESS, SENDER_PRIVATE_KEY, RECEIVER_ADDRESS, algo_amount)

    # Opt-in Monopoly Money Asset
    asset_transfer(RECEIVER_ADDRESS, RECEIVER_PRIVATE_KEY, RECEIVER_ADDRESS, 0, ASSET_ID)

    # Send Monopoly Money ASA
    asset_transfer(SENDER_ADDRESS, SENDER_PRIVATE_KEY, RECEIVER_ADDRESS, amount, ASSET_ID)

    # Create PNG file with QR-code which store the passphrase
    passphrase = '{{"version":"1.0", "mnemonic":"{}"}}'.format(mnemonic.from_private_key(RECEIVER_PRIVATE_KEY))
    qr_code = pyqrcode.create(passphrase)
    rnd = random.random()
    qr_file = 'static/{}{}.png'.format(RECEIVER_ADDRESS, str(rnd))
    qr_code.png(qr_file, scale=6)
    return qr_file, message
コード例 #2
0
ファイル: generateAccount.py プロジェクト: bobeu/testalgotel
def create_account(update, context):
    """
    Create new public/private key pair
    Returns the result of generating an account to user:
    :param update:
    :param context:
    :return: 1). An Algorand address, 2). A mnemonic seed phrase
    """
    update.message.reply_text("Hang on while I get you an account ...")
    time.sleep(1)
    try:
        sk, pk = account.generate_account()
        mn = mnemonic.from_private_key(sk)
        if not (pk and sk is None):
            update.message.reply_text("Account creation success.\nAddress:  {}\n\n"
                                      "Private Key:  {}\n\n"
                                      "Mnemonic:\n {}\n\n"
                                      "I do not hold or manage your keys."
                                      "".format(pk, sk, mn)
                                      )
            context.user_data['default_pk'] = pk
        update.message.reply_text('To test if your address works fine, copy your address, and visit:\n ')
        keyboard = [[InlineKeyboardButton(
            "DISPENSER", 'https://bank.testnet.algorand.network/', callback_data='1')]]

        dispenser = InlineKeyboardMarkup(keyboard)

        update.message.reply_text('the dispenser to get some Algos\nSession ended.'
                                  'Click /start to begin.', reply_markup=dispenser)
    except Exception as e:
        update.message.reply_text('Account creation error.')
        return e
コード例 #3
0
def generate_new_account():
    """
	Generate a new Algorand account and print the public address
	and private key mnemonic.
	"""
    private_key, public_address = account.generate_account()
    passphrase = mnemonic.from_private_key(private_key)
    print("Address: {}\nPassphrase: \"{}\"".format(public_address, passphrase))
コード例 #4
0
 def generateBankerAddr(self, ref_number):
     if ref_number in self.refNumber:
         sk, accountIdentifier = account.generate_account()
         seedPhrase = mnemonic.from_private_key(sk)
         self.members.append(accountIdentifier)  # Remembers bankers identifier
         return (seedPhrase, accountIdentifier)
     else:
         print("You're not recognized")
コード例 #5
0
def setup_cmo():
    private_key, account = account_algosdk.generate_account()
    # passphrase1 = "faint fog unfair treat enemy disagree host merit bulb lizard client proof aspect cruise vital lion gate victory planet grace weird food phrase absent marriage"
    # private_key = mnemonic.to_private_key(passphrase1)
    # account = account_algosdk.address_from_private_key(private_key)
    print("CMO address: {}".format(account))
    print("CMO passphrase: {}".format(mnemonic.from_private_key(private_key)))
    return  account, private_key
コード例 #6
0
ファイル: wallet.py プロジェクト: rexcheng1997/MUGO
def create_wallet():
    """
    Creates an Algorand wallet and returns the mnemonic of the new wallet.
    @returns a string of the 25-word passphrase
    """
    private_key, account_address = account.generate_account()
    passphrase = mnemonic.from_private_key(private_key)
    return passphrase
コード例 #7
0
    def __repr__(self) -> str:
        """
        Returns all information about the wallet in a string

        Returns:
            str
        """
        return WALLET_REPR.substitute(private_key=from_private_key(self.private_key),
                                      public_key=self.public_key,
                                      balance=self.balance,
                                      qr_code_link=self.qrcode)
コード例 #8
0
def generate_algorand_keypair():
    print("## START keypair generator ##\n")

    private_key, address = account.generate_account()
    print("New address: {}".format(address))
    print("New passphrase: {}".format(mnemonic.from_private_key(private_key)) +
          "\n")

    print("# END keypair generator #\n")

    return (private_key, address)
コード例 #9
0
def generate_new_account():
    """
    Generate a new Algorand account and print the public address
    and private key mnemonic.
    """
    private_key, public_address = account.generate_account()
    passphrase = mnemonic.from_private_key(private_key)
    return json.dumps({
        "Address": public_address,
        "Key": private_key,
        "Passphrase": passphrase
    })
コード例 #10
0
    def export_address(self):
        item = self.listWidget.currentItem()

        try:
            private_key = self.wallet.algo_wallet.export_key(item.text())
        except Exception as e:
            if __debug__:
                print(type(e), str(e), file=stderr)
            QtWidgets.QMessageBox.critical(self, "Could not export address",
                                           str(e))
        else:
            QtGui.QGuiApplication.clipboard().setText(
                from_private_key(private_key))
            QtWidgets.QMessageBox.information(
                self, "Success", "Private key copied into clipboard")
コード例 #11
0
def create_New_Account(
    wallet_id, wallet_pass
):  #Taken from algorand example.py, changed the variable name to more suitable one
    wallet_handle = kcl.init_wallet_handle(wallet_id, wallet_pass)
    account_private_key, account_address = account.generate_account()
    kcl.import_key(
        handle,
        accouunt_private_key)  # import generated account into the wallet
    mnemonice_phrase = mnemonic.from_private_key(account_private_key)
    print("Wallet handle token: " + handle + "\n")
    print("Private key: " + account_private_key + "\n")
    print("Account address: " + account_address)
    print("Mnemonic phrase generated for the account:(Keep it safe) " +
          mnemonice_phrase + "\n")
    algosdk.algod.account_info(address, **kwargs)
コード例 #12
0
ファイル: generateAccount.py プロジェクト: bobeu/testalgotel
def get_mnemonics_from_sk(update, context):
    """
    Takes in private key and converts to mnemonics
    :param context:
    :param update:
    :return: 25 mnemonic words
    # """
    if '/Private_key' in context.user_data:
        sk = context.user_data['/Private_key']
        phrase = mnemonic.from_private_key(str(sk))
        update.message.reply_text(
            "Your Mnemonics:\n {}\n\nKeep your mnemonic phrase from prying eyes.\n"
            "\nI do not hold or manage your keys.".format(phrase), reply_markup=mappedKeyboard
        )
        update.message.reply_text('\nSession ended.')
        del context.user_data['/Private_key']
    else:
        update.message.reply_text("Key not found")
        # return ConversationHandler.END
    return STARTING
コード例 #13
0
def get_test_account(update, context):
    """
    Create new public/private key pair
    Returns the result of generating an account to user:
    :param update:
    :param context:
    :return: 1). An Algorand address, 2). A mnemonic seed phrase
    """
    global mn

    update.message.reply_text("Swift!\nYour keys are ready: \n")
    try:
        sk, pk = account.generate_account()
        mn = mnemonic.from_private_key(sk)
        address = account.address_from_private_key(sk)
        update.message.reply_text("Account address/Public key:  {}\n\n"
                                  "Private Key:  {}\n\n"
                                  "Mnemonic:\n {}\n\n"
                                  "I do not hold or manage your keys."
                                  "".format(address, sk, mn))
        context.user_data['default_pk'] = pk
        update.message.reply_text(
            'To test if your address works fine, copy your address, and visit:\n '
        )
        key_board = [[
            InlineKeyboardButton("DISPENSER",
                                 'https://bank.testnet.algorand.network/',
                                 callback_data='1')
        ]]

        dispenser = InlineKeyboardMarkup(key_board)

        update.message.reply_text(
            'the dispenser to get some Algos\nSession ended.'
            'Click /start to begin.',
            reply_markup=dispenser)
        context.user_data.clear()
    except Exception as e:
        update.message.reply_text('Account creation error.')
        return e
コード例 #14
0
def create_account(fund=True):
    # Change algod_token and algod_address to connect to a different client
    algod_token = "2f3203f21e738a1de6110eba6984f9d03e5a95d7a577b34616854064cf2c0e7b"
    algod_address = "https://academy-algod.dev.aws.algodev.network/"
    algod_client = algod.AlgodClient(algod_token, algod_address)

    #Generate new account for this transaction
    secret_key, my_address = account.generate_account()
    m = mnemonic.from_private_key(secret_key)
    print("My address: {}".format(my_address))

    # Check your balance. It should be 0 microAlgos
    account_info = algod_client.account_info(my_address)
    print("Account balance: {} microAlgos".format(account_info.get('amount')) +
          "\n")

    if fund:
        #Fund the created account
        print(
            'Go to the below link to fund the created account using testnet faucet: \n https://dispenser.testnet.aws.algodev.network/?account={}'
            .format(my_address))

        completed = ""
        while completed.lower() != 'yes':
            completed = input("Type 'yes' once you funded the account: ")

        print('Fund transfer in process...')
        # Wait for the faucet to transfer funds
        time.sleep(5)

        print('Fund transferred!')
        # Check your balance. It should be 5000000 microAlgos
        account_info = algod_client.account_info(my_address)
        print("Account balance: {} microAlgos".format(
            account_info.get('amount')) + "\n")

    return m
コード例 #15
0
 def mnemonic(self) -> str:
     return mnemonic.from_private_key(self.private_key)
コード例 #16
0
def create_wallet():
    """ Create new Algorand wallet """
    private_key, address = account.generate_account()
    passphrase = mnemonic.from_private_key(private_key)
    return private_key, address, passphrase
コード例 #17
0
def check_account(username):
    if not models.fetch_user(username):
        private_key, address, passphrase = create_wallet()
        passphrase = mnemonic.from_private_key(private_key)
        models.insert_user(username, address, private_key, passphrase)
    return True
コード例 #18
0
 def test_mnemonic_private_key(self):
     priv_key, address = account.generate_account()
     mn = mnemonic.from_private_key(priv_key)
     self.assertEqual(len(mn.split(" ")), constants.mnemonic_len)
     self.assertEqual(priv_key, mnemonic.to_private_key(mn))
コード例 #19
0
def generate_new_account():
    private_key, address = account.generate_account()
    print("Created new account: ", address)
    print("Generated mnemonic: \"{}\"".format(
        mnemonic.from_private_key(private_key)))
    return address
コード例 #20
0
ファイル: accounts.py プロジェクト: gyan0890/AlgorandPython
def generate_algorand_keypair():
    private_key, address = account.generate_account()
    print("My address: {}".format(address))
    print("My passphrase: {}".format(mnemonic.from_private_key(private_key)))
    return private_key, address
コード例 #21
0
    txinfo = wait_for_confirmation( acl, txid) 

    # todo add asset_id return


acl = setup_acl()

# create cmo account 
cmo_account, cmo_private_key = setup_cmo()
cmo_list = [cmo_account]


# create rightholder account
private_key, account = account_algosdk.generate_account()
print("Rh address: {}".format(account))
print("Rh passphrase: {}".format(mnemonic.from_private_key(private_key)))


input("Press smt when you have filled the accounts")

# create IPI names & identifier
asset_id_ipi = create_ipi_name(account, private_key)
asset_info_ipi = acl.asset_info(asset_id_ipi)
# print(json.dumps(asset_info_ipi, indent=4))

# create ipi record. Two types: 1) external 2) on-chain
ipi_record_id = create_external_ipi_record(account, private_key, "https://bit.ly/37hQKQa")
ipi_record_id2 = create_succint_ipi_record(asset_info_ipi["unitname"], cclasses_list[1], roles_list[1], rights_list[1], "2000", "2050", 100, ["IT"], account, private_key)


print("Here is how IPI records look like in chain ...")
コード例 #22
0
import params
from algosdk import kmd, mnemonic
from algosdk.wallet import Wallet

# create a kmd client
kcl = kmd.KMDClient(params.kmd_token, params.kmd_address)

# wallet = Wallet("wallet_name", "wallet_password", kcl)

walletid = None
wallets = kcl.list_wallets()
print("Wallet List:", wallets)
for arrayitem in wallets:
    if arrayitem.get("name") == "wallet1":
        walletid = arrayitem.get("id")
        break
print("Wallet ID:", walletid)

wallethandle = kcl.init_wallet_handle(walletid, "testpassword")
print("Wallet Handle:", wallethandle)

accounts = kcl.list_keys(wallethandle)
print("Accounts:", accounts)
accountkey = kcl.export_key(wallethandle, "testpassword", "WHWPLXPIANMRNFB6ZEBJKXMZWRN4NLDK3BNVNOIEEAEUWIJDFVNHNPA3OQ")
print("Account Key:", accountkey)
mn = mnemonic.from_private_key(accountkey)
print("Mnemonic: ", mn)

# wallethandle = wallet.init_handle()
# print("Wallet Handle:", wallethandle)
コード例 #23
0
ファイル: test.py プロジェクト: shyich03/tree-backend
import base64
from algosdk.v2client import algod
from algosdk import mnemonic
from algosdk import transaction
from Certificate import Certificate
import Algorand
from CertificateIndexer import CertificateIndexer
from CertificateMaker import CertificateMaker
import hashlib
import datetime
import numpy as np
from algosdk import account
# private_key, public_address = account.generate_account()
# print("Base64 Private Key: {}\nPublic Algorand Address: {}\n".format(private_key, public_address))
m = mnemonic.from_private_key(
    'x3/x7jdaBWxJZN6IW7DtRw8T/mTMEim1Ca6yXrm1JXTCg+9kOU561gfgnml6qD3wj9cY1W3X4qzlzszEfDjRFw=='
)
print(m)
# x3/x7jdaBWxJZN6IW7DtRw8T/mTMEim1Ca6yXrm1JXTCg+9kOU561gfgnml6qD3wj9cY1W3X4qzlzszEfDjRFw==
# YKB66ZBZJZ5NMB7ATZUXVKB56CH5OGGVNXL6FLHFZ3GMI7BY2EL5EH3UZM
algod_address = "https://testnet-algorand.api.purestake.io/ps2"
algod_token = "zLAOcinLq31BhPezSnHQL3NF7qBwHtku6XwN8igq"
purestake_token = {'X-Api-key': algod_token}

passphrase = "wedding shine wash pet apple force car taxi illegal scrap walnut virtual champion display glimpse barrel pioneer chat finish twenty increase hope patrol about stage"
private_key = mnemonic.to_private_key(passphrase)
my_address = mnemonic.to_public_key(passphrase)
print("My address: {}".format(my_address))

algod_client = algod.AlgodClient(algod_token,
                                 algod_address,
コード例 #24
0
if (len(sys.argv) < 2):
    sys.exit(
        "usage : convert_mnemonic.py 'my mnemonic phrase' [accountid, default = 0]"
    )

words = sys.argv[1]
accountid = "0"

if (len(sys.argv) == 3):
    if (sys.argv[2].isdecimal()):
        accountid = sys.argv[2]
    else:
        print("\nWarning: invalid account id, defaulting to 0")

seed = mnemo.to_seed(words, passphrase="")

run_cmd = ["./build/src/privkey_algorand", seed.hex(), accountid]
testRun = subprocess.run(run_cmd,
                         stdout=subprocess.PIPE,
                         stdin=None,
                         cwd=os.path.dirname(os.path.realpath(__file__)),
                         stderr=subprocess.PIPE,
                         bufsize=0,
                         universal_newlines=True,
                         timeout=100)
privatekey = testRun.stdout.partition('\n')[0]

pkey_hex = binascii.unhexlify(privatekey)
algo_mnemonic = mnemonic.from_private_key(base64.b64encode(pkey_hex))

print("\n" + algo_mnemonic)
コード例 #25
0
import json
from algosdk import account, mnemonic

acct = account.generate_account()
address1 = acct[1]
print("Account 1")
print(address1)
mnemonic1 = mnemonic.from_private_key(acct[0])

print("Account 2")
acct = account.generate_account()
address2 = acct[1]
print(address2)
mnemonic2 = mnemonic.from_private_key(acct[0])

print("Account 3")
acct = account.generate_account()
address3 = acct[1]
print(address3)
mnemonic3 = mnemonic.from_private_key(acct[0])
print("")
print(
    "Copy off accounts above and add TestNet Algo funds using the TestNet Dispenser at https://bank.testnet.algorand.network/"
)
print("copy off the following mnemonic code for use later")
print("")
print("mnemonic1 = \"{}\"".format(mnemonic1))
print("mnemonic2 = \"{}\"".format(mnemonic2))
print("mnemonic3 = \"{}\"".format(mnemonic3))
コード例 #26
0
print("Wallet handle token: " + handle + "\n")

# generate account with account and check if it's valid
private_key_1, address_1 = account.generate_account()
print("Private key: " + private_key_1 + "\n")
print("First account: " + address_1)

# import generated account into the wallet
kcl.import_key(handle, private_key_1)

# generate account with kmd
address_2 = kcl.generate_key(handle, False)
print("Second account: " + address_2 + "\n")

# get the mnemonic for address_1
mn = mnemonic.from_private_key(private_key_1)
print("Mnemonic for the first account: " + mn + "\n")

# get suggested parameters
sp = acl.suggested_params()

# get last block info
block_info = acl.block_info(sp.first)
print("Block", sp.first, "info:", json.dumps(block_info, indent=2), "\n")

# create a transaction
amount = 100000
txn = transaction.PaymentTxn(existing_account, sp, address_1, amount)
print("Encoded transaction:", encoding.msgpack_encode(txn), "\n")

# sign transaction with kmd
コード例 #27
0
def createPetition():
    form = CreatePetitionForm(request.form)
    if form.validate_on_submit():
        petitionWallet = "Petitions"
        petitionWalletPassword = "******"
        masterAccountWallet = "MasterAccounts"
        masterAccountWalletPassword = "******"
        wallets = kcl.list_wallets()
        petitionWalletID = None
        for w in wallets:
            if w["name"] == petitionWallet:
                petitionWalletID = w["id"]
                break
        masterAccountWalletID = None
        for w2 in wallets:
            if w2["name"] == masterAccountWallet:
                masterAccountWalletID = w2["id"]
                break

        # if it doesn't exist, create the wallet and get its ID
        if not petitionWalletID:
            petitionWalletID = kcl.create_wallet(petitionWallet,
                                                 petitionWalletPassword)["id"]

        # get a handle for the wallet
        handle = kcl.init_wallet_handle(petitionWalletID,
                                        petitionWalletPassword)
        #### MASTER ACCOUNTS
        # if it doesn't exist, create the wallet and get its ID
        if not masterAccountWalletID:
            masterAccountWalletID = kcl.create_wallet(
                masterAccountWallet, masterAccountWalletPassword)["id"]
        # get a handle for the wallet
        handle2 = kcl.init_wallet_handle(masterAccountWalletID,
                                         masterAccountWalletPassword)
        # generate account with account and check if it's valid
        private_key_1, address_1 = account.generate_account()
        # generate master account with account and check if it's valid
        private_key_2, address_2 = account.generate_account()
        # import generated account into the wallet
        kcl.import_key(handle, private_key_1)
        kcl.import_key(handle2, private_key_2)

        # get the mnemonic for address_1
        mn = mnemonic.from_private_key(private_key_2)
        print("Mnemonic for the first account: " + mn + "\n")

        petition = Petition(name=form.name.data,
                            publicKey=address_1,
                            masterAccount=address_2,
                            yesCount=0,
                            startDate=form.startDate.data,
                            endDate=form.endDate.data)
        db.session.add(petition)
        db.session.commit()

        # Run bash script that automatically transfers microAlgos
        # from unencrypted-default-wallet to the desired Peition's
        # Master Account.
        # subprocess.call(["project/autoDispense.sh",str(address_2)])

        flash('Petition has been created!.', 'success')

    return render_template('petition/createPetition.html', form=form)
コード例 #28
0
from algosdk import account, mnemonic

private_key, account_address = account.generate_account()
words = mnemonic.from_private_key(private_key)

with open('../accountA.creds', 'w') as fd:
    fd.write(f'Account address: {account_address}\n')
    fd.write(f'Private key: {private_key}\n')
    fd.write(f'Private key mnemonic: {words}')
コード例 #29
0
def sk_to_mn(context):
    context.mn = mnemonic.from_private_key(context.sk)
コード例 #30
0
ファイル: algo_vanity.py プロジェクト: PureStake/api-examples
if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument("pattern", type=str, help="Pattern to Look for at the start of an algorand address.")
    pattern = p.parse_args().pattern

    num_processors = multiprocessing.cpu_count()
    print("Detected " + str(num_processors) + " cpu(s)")

    start_time = time.time()
    count = Value('i', 0)
    queue = Queue()
    jobs = []

    # spawn number of address search processes equal to the number of processors on the system
    for i in range(num_processors):
        p = Process(target=find_address, args=(pattern, queue, count))
        jobs.append(p)
        p.start()

    signal.signal(signal.SIGINT, signal_handler)  # capture ctrl-c so we can report attempts and running time

    address, private_key = queue.get()  # this will return once one of the spawned processes finds a match
    if (address):
        print("Found a match for " + pattern + " after " + str(
            count.value) + " tries in " + get_running_time() + " seconds")
        print("Address: ", address)
        print("Private key: ", mnemonic.from_private_key(private_key))

    terminate_processes()