Beispiel #1
0
def test_export_private_key(fx_test_client: FlaskClient, fx_session: Session,
                            fx_user: User, fx_private_key: PrivateKey):
    fx_test_client.post('/login',
                        data={
                            'private_key': fx_private_key.to_hex(),
                        },
                        follow_redirects=True)
    response = fx_test_client.get('/export/')
    assert response.headers['Content-Disposition'] == \
        f'attachment;filename={fx_user.address}.csv'
    assert response.headers['Content-Type'] == 'text/csv'
    assert response.data == fx_private_key.to_hex().encode()
Beispiel #2
0
def test_get_new_novice_broadcasting(
    fx_test_client: FlaskClient,
    fx_user: User,
    fx_private_key: PrivateKey,
    fx_session: scoped_session,
):
    with unittest.mock.patch('nekoyume.game.multicast') as m:
        fx_test_client.post('/login',
                            data={
                                'private_key': fx_private_key.to_hex(),
                                'name': 'test_user',
                            },
                            follow_redirects=True)
        res = fx_test_client.get('/new')
        assert res.status_code == 200
        move = fx_session.query(Move).filter(
            Move.name == 'create_novice', ).first()
        assert move
        serialized = move.serialize(
            use_bencode=False,
            include_signature=True,
            include_id=True,
        )
        assert m.called
        args = m.call_args[1]
        assert serialized == args['serialized']
        my_node = args['my_node']
        assert isinstance(my_node, Node)
        assert my_node.url == 'http://localhost'
        broadcast = args['broadcast']
        assert isinstance(broadcast, typing.Callable)
        assert broadcast.__name__ == 'broadcast_move'
    def __save_key(key_folder: str, pk: coincurve.PrivateKey) -> str:
        path = os.path.abspath(key_folder)
        if not os.path.exists(path):
            os.makedirs(path)

        with open(os.path.join(path, Client.KEY_FILE_NAME), "wb") as file_out:
            file_out.write(pk.to_hex().encode())

        return path
def get_web3(eth_tester: EthereumTester, deployer_key: CCPrivateKey) -> Web3:
    """Returns an initialized Web3 instance"""
    provider = EthereumTesterProvider(eth_tester)
    web3 = Web3(provider)

    # add faucet account to tester
    eth_tester.add_account(deployer_key.to_hex())

    # make faucet rich
    eth_tester.send_transaction(
        {
            "from": eth_tester.get_accounts()[0],
            "to": private_key_to_address(deployer_key.to_hex()),
            "gas": 21000,
            "value": FAUCET_ALLOWANCE,
        }
    )

    return web3
Beispiel #5
0
def test_new_character_creation(fx_test_client, fx_session):
    privkey = PrivateKey()
    fx_test_client.post('/login',
                        data={
                            'private_key': privkey.to_hex(),
                        },
                        follow_redirects=True)

    assert fx_session.query(Move).filter_by(
        user_address=get_address(privkey.public_key),
        user_public_key=privkey.public_key.format(compressed=True),
        name='create_novice').first()
def deploy_contract(
    web3: Web3,
    contracts_manager: ContractManager,
    contract_name: str,
    deployer_key: CCPrivateKey,
    args: List[Any],
) -> Contract:
    deployer_address = private_key_to_address(deployer_key.to_hex())
    json_contract = contracts_manager.get_contract(contract_name)
    contract = web3.eth.contract(abi=json_contract["abi"], bytecode=json_contract["bin"])
    tx_hash = contract.constructor(*args).transact(TxParams({"from": deployer_address}))
    contract_address = web3.eth.get_transaction_receipt(tx_hash)["contractAddress"]

    return contract(contract_address)
def generateKey():
    # [type] PrivateKey
    priKey = PrivateKey()
    # [type] bytes
    pubKey = priKey.public_key.format(compressed=False)[1:]
    # address
    addr = keccak_256(pubKey).digest()[-20:]

    return {
        "privateKey": str(priKey.to_hex()),
        "publicKey": str(pubKey.hex()),
        "address": str(addr.hex()),
        "address(EIP-55)": str(addCheckSum(addr))
    }
Beispiel #8
0
def deploy_contract(
    web3: Web3,
    contracts_manager: ContractManager,
    contract_name: str,
    deployer_key: PrivateKey,
    args: Optional[List] = None,
) -> Contract:
    deployer_address = private_key_to_address(deployer_key.to_hex())
    json_contract = contracts_manager.get_contract(contract_name)
    contract = web3.eth.contract(abi=json_contract["abi"],
                                 bytecode=json_contract["bin"])
    tx_hash = contract.constructor(*args).call_and_transact(
        {"from": deployer_address})
    contract_address = web3.eth.getTransactionReceipt(tx_hash).contractAddress

    return contract(contract_address)
    def __init__(self):
        super().__init__()

        self.log = list()
        self.settle_timeout = 10

        deployer_key = PrivateKey(secret=b'deploy_key')

        pyevm_main.GENESIS_GAS_LIMIT = 6 * 10**6
        self.tester_chain = ethereum_tester()

        self.web3 = get_web3(self.tester_chain, deployer_key)

        self.tokens = [
            deploy_custom_token(
                self.web3,
                deployer_key,
            ),
            deploy_custom_token(
                self.web3,
                deployer_key,
            ),
        ]
        self.token = self.tokens[0]

        self.token_addresses = [token.address for token in self.tokens]

        self.private_keys = [
            PrivateKey(secret=b'p1'),
            PrivateKey(secret=b'p2'),
            PrivateKey(secret=b'p3'),
        ]

        # Create and fund accounts with Ether and CustomToken
        self.addresses = []
        token_amount = 100000
        for private_key in self.private_keys:
            self.tester_chain.add_account(private_key.to_hex())

            address = private_key_to_address(private_key.to_hex())
            self.tester_chain.send_transaction({
                'from':
                self.tester_chain.get_accounts()[0],
                'to':
                address,
                'gas':
                21000,
                'value':
                self.web3.toWei(100, 'ether'),
            })

            self.token.functions.transfer(
                address,
                token_amount,
            ).transact({
                'from': private_key_to_address(deployer_key.to_hex()),
            })

            self.addresses.append(address)

        self.secret_registry = deploy_contract(
            self.web3,
            CONTRACT_SECRET_REGISTRY,
            deployer_key,
            [],  # No Libs
            [],  # No Args
        )

        self.token_network_registry = deploy_contract(
            self.web3,
            CONTRACT_TOKEN_NETWORK_REGISTRY,
            deployer_key,
            [],
            [
                self.secret_registry.address,
                1,
                TEST_SETTLE_TIMEOUT_MIN,
                TEST_SETTLE_TIMEOUT_MAX,
            ],
        )

        self.token_network_registry.functions.createERC20TokenNetwork(
            self.token.address,
            MAX_ETH_CHANNEL_PARTICIPANT,
            MAX_ETH_TOKEN_NETWORK,
        ).transact()

        token_network_address = self.token_network_registry.functions.token_to_token_networks(
            self.token.address, ).call()

        self.token_network = get_token_network(
            self.web3,
            to_checksum_address(token_network_address),
        )

        channel_identifier = self.open_channel()

        self.closing_address = None
        self.update_transfer_called = False

        self.participant_addresses = {
            self.addresses[0],
            self.addresses[1],
        }

        self.channel_addresses = [
            channel_identifier,
            make_address(),
        ]
Beispiel #10
0
class Kutil:
    def __init__(self, network: str, privkey=None, seed=None, wif=None):
        '''wif=<WIF> import private key from your wallet in WIF format
           privkey=<privkey> import private key in binary format
           network=<network> specify network [ppc, tppc, btc]
           seed=<seed> specify seed (string) to make the privkey from'''

        if privkey is not None:
            self.keypair = PrivateKey(unhexlify(privkey))

        if seed is not None:
            self.keypair = PrivateKey(sha256(seed.encode()).hexdigest())

        if wif is not None:
            key = self.wif_to_privkey(wif)
            self.keypair = PrivateKey(key["privkey"])
            network = key['net_prefix']

        if privkey == seed == wif is None:
            self.keypair = PrivateKey()

        if not is_ecdsa:
            self.privkey = self.keypair.to_hex().encode()
            self.pubkey = hexlify(self.keypair.public_key.format())
        else:
            self.privkey = self.keypair.private_key
            self.pubkey = self.keypair.public_key

        self.load_network_parameters(network)

    def load_network_parameters(self, network: str) -> None:
        '''loads network parameters and sets class variables'''

        for field, var in zip(query(network)._fields, query(network)):
            setattr(self, field, var)

    def wif_to_privkey(self, wif: str) -> dict:
        '''import WIF'''
        if not 51 <= len(wif) <= 52:
            return 'Invalid WIF length'

        b58_wif = b58decode(wif)
        return {'privkey': b58_wif[1:33], 'net_prefix': hexlify(b58_wif[0:1])}

    @property
    def address(self) -> str:
        '''generate an address from pubkey'''

        key = unhexlify(self.pubkey)  # compressed pubkey as default

        keyhash = unhexlify(
            self.pubkeyhash +
            hexlify(new('ripemd160',
                        sha256(key).digest()).digest()))

        checksum = sha256(sha256(keyhash).digest()).digest()[0:4]
        address = keyhash + checksum
        return b58encode(address)

    @property
    def wif(self) -> str:
        '''convert raw private key to WIF'''

        extkey = unhexlify(self.wif_prefix + self.privkey +
                           b'01')  # compressed by default
        extcheck = extkey + sha256(sha256(extkey).digest()).digest()[0:4]
        wif = b58encode(extcheck)

        return wif
Beispiel #11
0
def generate_private_key():
    """Generates a private key."""
    privkey = PrivateKey()
    return bytes(bytearray.fromhex(privkey.to_hex()))
Beispiel #12
0
class BaseKey:
    """This class represents a point on the elliptic curve secp256k1 and
    provides all necessary cryptographic functionality. You shouldn't use
    this class directly.

    :param wif: A private key serialized to the Wallet Import Format. If the
                argument is not supplied, a new private key will be created.
                The WIF compression flag will be adhered to, but the version
                byte is disregarded. Compression will be used by all new keys.
    :type wif: ``str``
    :raises TypeError: If ``wif`` is not a ``str``.
    """
    def __init__(self, wif=None):
        if wif:
            if isinstance(wif, str):
                private_key_bytes, compressed, version = wif_to_bytes(wif)
                self._pk = ECPrivateKey(private_key_bytes)
            elif isinstance(wif, ECPrivateKey):
                self._pk = wif
                compressed = True
            else:
                raise TypeError('Wallet Import Format must be a string.')
        else:
            self._pk = ECPrivateKey()
            compressed = True

        self._public_point = None
        self._public_key = self._pk.public_key.format(compressed=compressed)

    @property
    def public_key(self):
        """The public point serialized to bytes."""
        return self._public_key

    @property
    def public_point(self):
        """The public point (x, y)."""
        if self._public_point is None:
            self._public_point = Point(*public_key_to_coords(self._public_key))
        return self._public_point

    def sign(self, data):
        """Signs some data which can be verified later by others using
        the public key.

        :param data: The message to sign.
        :type data: ``bytes``
        :returns: A signature compliant with BIP-62.
        :rtype: ``bytes``
        """
        return self._pk.sign(data)

    def verify(self, signature, data):
        """Verifies some data was signed by this private key.

        :param signature: The signature to verify.
        :type signature: ``bytes``
        :param data: The data that was supposedly signed.
        :type data: ``bytes``
        :rtype: ``bool``
        """
        return self._pk.public_key.verify(signature, data)

    def pub_to_hex(self):
        """:rtype: ``str`` """
        return bytes_to_hex(self.public_key)

    def to_hex(self):
        """:rtype: ``str``"""
        return self._pk.to_hex()

    def to_bytes(self):
        """:rtype: ``bytes``"""
        return self._pk.secret

    def to_der(self):
        """:rtype: ``bytes``"""
        return self._pk.to_der()

    def to_pem(self):
        """:rtype: ``bytes``"""
        return self._pk.to_pem()

    def to_int(self):
        """:rtype: ``int``"""
        return self._pk.to_int()

    def is_compressed(self):
        """Returns whether or not this private key corresponds to a compressed
        public key.

        :rtype: ``bool``
        """
        return True if len(self.public_key) == 33 else False

    def __eq__(self, other):
        return self.to_int() == other.to_int()