Ejemplo n.º 1
0
 def get_privatekey(self, keystore_data, password):
     try:
         key_bytes = keys.decode_keystore_json(keystore_data, password)
         key_hex = self.web3.toHex(key_bytes)
     except Exception as err:
         return {'code': 102, 'error': str(err)}, None
     return None, key_hex
Ejemplo n.º 2
0
def get_privkey(filename, passwd):
    with open(filename) as f:
        import json
        data = json.load(f)
        from ethereum.tools.keys import decode_keystore_json
        from rlp.utils import encode_hex
        return encode_hex(decode_keystore_json(data, passwd))
Ejemplo n.º 3
0
def test_key(
    filename,
    testname,
    testdata,
):
    logger.debug('running test:%r in %r' % (testname, filename))
    assert keys.check_keystore_json(testdata["json"])
    privkey = keys.decode_keystore_json(testdata["json"], testdata["password"])
    assert utils.encode_hex(privkey) == testdata["priv"]
Ejemplo n.º 4
0
    def __init__(self, keyfile, passfile):
        with open(keyfile) as data_file:
            data = json.load(data_file)

        with open(passfile) as f:
            password = f.read().strip('\n')

        privkey_bin = decode_keystore_json(data, password)
        self.private_key = PrivateKey(privkey_bin)
Ejemplo n.º 5
0
def get_private_key(keystorePtah, password):
    """
    获取私钥
    :param keystorePtah: keystore钱包json文件路径
    :param password: 钱包密码
    :return:钱包私钥
    """
    privateKey = keys.decode_keystore_json(json.load(open(keystorePtah)),
                                           password)
    return privateKey
Ejemplo n.º 6
0
def load_keyfile(keyfile, password):
    """加载钱包keyfile

    :param keyfile:
    :param password: 密码
    :param filename: keyfile路径
    """
    with open(keyfile, 'r') as f:
        keystore = json.loads(f.read())
        if not keys.check_keystore_json(keystore):
            raise ValueError('invalid keyfile format')
        return keys.decode_keystore_json(keystore, password)
Ejemplo n.º 7
0
    def unlock(self, password):
        """Unlock the account with a password.

        If the account is already unlocked, nothing happens, even if the password is wrong.

        :raises: :exc:`ValueError` (originating in ethereum.keys) if the password is wrong (and the
                 account is locked)
        """
        if self.locked:
            self._privkey = keys.decode_keystore_json(self.keystore, password)
            self.locked = False
            self.address  # get address such that it stays accessible after a subsequent lock
Ejemplo n.º 8
0
    def unlock(self, password):
        """Unlock the account with a password.

        If the account is already unlocked, nothing happens, even if the password is wrong.

        Raises:
            ValueError: (originating in ethereum.keys) if the password is wrong
            (and the account is locked)
        """
        if self.locked:
            self._privkey = keys.decode_keystore_json(self.keystore, password)
            self.locked = False
            self.address  # get address such that it stays accessible after a subsequent lock
Ejemplo n.º 9
0
def retrieve_private_key(password, key_file):
    if os.path.isfile(key_file):
        with open(key_file) as f:
            try:
                keystore_json = json.load(f)
                keystore_json['id'] = keystore_json['id']
                key = ethkeys.decode_keystore_json(keystore_json, password)
                if not key:
                    raise Exception
                return key
            except Exception:
                logging.error('Error retrieving private key.')
                sys.exit(1)
    else:
        logging.error("Keystore file '{}' inexistent.".format(key_file))
        sys.exit(1)
Ejemplo n.º 10
0
def attempt(w, pw, verbose):
    if not isinstance(pw, str):
        pw = ''.join(str(i) for i in pw)

    if verbose > 0:
        print(pw)

    try:
        if 'encseed' in w:
            seed = getseed(w['encseed'], pw, w['ethaddr'])
        else:
            seed = decode_keystore_json(w, pw)

        if seed:
            print("""\n\nYour seed is:\n%s\n\nYour password is:\n%s\n""" %
                  (encode_hex(seed), pw))
            raise PasswordFoundException()

    except ValueError:
        return None
Ejemplo n.º 11
0
def get_private_key(key_path, password_path=None):
    """Open a JSON-encoded private key and return it

    If a password file is provided, uses it to decrypt the key. If not, the
    password is asked interactively. Raw hex-encoded private keys are supported,
    but deprecated."""

    assert key_path, key_path
    if not os.path.exists(key_path):
        log.fatal("%s: no such file", key_path)
        return None

    if not check_permission_safety(key_path):
        log.fatal("Private key file %s must be readable only by its owner.", key_path)
        return None

    if password_path and not check_permission_safety(password_path):
        log.fatal("Password file %s must be readable only by its owner.", password_path)
        return None

    with open(key_path) as keyfile:
        private_key = keyfile.readline().strip()

        if is_hex(private_key) and len(decode_hex(private_key)) == 32:
            log.warning("Private key in raw format. Consider switching to JSON-encoded")
        else:
            keyfile.seek(0)
            try:
                json_data = json.load(keyfile)
                if password_path:
                    with open(password_path) as password_file:
                        password = password_file.readline().strip()
                else:
                    password = getpass.getpass("Enter the private key password: "******"Invalid private key format or password!")
                return None

    return private_key
Ejemplo n.º 12
0
def load_keyfile(keyfile, password):
    """Loads a private key from the given keyfile.

    :param str keyfile: keyfile path

    :param str password: keyfile password

    :returns: private key
    :rtype: str

    :raises: NotImplementedError: when using Python 3
    :raises: IOError: if the file is not found
    :raises: ValueError: if the keyfile format is invalid
    """
    if sys.version_info.major >= 3:
        raise NotImplementedError('keyfile usage is only supported in python2')
    with open(keyfile, 'r') as f:
        keystore = json.load(f)
        from ethereum.tools import keys as keys
        if not keys.check_keystore_json(keystore):
            raise ValueError('invalid keyfile format')
        return keys.decode_keystore_json(keystore, password)
Ejemplo n.º 13
0
def load_keyfile(keyfile, password):
    """Loads a private key from the given keyfile.

    :param str keyfile: keyfile path

    :param str password: keyfile password

    :returns: private key
    :rtype: str

    :raises: NotImplementedError: when using Python 3
    :raises: IOError: if the file is not found
    :raises: ValueError: if the keyfile format is invalid
    """
    if sys.version_info.major >= 3:
        raise NotImplementedError('keyfile usage is only supported in python2')
    with open(keyfile, 'r') as f:
        keystore = json.load(f)
        from ethereum.tools import keys as keys
        if not keys.check_keystore_json(keystore):
            raise ValueError('invalid keyfile format')
        return keys.decode_keystore_json(keystore, password)
Ejemplo n.º 14
0
    def _submit_transaction(self, data_value):

        amount = 0

        tx_count = self.web3.eth.getTransactionCount(self.from_addr)

        tx_gasprice = self.web3.eth.gasPrice

        # tx_startgas = self.web3.eth.estimateGas({
        #     'to': self.to_addr,
        #     'from': self.from_addr,
        #     'value': amount,
        #     'data': data_value,
        # })

        tx_startgas = 90000

        tx = Transaction(
            nonce=tx_count,
            gasprice=tx_gasprice,
            startgas=tx_startgas,
            to=self.web3.toAscii(self.to_addr),
            value=amount,
            data=self.web3.toAscii(data_value)
        )

        key_file_json = json.loads(open(self.key_file).read())

        keys = decode_keystore_json(key_file_json, self.key_pass)

        tx.sign(keys)

        tx_hex_signed = self.web3.toHex(encode(tx))

        tx_id = self.web3.eth.sendRawTransaction(tx_hex_signed)
        print('Transaction Hash: ' + tx_id)

        return tx_id
Ejemplo n.º 15
0
 def privatekey(self, account_addr, password):
     keystore = self.keystore(account_addr)
     key_bytes = keys.decode_keystore_json(keystore, password)
     key_hex = self.web3.toHex(key_bytes)
     return key_hex
Ejemplo n.º 16
0
    def generateTX(self):
        try:
            address = self.textbox_receiver.text()
            if not len(address) == 42:
                raise Exception(
                    'Address must have length 42 (beginning with "0x")')

            unitconv = {'wei (atto)':1, 'babbage (femto)':10**3, 'lovelace (pico)':10**6,\
                'shannon (nano)':10**9, 'szabo (micro)':10**12, 'finney (milli)':10**15,\
                'ether':10**18}
            unit = self.combobox_unit.currentText()

            amount = int(
                float(self.textbox_amount.text().replace(',', '.')) *
                unitconv[unit])
            if amount < 0:
                raise Exception('Amount must be greated than 0')

            nonce = int(self.textbox_nonce.text())
            if nonce < 0:
                raise Exception('Nonce must be greated than 0')

            gas_price = int(self.textbox_gasprice.text())
            if gas_price < 0:
                raise Exception('Gas price must be greated than 0')

            gas = int(self.textbox_gas.text())
            if gas < 0:
                raise Exception('Gas amount must be greated than 0')

            #data = self.textbox_data.text().encode('utf-8')
            data = self.textbox_data.text()

            # try to get data from base16 input
            try:
                ldata = ceil(len(data[2:]) /
                             2) if data[:2] == '0x' else ceil(len(data) / 2)
                data = int(data, 16).to_bytes(ldata, 'big')
            except ValueError as e:
                data = data.encode('utf-8')

            # from which field do we get the networkid?
            if (self.radiobutton_networkid_textbox.isChecked()):
                # textbox
                networkid = int(self.textbox_networkid.text())
            else:
                # drop down menu
                networkid = int(self.combobox_networkid.currentText()[:2])

            if networkid < 0:
                raise Exception('Network ID must be greated than 0')

            # how to retrieve the private key?
            if (self.radiobutton_key.isChecked()):
                # directly
                priv_key = self.textbox_privatekey.text()

            else:
                # keystore
                keystorefile = self.textbox_keystore.text()
                keystorepw = self.textbox_keystore_pw.text()

                with open(keystorefile, 'r') as kf:
                    jdata = jload(kf)

                priv_key = keys.decode_keystore_json(jdata, keystorepw)
                priv_key = self.safeBytesToHex(priv_key, 64)

            if not len(priv_key) in [64, 66]:
                raise Exception(
                    'Invalid private key length: got {}, expected 64 or 66'.
                    format(len(priv_key)))

            #address_sender = hex(int.from_bytes(keys.privtoaddr(priv_key), 'big'))
            address_sender = self.safeBytesToHex(keys.privtoaddr(priv_key), 40)
            self.label_address_sender.setText(address_sender)

            priv_key = int(priv_key, 16)

            # generate the tx data
            tx = Transaction(nonce, gas_price, gas, address, amount, data)
            tx_signed = tx.sign(priv_key)
            tx_data = hex(int.from_bytes(rlpencode(tx_signed), 'big'))
            self.textbrowser_result.setPlainText(str(tx_data))
        except Exception as e:
            print(dir(e))
            self.textbrowser_result.setPlainText('ERROR: \n' + str(e))
Ejemplo n.º 17
0
    def __init__(self,
                 keyfile='',
                 password='',
                 private_key='',
                 provider='',
                 provider_endpoint_uri='http://159.89.240.147:8545',
                 contract_address=KIN_CONTRACT_ADDRESS,
                 contract_abi=KIN_ABI):
        """Create a new instance of the KIN SDK.

        The SDK needs a JSON-RPC provider, contract definitions and the wallet private key.
        The user may pass either a provider or a provider endpoint URI, in which case a default
        `web3:providers:HTTPProvider` will be created.

        If private_key is not provided, the SDK can still be used in "anonymous" mode with only the following
        functions available:
            - get_address_ether_balance
            - get_transaction_status
            - monitor_ether_transactions

        :param str private_key: a private key to initialize the wallet with. If either private key or keyfile
            are not provided, the wallet will not be initialized and methods needing the wallet will raise exception.

        :param str keyfile: the path to the keyfile to initialize to wallet with. Usually you will also need to supply
        a password for this keyfile.

        :param str password: a password for the keyfile.

        :param provider: JSON-RPC provider to work with. If not provided, a default `web3:providers:HTTPProvider`
            is used, inited with provider_endpoint_uri.
        :type provider: :class:`web3:providers:BaseProvider`

        :param str provider_endpoint_uri: a URI to use with a default HTTPProvider. If not provided, a
            default endpoint will be used.

        :param str contract_address: the address of the token contract. If not provided, a default KIN
            contract address will be used.

        :param dict contract_abi: The contract ABI. If not provided, a default KIN contract ABI will be used.

        :returns: An instance of the SDK.
        :rtype: :class:`~kin.TokenSDK`

        :raises: :class:`~kin.exceptions.SdkConfigurationError` if some of the configuration parameters are invalid.
        """

        if not provider and not provider_endpoint_uri:
            raise SdkConfigurationError(
                'either provider or provider endpoint must be provided')

        if not contract_address:
            raise SdkConfigurationError('token contract address not provided')

        try:
            validate_address(contract_address)
        except ValueError:
            raise SdkConfigurationError('invalid token contract address')

        if not contract_abi:
            raise SdkConfigurationError('token contract abi not provided')

        try:
            validate_abi(contract_abi)
        except Exception as e:
            raise SdkConfigurationError('invalid token contract abi: ' +
                                        str(e))

        if provider:
            self.web3 = Web3(provider)
        else:
            self.web3 = Web3(HTTPProvider(provider_endpoint_uri))
        if not self.web3.isConnected():
            raise SdkConfigurationError('cannot connect to provider endpoint')

        self.token_contract = self.web3.eth.contract(
            contract_address, abi=contract_abi, ContractFactoryClass=Contract)
        self.private_key = None
        self.address = None

        if keyfile:
            with open(keyfile, 'r') as f:
                try:
                    keystore = json.load(f)
                except Exception as e:
                    raise SdkConfigurationError(
                        'invalid json in keystore file')
            from ethereum.tools import keys as ekeys
            if not ekeys.check_keystore_json(keystore):
                raise SdkConfigurationError('invalid keystore file')
            try:
                self.private_key = ekeys.decode_keystore_json(
                    keystore, password)
            except ValueError as e:
                raise SdkConfigurationError('keyfile decode error: ' + str(e))
        elif private_key:
            self.private_key = private_key

        if self.private_key:
            try:
                private_key_bytes = hexstr_if_str(to_bytes, self.private_key)
                pk = keys.PrivateKey(private_key_bytes)
            except ValidationError as e:
                raise SdkConfigurationError('cannot load private key: ' +
                                            str(e))
            self.address = self.web3.eth.defaultAccount = pk.public_key.to_checksum_address(
            )

        # monitoring filters
        self._pending_tx_filter = None
        self._new_block_filter = None