Esempio n. 1
0
def save_wallet(acct: Account, password: str) -> Account:
    encrypted: Dict = Account.encrypt(acct.privateKey, password)
    file_path: str = "%s%s%s%s" % (get_key_file_path(), KEYFILE_PREFIX,
                                   acct.address, KEYFILE_POSTFIX)
    with open(file_path, 'w+') as f:
        f.write(json.dumps(encrypted))
    return acct
Esempio n. 2
0
def _generate_transacting_keys(passphrase: str) -> dict:
    """Create a new wallet address and private "transacting" key from the provided passphrase"""
    entropy = os.urandom(32)  # max out entropy for keccak256
    account = Account.create(extra_entropy=entropy)
    encrypted_wallet_data = Account.encrypt(private_key=account.privateKey,
                                            password=passphrase)
    return encrypted_wallet_data
 def __init__(self, password=None):
     self.password = secrets.token_hex(32)
     if password:
         self.password = password
     local_account = EthAccount.create(password)
     self.key_data = EthAccount.encrypt(local_account.key, password)
     self.address = Web3.toChecksumAddress(self.key_data['address'])
Esempio n. 4
0
def create_account(keystore_dir: PS, passphrase: Optional[str] = None) -> str:
    """ Create a new Ethereum account and save it to the keystore """

    if not isinstance(keystore_dir, Path):
        keystore_dir = Path(keystore_dir)

    if not passphrase:
        if not passphrase:
            passphrase = getpass("Enter password to encrypt account:")

    eth_account = Account()
    new_account = eth_account.create()
    PRIVATE_KEY = new_account.privateKey
    new_account_json = eth_account.encrypt(PRIVATE_KEY, passphrase)

    filename = keystore_dir.joinpath('UTC--{}--{}'.format(
        datetime.now().isoformat(),
        Web3.toChecksumAddress(new_account_json.get('address'))))
    with filename.open('w') as json_file:
        try:
            json_string = json.dumps(new_account_json)
            json_file.write(json_string)
        except Exception as e:
            log.error("Error writing JSON file {}: {}".format(
                filename, str(e)))

    return new_account.address
Esempio n. 5
0
def Generate_Three_Key(password1, password2):
    if password1 == password2:
        pass1 = password1
        pass2 = password2
        if len(pass1) < 6:
            print('less than 6')
            return (0, 10000)
        else:
            acct = Account.create(password1)
            public_key = acct.address
            private_key = acct.privateKey
            encrypted = Account.encrypt(private_key, password1)
            # cmd = 'ma -genkey ' + '-pass ' + password2
            # a = subprocess.getstatusoutput(cmd)
            # if a[0] == 0:
            #     ret = (a[1].split('{')[1].split('}')[0], a[1].split('{')[2].split('}')[0])
            #     # return ret      
            #     acct = Account.privateKeyToAccount(ret[1])
            #     public_key = acct.address
            #     encrypted = Account.encrypt(ret[1], password2)
            #     return (1, [public_key, ret[1], json.dumps(encrypted),ret[0]])
            return (1, [public_key, w3.toHex(private_key), json.dumps(encrypted)])
    else:
        print('wrong')
        return (0, 10001)
Esempio n. 6
0
def _generate_wallet(passphrase: str) -> Tuple[str, dict]:
    """Create a new wallet address and private "transacting" key encrypted with the passphrase"""
    account = Account.create(
        extra_entropy=os.urandom(32))  # max out entropy for keccak256
    encrypted_wallet_data = Account.encrypt(private_key=account.privateKey,
                                            password=passphrase)
    return account.address, encrypted_wallet_data
Esempio n. 7
0
 def createAccount(self, passphrase, seed):
     acc = Account.create(seed)
     enc = Account.encrypt(acc._private_key, passphrase)
     with open(
             '/home/Development/.ethereum/rinkeby/keystore/{}'.format(
                 acc.address), 'w') as f:
         f.write(json.dumps(enc))
     return acc.address
Esempio n. 8
0
    def change_password(self):
        self.locked = True  # force entering passphrase to get key
        key = self.__key

        passphrase = self._prompt_for_passphrase("Create new passphrase",
                                                 confirmation_prompt=True)
        self.keyfile_path.write_text(
            json.dumps(EthAccount.encrypt(key, passphrase)))
Esempio n. 9
0
 def encrypt_account(self, fname, fpath=None, password=None):
     """
     Encrypt private key and metadata
     """
     fpath = './accs/' + fname if not fpath else fpath
     password = getpass.getpass() if not password else password
     encrypted = Account.encrypt(self.pk, password)
     with open(fpath, 'w') as f:
         f.write(json.dumps(encrypted))
Esempio n. 10
0
def save_wallet(acct: Account, password: str) -> Account:
    """
    For a given account and password, encrypt the account address and store it in the path from get_key_file_path()
    """
    encrypted: Dict = Account.encrypt(acct.privateKey, password)
    file_path: str = "%s%s%s%s" % (get_key_file_path(), KEYFILE_PREFIX, acct.address, KEYFILE_POSTFIX)
    with open(file_path, 'w+') as f:
        f.write(json.dumps(encrypted))
    return acct
Esempio n. 11
0
def keystore_file(tmp_path) -> str:
    keystore_file = tmp_path / KEYSTORE_FILE_NAME

    account = Account.create()
    keystore_json = Account.encrypt(private_key=account.privateKey, password=KEYSTORE_PASSWORD)
    with open(keystore_file, "w") as fp:
        json.dump(keystore_json, fp)

    return keystore_file
def add_private_key(private_key, mode) :
	encrypted = Account.encrypt(private_key, mode.password)
	address = mode.w3.toChecksumAddress(encrypted['address'])
	try :
		f = open(mode.keystore_path + address[2:] +".json", 'w')
	except :
		return False
	f.write(json.dumps(encrypted))
	f.close()
	return True
Esempio n. 13
0
def Import_Keystore(passphrase, filecontent):
    try:
        # content = json.loads(filecontent)
        private_key = w3.toHex(Account.decrypt(filecontent, passphrase))
        public_key = Account.privateKeyToAccount(private_key).address
        encrypted = Account.encrypt(private_key, passphrase)
        return (1, [public_key, private_key], json.dumps(encrypted))
    except Exception as err:
        print(err)
        return (0, 10000)
Esempio n. 14
0
def keystore_file(tmp_path) -> str:
    filename = tmp_path / KEYSTORE_FILE_NAME

    account = Account.create()
    keystore_json = Account.encrypt(private_key=account.key,
                                    password=KEYSTORE_PASSWORD)
    with open(filename, mode="w", encoding="utf-8") as f:
        json.dump(keystore_json, f)

    return filename
Esempio n. 15
0
 def import_account_key(self, address, raw_key, password, url=None):
     if url:
         web3 = Web3(HTTPProvider(url))
         address = web3.manager.request_blocking(
             'parity_newAccountFromSecret', [raw_key, password])
     else:
         self._key_chain.set_key(address,
                                 EthAccount.encrypt(raw_key, password))
         self._key_chain.save()
     return address
Esempio n. 16
0
def generate_private_key(password: str) -> dict:
    private_key = EthereumAccount().create()
    private_key_dict = private_key.encrypt(password)
    try:
        makedirs('./private-keys')
    except FileExistsError:
        pass
    with open(f'./private-keys/{private_key.address}.json',
              'w') as output_file:
        json.dump(private_key_dict, output_file)
    return private_key_dict
Esempio n. 17
0
    def change_password(self):
        self.locked = True  # force entering passphrase to get key
        key = self.__key

        passphrase = click.prompt(
            "Create New Passphrase",
            hide_input=True,
            confirmation_prompt=True,
        )

        self._keyfile.write_text(
            json.dumps(EthAccount.encrypt(key, passphrase)))
Esempio n. 18
0
 def save_keystore(self, password):
     """
     Encrypts and save keystore to path
     :param password: user password from keystore
     :return: path
     """
     create_directory(self.conf.keystore_location)
     keystore_path = self.conf.keystore_location + self.conf.keystore_filename
     encrypted_private_key = Account.encrypt(self.account.privateKey,
                                             password)
     with open(keystore_path, 'w+') as outfile:
         json.dump(encrypted_private_key, outfile, ensure_ascii=False)
     return keystore_path
Esempio n. 19
0
    def create(password: str) -> AccountBase:
        """

        Create a new account.

        You need to call `save_key_file` method to save the key information

        :return: Returns an account object
        """
        local_account = EthAccount.create(password)
        key_data = EthAccount.encrypt(local_account.key, password)
        account = EthereumAccount(key_data, password)
        return account
Esempio n. 20
0
    def create_account(self, password: str) -> str:
        """ Create a new account and encrypt it with password

        :param password: (:code:`str`) Password to use to encrypt the new account
        :returns: (:code:`str`) address of the new account
        """

        new_account = self.eth_account.create(os.urandom(len(password) * 2))
        encrypted_account = Account.encrypt(new_account.key, password)

        self._write_json_file(encrypted_account)

        return Web3.toChecksumAddress(new_account.address)
Esempio n. 21
0
def Import_mnemonic(passphrase1, passphrase2, mnemonicwords):
    if passphrase1 == passphrase2:
        cmd = 'ma -m \"' + mnemonicwords + '\" -pass \"' + passphrase2 +'\"'
        a = subprocess.getstatusoutput(cmd)
        if a[0] == 0:
            ret = (a[1].split('{')[1].split('}')[0],a[1].split('{')[2].split('}')[0])
            acct = Account.privateKeyToAccount(ret[1])
            public_key = acct.address
            encrypted = Account.encrypt(ret[1], passphrase2)
            return (1, [public_key, ret[1],json.dumps(encrypted)])
        else:
            return (0, 0)
    else:
        return (0, 0)
Esempio n. 22
0
def generate_account():
    acct = Account.create()
    eth_addr = acct.address
    eth_key = acct.key

    print('💰  Generated eth account:')
    print(f'🏘️  Eth addr: {eth_addr}')
    print(f'🔑  Eth key: {eth_key}')

    json_encrypt = Account.encrypt(eth_key, '123')

    file_name = f'UTC--{datetime.utcnow().isoformat()}000Z-e-{eth_addr[2:]}'
    file_name = file_name.replace(':', '-')
    path_file_name = f'keystore/{file_name}'

    with open(path_file_name, 'w', encoding='utf-8') as f:
        json.dump(json_encrypt, f, ensure_ascii=False, indent=4)
        f.write('\n')

    with open('environment.yaml', 'r') as f:
        data_loaded = yaml.safe_load(f)

    n = len(data_loaded['nodes']) + 1
    node_name = f'miner0{n}'
    node_info = [{
        node_name: {
            'k8s': {
                'replicas': 1
            },
            'geth': {
                'storage_size': 20,
                'Eth_Etherbase': f'{eth_addr}',
                'Eth_Password': '******',
                'Node_UserIdent': node_name,
                'Node_DataDir': f'/etc/testnet/{node_name}',
                'Node_HTTPPort': 8545,
                'Node_WSPort': 8546,
                'NodeP2P_DiscoveryAddr': 30303,
                'Dashboard_Port': 8080,
                'Dashboard_Refresh': 3000000000
            }
        }
    }]
    node_list = data_loaded['nodes']
    data_loaded['nodes'] = node_list + node_info

    data_loaded['keystore']['items'][eth_addr] = file_name

    with open('environment.yaml', 'w') as f:
        yaml.dump(data_loaded, f)
Esempio n. 23
0
 def new_account(self, password, url=None):
     address = None
     if url:
         web3 = Web3(HTTPProvider(url))
         address = web3.personal.newAccount(password)
         accounts = web3.personal.listAccounts
         if not address in accounts:
             raise NameError(f'Unable to create a new account')
     else:
         local_account = EthAccount.create(password)
         address = local_account.address
         key_value = EthAccount.encrypt(local_account.privateKey, password)
         self._key_chain.set_key(address, key_value)
         self._key_chain.save()
     return address
Esempio n. 24
0
 def post(self, request):
     value = request.POST.get('value')
     print(value)
     account = Account.create()
     print('private => {0}'.format(account._key_obj))
     print('public  => {0}'.format(account._key_obj.public_key))
     print('address => {0}'.format(account.address))
     user = request.user
     user.address = account.address
     user.publickey = account._key_obj.public_key
     user.save()
     wallet = Account.encrypt(account.privateKey, value)
     response = HttpResponse(content_type='application/json')
     response['Content-Disposition'] = 'attachment; filename=%s.json' % (
         account.address)
     response.write(json.dumps(wallet))
     return response
Esempio n. 25
0
def generate(cli_ctx, alias):
    path = _get_container().data_folder.joinpath(f"{alias}.json")
    extra_entropy = click.prompt(
        "Add extra entropy for key generation...",
        hide_input=True,
    )

    account = EthAccount.create(extra_entropy)
    passphrase = click.prompt(
        "Create Passphrase",
        hide_input=True,
        confirmation_prompt=True,
    )
    path.write_text(json.dumps(EthAccount.encrypt(account.key, passphrase)))
    cli_ctx.logger.success(
        f"A new account '{account.address}' has been added with the id '{alias}'"
    )
Esempio n. 26
0
def _import(cli_ctx, alias):
    path = _get_container().data_folder.joinpath(f"{alias}.json")
    key = click.prompt("Enter Private Key", hide_input=True)
    try:
        account = EthAccount.from_key(to_bytes(hexstr=key))
    except Exception as error:
        cli_ctx.abort(f"Key can't be imported: {error}")
        return

    passphrase = click.prompt(
        "Create Passphrase",
        hide_input=True,
        confirmation_prompt=True,
    )
    path.write_text(json.dumps(EthAccount.encrypt(account.key, passphrase)))
    cli_ctx.logger.success(
        f"A new account '{account.address}' has been added with the id '{alias}'"
    )
Esempio n. 27
0
def create_ethereum_account():
    ac = Account.create()
    wf = xp.locate_wordfile()
    words = xp.generate_wordlist(wordfile=wf, min_length=5, max_length=8)

    password_str = xp.generate_xkcdpassword(words)
    print(
        cyan(
            "password string to decrypt private key -- please store in safe location:"
        ))
    print()
    print(yellow(password_str))
    print()
    print(cyan("address:"))
    print(yellow(ac.address))

    ks = json.dumps(Account.encrypt(ac.privateKey, password_str), indent=2)
    print(red(ks))
Esempio n. 28
0
    def handle_command(self, command):
        if command == 'eth-create-address':
            tmp = getpass.getpass('Please enter a few random words: ')
            tmp = hashlib.sha256(
                (tmp + str(time.time())).encode('utf-8')).hexdigest()
            account = Account.create(tmp)
            # account.address
            # account.privateKey
            self.__ask_decrypt_password()
            encrypted = Account.encrypt(account.privateKey,
                                        self.decrypt_password)

            try:
                with open(self.ini_args.get('ethereum', 'private_key_file'),
                          'x') as keyfile:
                    keyfile.write(json.dumps(encrypted))
            except OSError as e:
                sys.exit('Error storing private key: ' + str(e))

            self.__load_private_key()
Esempio n. 29
0
def create_account(output):
    """
    Create an encrypted account on ATN test net.
    """
    acct = Account.create()
    password = getpass.getpass("Enter the password to encrypt your account: ")
    encrypted = Account.encrypt(acct.privateKey, password)
    os.makedirs(output, exist_ok=True)
    acct_path = os.path.join(output, acct.address)
    os.makedirs(acct_path, exist_ok=True)
    pk_file = os.path.join(acct_path, 'privatekey')
    pw_file = os.path.join(acct_path, 'password')
    with open(pk_file, 'w') as fh:
        fh.write(json.dumps(encrypted, indent=2))
    with open(pw_file, 'w') as fh:
        fh.write(password)
    click.echo('A new account {} created.'.format(acct.address))
    click.echo('The private  file saved at {}'.format(
        os.path.abspath(pk_file)))
    click.echo('The password file saved at {}'.format(
        os.path.abspath(pw_file)))
Esempio n. 30
0
def generate(alias):
    if alias in accounts.aliases:
        notify("ERROR", f"Account with alias '{alias}' already exists")
        return

    path = container.data_folder.joinpath(f"{alias}.json")
    extra_entropy = click.prompt(
        "Add extra entropy for key generation...",
        hide_input=True,
    )
    account = EthAccount.create(extra_entropy)
    passphrase = click.prompt(
        "Create Passphrase",
        hide_input=True,
        confirmation_prompt=True,
    )
    path.write_text(json.dumps(EthAccount.encrypt(account.key, passphrase)))

    notify(
        "SUCCESS",
        f"A new account '{account.address}' has been added with the id '{alias}'"
    )