コード例 #1
0
    def create(self, extra_entropy='', chain_id=MAINNET_CHAIN_ID):
        '''
        Creates a new private key, and returns it as a :class:`~newchain_account.local.LocalAccount`.

        :param extra_entropy: Add extra randomness to whatever randomness your OS can provide
        :type extra_entropy: str or bytes or int
        :returns: an object with private key and convenience methods

        .. code-block:: python

            >>> from newchain_account import Account
            >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
            >>> acct.address
            '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
            >>> acct.privateKey
            b"\\xb2\\}\\xb3\\x1f\\xee\\xd9\\x12''\\xbf\\t9\\xdcv\\x9a\\x96VK-\\xe4\\xc4rm\\x03[6\\xec\\xf1\\xe5\\xb3d"

            # These methods are also available: signHash(), signTransaction(), encrypt()
            # They correspond to the same-named methods in Account.*
            # but without the private key argument
        '''
        self.chain_id = chain_id
        extra_key_bytes = text_if_str(to_bytes, extra_entropy)
        key_bytes = keccak(os.urandom(32) + extra_key_bytes)
        return self.privateKeyToAccount(key_bytes)
コード例 #2
0
    def generate_account(self, web3, balance=0):
        extra_entropy = ''
        extra_key_bytes = text_if_str(to_bytes, extra_entropy)
        key_bytes = keccak(os.urandom(32) + extra_key_bytes)
        privatekey = keys.PrivateKey(key_bytes)
        address = privatekey.public_key.to_address()
        address = Web3.toChecksumAddress(address)
        prikey = privatekey.to_hex()[2:]
        if balance != 0:
            self.sendTransaction(web3, '', self.account_with_money['address'],
                                 address, web3.platon.gasPrice, 21000, balance)
        account = {
            "address": address,
            "nonce": 0,
            "balance": balance,
            "prikey": prikey,
        }
        self.accounts[address] = account

        # todo delete debug

        def debug():
            from conf.settings import BASE_DIR
            from ruamel import yaml
            accounts = list(self.accounts.values())
            with open(os.path.join(BASE_DIR, "deploy/tmp/accounts.yml"),
                      mode="w",
                      encoding="UTF-8") as f:
                yaml.dump(accounts, f, Dumper=yaml.RoundTripDumper)

        debug()
        return address, prikey
コード例 #3
0
ファイル: account.py プロジェクト: danielsocials/ios
    def encrypt(cls, private_key, password, kdf=None, iterations=None):
        """
        Creates a dictionary with an encrypted version of your private key.
        To import this keyfile into Ethereum clients like geth and parity:
        encode this dictionary with :func:`json.dumps` and save it to disk where your
        client keeps key files.

        :param private_key: The raw private key
        :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
        :param str password: The password which you will need to unlock the account in your client
        :param str kdf: The key derivation function to use when encrypting your private key
        :param int iterations: The work factor for the key derivation function
        :returns: The data to use in your encrypted file
        :rtype: dict

        If kdf is not set, the default key derivation function falls back to the
        environment variable :envvar:`ETH_ACCOUNT_KDF`. If that is not set, then
        'scrypt' will be used as the default.

        .. doctest:: python

            >>> from pprint import pprint
            >>> encrypted = Account.encrypt(
            ...     0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364,
            ...     'password'
            ... )
            >>> pprint(encrypted)
            {'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
             'crypto': {'cipher': 'aes-128-ctr',
                        'cipherparams': {'iv': '...'},
                        'ciphertext': '...',
                        'kdf': 'scrypt',
                        'kdfparams': {'dklen': 32,
                                      'n': 262144,
                                      'p': 8,
                                      'r': 1,
                                      'salt': '...'},
                        'mac': '...'},
             'id': '...',
             'version': 3}

            >>> with open('my-keyfile', 'w') as f: # doctest: +SKIP
            ...    f.write(json.dumps(encrypted))
        """
        if isinstance(private_key, keys.PrivateKey):
            key_bytes = private_key.to_bytes()
        else:
            key_bytes = HexBytes(private_key)

        if kdf is None:
            kdf = cls._default_kdf

        password_bytes = text_if_str(to_bytes, password)
        assert len(key_bytes) == 32

        return create_keyfile_json(key_bytes,
                                   password_bytes,
                                   kdf=kdf,
                                   iterations=iterations)
コード例 #4
0
    def encrypt(cls, private_key, password, kdf=None):
        '''
        Creates a dictionary with an encrypted version of your private key.
        To import this keyfile into Ethereum clients like geth and parity:
        encode this dictionary with :func:`json.dumps` and save it to disk where your
        client keeps key files.

        :param private_key: The raw private key
        :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
        :param str password: The password which you will need to unlock the account in your client
        :param str kdf: The key derivation function to use when encrypting your private key
        :returns: The data to use in your encrypted file
        :rtype: dict

        .. code-block:: python

            >>> import getpass
            >>> encrypted = Account.encrypt(
                0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364,
                getpass.getpass()
            )

            {
                'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
                'crypto': {
                    'cipher': 'aes-128-ctr',
                    'cipherparams': {
                        'iv': '0b7845a5c3597d3d378bde9b7c7319b7'
                    },
                    'ciphertext': 'a494f1feb3c854e99c1ff01e6aaa17d43c0752009073503b908457dc8de5d2a5',  # noqa: E501
                    'kdf': 'scrypt',
                    'kdfparams': {
                        'dklen': 32,
                        'n': 262144,
                        'p': 8,
                        'r': 1,
                        'salt': '13c4a48123affaa29189e9097726c698'
                    },
                    'mac': 'f4cfb027eb0af9bd7a320b4374a3fa7bef02cfbafe0ec5d1fd7ad129401de0b1'
                },
                'id': 'a60e0578-0e5b-4a75-b991-d55ec6451a6f',
                'version': 3
            }

             >>> with open('my-keyfile', 'w') as f:
                 f.write(json.dumps(encrypted))
        '''
        if isinstance(private_key, keys.PrivateKey):
            key_bytes = private_key.to_bytes()
        else:
            key_bytes = HexBytes(private_key)

        if kdf is None:
            kdf = cls.default_kdf

        password_bytes = text_if_str(to_bytes, password)
        assert len(key_bytes) == 32
        return create_keyfile_json(key_bytes, password_bytes, kdf=kdf)
コード例 #5
0
ファイル: accountUtil.py プロジェクト: victoriousian/caver-py
def createKey(entropy):
    extra_key_bytes = text_if_str(to_bytes, entropy)
    key_bytes = keccak(os.urandom(32) + extra_key_bytes)
    key = parsePrivateKey(key_bytes)

    return {
        "private_key": key,
        "address": key.public_key.to_checksum_address()
    }
コード例 #6
0
def generate_key():
    """
    generate node public private key
    :return:
        privateKey
        publicKey
    """
    extra_entropy = ''
    extra_key_bytes = text_if_str(to_bytes, extra_entropy)
    key_bytes = keccak(os.urandom(32) + extra_key_bytes)
    privatekey = keys.PrivateKey(key_bytes)
    return privatekey.to_hex()[2:], keys.private_key_to_public_key(privatekey).to_hex()[2:]
コード例 #7
0
def generate_key():
    """
    生成节点公私钥
    :return:
        私钥
        公钥
    """
    extra_entropy = ''
    extra_key_bytes = text_if_str(to_bytes, extra_entropy)
    key_bytes = keccak(os.urandom(32) + extra_key_bytes)
    privatekey = keys.PrivateKey(key_bytes)
    pubKey = keys.private_key_to_public_key(privatekey)
    address = pubKey.to_address()
    # return address, privatekey.to_hex()[2:], keys.private_key_to_public_key(privatekey).to_hex()[2:]
    return address, privatekey.to_hex()[2:]
コード例 #8
0
    def encrypt(private_key, password):
        '''
        Creates a dictionary with an encrypted version of your private key.
        To import this keyfile into Ethereum clients like geth and parity:
        encode this dictionary with :func:`json.dumps` and save it to disk where your
        client keeps key files.

        :param private_key: The raw private key
        :type private_key: hex str, bytes, int or :class:`eth_keys.datatypes.PrivateKey`
        :param str password: The password which you will need to unlock the account in your client
        :returns: The data to use in your encrypted file
        :rtype: dict

        .. code-block:: python

            >>> import getpass
            >>> encrypted = Account.encrypt(
                0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364,
                getpass.getpass()
            )

            {'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
             'crypto': {'cipher': 'aes-128-ctr',
              'cipherparams': {'iv': '78f214584844e0b241b433d7c3bb8d5f'},
              'ciphertext': 'd6dbb56e4f54ba6db2e8dc14df17cb7352fdce03681dd3f90ce4b6c1d5af2c4f',
              'kdf': 'pbkdf2',
              'kdfparams': {'c': 1000000,
               'dklen': 32,
               'prf': 'hmac-sha256',
               'salt': '45cf943b4de2c05c2c440ef96af914a2'},
              'mac': 'f5e1af09df5ded25c96fcf075ada313fb6f79735a914adc8cb02e8ddee7813c3'},
             'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0',
             'version': 3}

             >>> with open('my-keyfile', 'w') as f:
                 f.write(json.dumps(encrypted))
        '''
        if isinstance(private_key, keys.PrivateKey):
            key_bytes = private_key.to_bytes()
        else:
            key_bytes = HexBytes(private_key)

        password_bytes = text_if_str(to_bytes, password)
        assert len(key_bytes) == 32
        return create_keyfile_json(key_bytes, password_bytes)
コード例 #9
0
    def decrypt(keyfile_json, password):
        """
        Decrypts a private key that was encrypted using an Ethereum client or
        :meth:`~Account.encrypt`.

        :param keyfile_json: The encrypted key
        :type keyfile_json: dict or str
        :param str password: The password that was used to encrypt the key
        :returns: the raw private key
        :rtype: ~hexbytes.main.HexBytes

        .. code-block:: python

            >>> encrypted = {
             'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
             'crypto': {'cipher': 'aes-128-ctr',
              'cipherparams': {'iv': '78f214584844e0b241b433d7c3bb8d5f'},
              'ciphertext': 'd6dbb56e4f54ba6db2e8dc14df17cb7352fdce03681dd3f90ce4b6c1d5af2c4f',
              'kdf': 'pbkdf2',
              'kdfparams': {'c': 1000000,
               'dklen': 32,
               'prf': 'hmac-sha256',
               'salt': '45cf943b4de2c05c2c440ef96af914a2'},
              'mac': 'f5e1af09df5ded25c96fcf075ada313fb6f79735a914adc8cb02e8ddee7813c3'},
             'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0',
             'version': 3}

            >>> import getpass
            >>> Account.decrypt(encrypted, getpass.getpass())
            HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364')

        """
        if isinstance(keyfile_json, str):
            keyfile = json.loads(keyfile_json)
        elif is_dict(keyfile_json):
            keyfile = keyfile_json
        else:
            raise TypeError(
                "The keyfile should be supplied as a JSON string, or a dictionary."
            )
        password_bytes = text_if_str(to_bytes, password)
        return HexBytes(decode_keyfile_json(keyfile, password_bytes))
コード例 #10
0
ファイル: account.py プロジェクト: danielsocials/ios
    def decrypt(keyfile_json, password):
        """
        Decrypts a private key that was encrypted using an Ethereum client or
        :meth:`~Account.encrypt`.

        :param keyfile_json: The encrypted key
        :type keyfile_json: dict or str
        :param str password: The password that was used to encrypt the key
        :returns: the raw private key
        :rtype: ~hexbytes.main.HexBytes

        .. doctest:: python

            >>> encrypted = {
            ... 'address': '5ce9454909639d2d17a3f753ce7d93fa0b9ab12e',
            ... 'crypto': {'cipher': 'aes-128-ctr',
            ...  'cipherparams': {'iv': '482ef54775b0cc59f25717711286f5c8'},
            ...  'ciphertext': 'cb636716a9fd46adbb31832d964df2082536edd5399a3393327dc89b0193a2be',
            ...  'kdf': 'scrypt',
            ...  'kdfparams': {},
            ...  'kdfparams': {'dklen': 32,
            ...                'n': 262144,
            ...                'p': 8,
            ...                'r': 1,
            ...                'salt': 'd3c9a9945000fcb6c9df0f854266d573'},
            ...  'mac': '4f626ec5e7fea391b2229348a65bfef532c2a4e8372c0a6a814505a350a7689d'},
            ... 'id': 'b812f3f9-78cc-462a-9e89-74418aa27cb0',
            ... 'version': 3}
            >>> Account.decrypt(encrypted, 'password')
            HexBytes('0xb25c7db31feed9122727bf0939dc769a96564b2de4c4726d035b36ecf1e5b364')

        """
        if isinstance(keyfile_json, str):
            keyfile = json.loads(keyfile_json)
        elif is_dict(keyfile_json):
            keyfile = keyfile_json
        else:
            raise TypeError(
                "The keyfile should be supplied as a JSON string, or a dictionary."
            )
        password_bytes = text_if_str(to_bytes, password)
        return HexBytes(decode_keyfile_json(keyfile, password_bytes))
コード例 #11
0
    def create(self, extra_entropy=''):
        r"""
        Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`.

        :param extra_entropy: Add extra randomness to whatever randomness your OS can provide
        :type extra_entropy: str or bytes or int
        :returns: an object with private key and convenience methods

        .. code-block:: python

            >>> from eth_account import Account
            >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
            >>> acct.address
            '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
            >>> acct.key
            HexBytes('0x8676e9a8c86c8921e922e61e0bb6e9e9689aad4c99082620610b00140e5f21b8')

            # These methods are also available: sign_message(), sign_transaction(), encrypt()
            # They correspond to the same-named methods in Account.*
            # but without the private key argument
        """
        extra_key_bytes = text_if_str(to_bytes, extra_entropy)
        key_bytes = keccak(os.urandom(32) + extra_key_bytes)
        return self.from_key(key_bytes)
コード例 #12
0
    def create(self, extra_entropy=''):
        r"""
        Creates a new private key, and returns it as a :class:`~eth_account.local.LocalAccount`.

        :param extra_entropy: Add extra randomness to whatever randomness your OS can provide
        :type extra_entropy: str or bytes or int
        :returns: an object with private key and convenience methods

        .. code-block:: python

            >>> from eth_account import Account
            >>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
            >>> acct.address
            '0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'
            >>> acct.key
            b"\xb2\}\xb3\x1f\xee\xd9\x12''\xbf\t9\xdcv\x9a\x96VK-\xe4\xc4rm\x03[6\xec\xf1\xe5\xb3d"

            # These methods are also available: sign_message(), sign_transaction(), encrypt()
            # They correspond to the same-named methods in Account.*
            # but without the private key argument
        """
        extra_key_bytes = text_if_str(to_bytes, extra_entropy)
        key_bytes = keccak(os.urandom(32) + extra_key_bytes)
        return self.from_key(key_bytes)
コード例 #13
0
ファイル: method_formatters.py プロジェクト: kclowes/web3.py
        (is_length(2), estimate_gas_with_block_id),
    )),
    RPC.eth_sendTransaction:
    apply_formatter_at_index(transaction_param_formatter, 0),
    RPC.eth_signTransaction:
    apply_formatter_at_index(transaction_param_formatter, 0),
    RPC.eth_getProof:
    apply_formatter_at_index(to_hex_if_integer, 2),
    # personal
    RPC.personal_importRawKey:
    apply_formatter_at_index(
        compose(remove_0x_prefix, hexstr_if_str(to_hex)),
        0,
    ),
    RPC.personal_sign:
    apply_formatter_at_index(text_if_str(to_hex), 0),
    RPC.personal_ecRecover:
    apply_formatter_at_index(text_if_str(to_hex), 0),
    RPC.personal_sendTransaction:
    apply_formatter_at_index(transaction_param_formatter, 0),
    # Snapshot and Revert
    RPC.evm_revert:
    apply_formatter_at_index(integer_to_hex, 0),
    RPC.trace_replayBlockTransactions:
    apply_formatter_at_index(to_hex_if_integer, 0),
    RPC.trace_block:
    apply_formatter_at_index(to_hex_if_integer, 0),
    RPC.trace_call:
    compose(apply_formatter_at_index(transaction_param_formatter, 0),
            apply_formatter_at_index(to_hex_if_integer, 2)),
}
コード例 #14
0
     ),
     'platon_getUncleByBlockHashAndIndex': apply_formatter_at_index(integer_to_hex, 1),
     'platon_newFilter': apply_formatter_at_index(filter_params_formatter, 0),
     'platon_getLogs': apply_formatter_at_index(filter_params_formatter, 0),
     'platon_call': combine_argument_formatters(
         transaction_param_formatter,
         block_number_formatter,
     ),
     'platon_estimateGas': apply_formatter_at_index(transaction_param_formatter, 0),
     'platon_sendTransaction': apply_formatter_at_index(transaction_param_formatter, 0),
     # personal
     'personal_importRawKey': apply_formatter_at_index(
         compose(remove_0x_prefix, hexstr_if_str(to_hex)),
         0,
     ),
     'personal_sign': apply_formatter_at_index(text_if_str(to_hex), 0),
     'personal_ecRecover': apply_formatter_at_index(text_if_str(to_hex), 0),
     'personal_sendTransaction': apply_formatter_at_index(transaction_param_formatter, 0),
     # Snapshot and Revert
     'evm_revert': apply_formatter_at_index(integer_to_hex, 0),
     'trace_replayBlockTransactions': apply_formatter_at_index(block_number_formatter, 0),
     'trace_block': apply_formatter_at_index(block_number_formatter, 0),
     'trace_call': compose(
         apply_formatter_at_index(transaction_param_formatter, 0),
         apply_formatter_at_index(block_number_formatter, 2)
     ),
 },
 result_formatters={
     # Eth
     'platon_accounts': apply_formatter_to_array(to_checksum_address),
     'platon_blockNumber': to_integer_if_hex,
コード例 #15
0
    to_bytes,
    to_canonical_address,
    to_text,
)
from hexbytes import (
    HexBytes, )

from celo_sdk.celo_account._utils.structured_data.hashing import (
    hash_domain,
    hash_message as hash_eip712_message,
    load_and_validate_structured_message,
)
from celo_sdk.celo_account._utils.validation import (
    is_valid_address, )

text_to_bytes = text_if_str(to_bytes)


# watch for updates to signature format
class SignableMessage(NamedTuple):
    """
    These are the components of an EIP-191_ signable message. Other message formats
    can be encoded into this format for easy signing. This data structure doesn't need to
    know about the original message format.

    In typical usage, you should never need to create these by hand. Instead, use
    one of the available encode_* methods in this module, like:

        - :meth:`encode_structured_data`
        - :meth:`encode_intended_validator`
        - :meth:`encode_structured_data`
コード例 #16
0
    RPC.eth_call: apply_formatters_to_sequence([
        transaction_param_formatter,
        block_number_formatter,
    ]),
    RPC.eth_estimateGas: apply_one_of_formatters((
        (is_length(1), estimate_gas_without_block_id),
        (is_length(2), estimate_gas_with_block_id),
    )),
    RPC.eth_sendTransaction: apply_formatter_at_index(transaction_param_formatter, 0),
    RPC.eth_getProof: apply_formatter_at_index(block_number_formatter, 2),
    # personal
    RPC.personal_importRawKey: apply_formatter_at_index(
        compose(remove_0x_prefix, hexstr_if_str(to_hex)),
        0,
    ),
    RPC.personal_sign: apply_formatter_at_index(text_if_str(to_hex), 0),
    RPC.personal_ecRecover: apply_formatter_at_index(text_if_str(to_hex), 0),
    RPC.personal_sendTransaction: apply_formatter_at_index(transaction_param_formatter, 0),
    # Snapshot and Revert
    RPC.evm_revert: apply_formatter_at_index(integer_to_hex, 0),
    RPC.trace_replayBlockTransactions: apply_formatter_at_index(block_number_formatter, 0),
    RPC.trace_block: apply_formatter_at_index(block_number_formatter, 0),
    RPC.trace_call: compose(
        apply_formatter_at_index(transaction_param_formatter, 0),
        apply_formatter_at_index(block_number_formatter, 2)
    ),
}


PYTHONIC_RESULT_FORMATTERS: Dict[RPCEndpoint, Callable[..., Any]] = {
    # Eth
コード例 #17
0
ファイル: pythonic.py プロジェクト: zheewang/web3.py
         apply_formatter_at_index(block_number_formatter, 0),
         apply_formatter_at_index(integer_to_hex, 1),
     ),
     'eth_getTransactionCount': apply_formatter_at_index(block_number_formatter, 1),
     'eth_getUncleCountByBlockNumber': apply_formatter_at_index(block_number_formatter, 0),
     'eth_newFilter': apply_formatter_at_index(filter_params_formatter, 0),
     'eth_getLogs': apply_formatter_at_index(filter_params_formatter, 0),
     'eth_call': apply_formatter_at_index(transaction_param_formatter, 0),
     'eth_estimateGas': apply_formatter_at_index(transaction_param_formatter, 0),
     'eth_sendTransaction': apply_formatter_at_index(transaction_param_formatter, 0),
     # personal
     'personal_importRawKey': apply_formatter_at_index(
         compose(remove_0x_prefix, hexstr_if_str(to_hex)),
         0,
     ),
     'personal_sign': apply_formatter_at_index(text_if_str(to_hex), 0),
     'personal_ecRecover': apply_formatter_at_index(text_if_str(to_hex), 0),
     # Snapshot and Revert
     'evm_revert': apply_formatter_at_index(integer_to_hex, 0),
 },
 result_formatters={
     # Eth
     'eth_accounts': apply_formatter_to_array(to_checksum_address),
     'eth_blockNumber': to_integer_if_hex,
     'eth_coinbase': to_checksum_address,
     'eth_estimateGas': to_integer_if_hex,
     'eth_gasPrice': to_integer_if_hex,
     'eth_getBalance': to_integer_if_hex,
     'eth_getBlockByHash': apply_formatter_if(is_not_null, block_formatter),
     'eth_getBlockByNumber': apply_formatter_if(is_not_null, block_formatter),
     'eth_getBlockTransactionCountByHash': to_integer_if_hex,