index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
55,153
pem._object_types
__eq__
null
def __eq__(self, other: object) -> bool: if not isinstance(other, type(self)): return NotImplemented return ( type(self) == type(other) and self._pem_bytes == other._pem_bytes )
(self, other: object) -> bool
55,154
pem._object_types
__hash__
null
def __hash__(self) -> int: return hash(self._pem_bytes)
(self) -> int
55,155
pem._object_types
__init__
null
def __init__(self, pem_bytes: bytes | str): self._pem_bytes = ( pem_bytes.encode("ascii") if isinstance(pem_bytes, str) else pem_bytes ) self._sha1_hexdigest = None
(self, pem_bytes: bytes | str)
55,156
pem._object_types
__repr__
null
def __repr__(self) -> str: return "<{}(PEM string with SHA-1 digest {!r})>".format( self.__class__.__name__, self.sha1_hexdigest )
(self) -> str
55,157
pem._object_types
__str__
Return the PEM-encoded content as a native :obj:`str`.
def __str__(self) -> str: """ Return the PEM-encoded content as a native :obj:`str`. """ return self._pem_bytes.decode("ascii")
(self) -> str
55,158
pem._object_types
as_bytes
Return the PEM-encoded content as :obj:`bytes`. .. versionadded:: 16.1.0
def as_bytes(self) -> bytes: """ Return the PEM-encoded content as :obj:`bytes`. .. versionadded:: 16.1.0 """ return self._pem_bytes
(self) -> bytes
55,159
pem._object_types
as_text
Return the PEM-encoded content as text. .. versionadded:: 18.1.0
def as_text(self) -> str: """ Return the PEM-encoded content as text. .. versionadded:: 18.1.0 """ return self._pem_bytes.decode("utf-8")
(self) -> str
55,160
pem._object_types
Certificate
A certificate.
class Certificate(AbstractPEMObject): """ A certificate. """ _pattern = (b"CERTIFICATE",)
(pem_bytes: 'bytes | str')
55,168
pem._object_types
CertificateRequest
A certificate signing request. .. versionadded:: 17.1.0
class CertificateRequest(AbstractPEMObject): """ A certificate signing request. .. versionadded:: 17.1.0 """ _pattern = (b"NEW CERTIFICATE REQUEST", b"CERTIFICATE REQUEST")
(pem_bytes: 'bytes | str')
55,176
pem._object_types
CertificateRevocationList
A certificate revocation list. .. versionadded:: 18.2.0
class CertificateRevocationList(AbstractPEMObject): """ A certificate revocation list. .. versionadded:: 18.2.0 """ _pattern = (b"X509 CRL",)
(pem_bytes: 'bytes | str')
55,184
pem._object_types
DHParameters
Diffie-Hellman parameters for DHE.
class DHParameters(AbstractPEMObject): """ Diffie-Hellman parameters for DHE. """ _pattern = (b"DH PARAMETERS",)
(pem_bytes: 'bytes | str')
55,192
pem._object_types
DSAPrivateKey
A private DSA key. Also private DSA key in OpenSSH legacy PEM format. .. versionadded:: 21.1.0
class DSAPrivateKey(PrivateKey): """ A private DSA key. Also private DSA key in OpenSSH legacy PEM format. .. versionadded:: 21.1.0 """ _pattern = (b"DSA PRIVATE KEY",)
(pem_bytes: 'bytes | str')
55,200
pem._object_types
ECPrivateKey
A private EC key. .. versionadded:: 19.2.0
class ECPrivateKey(PrivateKey): """ A private EC key. .. versionadded:: 19.2.0 """ _pattern = (b"EC PRIVATE KEY",)
(pem_bytes: 'bytes | str')
55,208
pem._object_types
Key
A key of unknown type.
class Key(AbstractPEMObject): """ A key of unknown type. """ # Key is special-cased later and is kind of abstract.
(pem_bytes: 'bytes | str')
55,216
pem._object_types
OpenPGPPrivateKey
An :rfc:`4880` armored OpenPGP private key. .. versionadded:: 23.1.0
class OpenPGPPrivateKey(PrivateKey): """ An :rfc:`4880` armored OpenPGP private key. .. versionadded:: 23.1.0 """ _pattern = (b"PGP PRIVATE KEY BLOCK",)
(pem_bytes: 'bytes | str')
55,224
pem._object_types
OpenPGPPublicKey
An :rfc:`4880` armored OpenPGP public key. .. versionadded:: 23.1.0
class OpenPGPPublicKey(PublicKey): """ An :rfc:`4880` armored OpenPGP public key. .. versionadded:: 23.1.0 """ _pattern = (b"PGP PUBLIC KEY BLOCK",)
(pem_bytes: 'bytes | str')
55,232
pem._object_types
OpenSSHPrivateKey
OpenSSH private key format .. versionadded:: 19.3.0
class OpenSSHPrivateKey(PrivateKey): """ OpenSSH private key format .. versionadded:: 19.3.0 """ _pattern = (b"OPENSSH PRIVATE KEY",)
(pem_bytes: 'bytes | str')
55,240
pem._object_types
OpenSSLTrustedCertificate
An OpenSSL "trusted certificate". .. versionadded:: 21.2.0
class OpenSSLTrustedCertificate(Certificate): """ An OpenSSL "trusted certificate". .. versionadded:: 21.2.0 """ _pattern = (b"TRUSTED CERTIFICATE",)
(pem_bytes: 'bytes | str')
55,248
pem._object_types
PrivateKey
A private key of unknown type. .. versionadded:: 19.1.0
class PrivateKey(Key): """ A private key of unknown type. .. versionadded:: 19.1.0 """ _pattern: ClassVar[tuple[bytes, ...]] = ( b"PRIVATE KEY", b"ENCRYPTED PRIVATE KEY", )
(pem_bytes: 'bytes | str')
55,256
pem._object_types
PublicKey
A public key of unknown type. .. versionadded:: 19.1.0
class PublicKey(Key): """ A public key of unknown type. .. versionadded:: 19.1.0 """ _pattern = (b"PUBLIC KEY",)
(pem_bytes: 'bytes | str')
55,264
pem._object_types
RSAPrivateKey
A private RSA key.
class RSAPrivateKey(PrivateKey): """ A private RSA key. """ _pattern = (b"RSA PRIVATE KEY",)
(pem_bytes: 'bytes | str')
55,272
pem._object_types
RSAPublicKey
A public RSA key. .. versionadded:: 19.1.0
class RSAPublicKey(PublicKey): """ A public RSA key. .. versionadded:: 19.1.0 """ _pattern = (b"RSA PUBLIC KEY",)
(pem_bytes: 'bytes | str')
55,280
pem._object_types
SSHCOMPrivateKey
A private key in SSH.COM / Tectia format. .. versionadded:: 21.1.0
class SSHCOMPrivateKey(PrivateKey): """ A private key in SSH.COM / Tectia format. .. versionadded:: 21.1.0 """ _pattern = (b"SSH2 ENCRYPTED PRIVATE KEY",)
(pem_bytes: 'bytes | str')
55,288
pem._object_types
SSHPublicKey
A public key in SSH :rfc:`4716` format. The Secure Shell (SSH) Public Key File Format. .. versionadded:: 21.1.0
class SSHPublicKey(PublicKey): """ A public key in SSH :rfc:`4716` format. The Secure Shell (SSH) Public Key File Format. .. versionadded:: 21.1.0 """ _pattern = (b"SSH2 PUBLIC KEY",)
(pem_bytes: 'bytes | str')
55,296
pem
__getattr__
null
def __getattr__(name: str) -> str: dunder_to_metadata = { "__version__": "version", "__description__": "summary", "__uri__": "", "__url__": "", "__email__": "", } if name not in dunder_to_metadata.keys(): msg = f"module {__name__} has no attribute {name}" raise AttributeError(msg) import warnings from importlib.metadata import metadata if name != "__version__": warnings.warn( f"Accessing pem.{name} is deprecated and will be " "removed in a future release. Use importlib.metadata directly " "to query packaging metadata.", DeprecationWarning, stacklevel=2, ) meta = metadata("pem") if name in ("__uri__", "__url__"): return meta["Project-URL"].split(" ", 1)[-1] if name == "__email__": return meta["Author-email"].split("<", 1)[1].rstrip(">") return meta[dunder_to_metadata[name]]
(name: str) -> str
55,299
pem._core
parse
Extract PEM-like objects from *pem_str*. Returns: list[AbstractPEMObject]: list of :ref:`pem-objects` .. versionchanged:: 23.1.0 *pem_str* can now also be a... :class:`str`.
def parse(pem_str: bytes | str) -> list[AbstractPEMObject]: """ Extract PEM-like objects from *pem_str*. Returns: list[AbstractPEMObject]: list of :ref:`pem-objects` .. versionchanged:: 23.1.0 *pem_str* can now also be a... :class:`str`. """ return [ _PEM_TO_CLASS[match.group(1)](match.group(0)) for match in _PEM_RE.finditer( pem_str if isinstance(pem_str, bytes) else pem_str.encode() ) ]
(pem_str: bytes | str) -> list[pem._object_types.AbstractPEMObject]
55,300
pem._core
parse_file
Read *file_name* and parse PEM objects from it using :func:`parse`. Returns: list[AbstractPEMObject]: list of :ref:`pem-objects` .. versionchanged:: 23.1.0 *file_name* can now also be a :class:`~pathlib.Path`.
def parse_file(file_name: str | Path) -> list[AbstractPEMObject]: """ Read *file_name* and parse PEM objects from it using :func:`parse`. Returns: list[AbstractPEMObject]: list of :ref:`pem-objects` .. versionchanged:: 23.1.0 *file_name* can now also be a :class:`~pathlib.Path`. """ return parse(Path(file_name).read_bytes())
(file_name: str | pathlib.Path) -> list[pem._object_types.AbstractPEMObject]
55,301
django_app_router.routers
AppRouter
null
class AppRouter(BaseRouter): def __init__( self, trailing_slash: bool = True, ) -> None: super().__init__() self.trailing_slash = trailing_slash def get_urls(self) -> list[URLPattern]: urls = [] for route_dir in self._router_dirs: page_files = route_dir.glob(r'**/page.py') for page_file in page_files: module = utils.import_module_from_path(page_file) if method := getattr(module, 'page', None): file_path = page_file.relative_to(route_dir).parent route = _get_route( file_path, method, trailing_slash=self.trailing_slash, ) urls.append(path(route, method, name=method.__doc__)) return urls
(trailing_slash: 'bool' = True) -> 'None'
55,302
django_app_router.routers
__init__
null
def __init__( self, trailing_slash: bool = True, ) -> None: super().__init__() self.trailing_slash = trailing_slash
(self, trailing_slash: bool = True) -> NoneType
55,303
django_app_router.routers
get_urls
null
def get_urls(self) -> list[URLPattern]: urls = [] for route_dir in self._router_dirs: page_files = route_dir.glob(r'**/page.py') for page_file in page_files: module = utils.import_module_from_path(page_file) if method := getattr(module, 'page', None): file_path = page_file.relative_to(route_dir).parent route = _get_route( file_path, method, trailing_slash=self.trailing_slash, ) urls.append(path(route, method, name=method.__doc__)) return urls
(self) -> 'list[URLPattern]'
55,304
django_app_router.routers
include_app
null
def include_app(self, app: str, /) -> None: app_dir = Path(app).resolve() if not app_dir.exists(): raise FileNotFoundError(f'No app directory found in {app}') router_dir = app_dir.joinpath('routers') if not router_dir.exists(): raise FileNotFoundError(f'No routers directory found in {app}') self._router_dirs.append(router_dir) # invalidate the urls cache if hasattr(self, '_urls'): del self._urls
(self, app: str, /) -> NoneType
55,307
coincurve.context
Context
null
class Context: def __init__(self, seed: Optional[bytes] = None, flag=CONTEXT_NONE, name: str = ''): if flag not in CONTEXT_FLAGS: raise ValueError(f'{flag} is an invalid context flag.') self._lock = Lock() self.ctx = ffi.gc(lib.secp256k1_context_create(flag), lib.secp256k1_context_destroy) self.reseed(seed) self.name = name def reseed(self, seed: Optional[bytes] = None): """ Protects against certain possible future side-channel timing attacks. """ with self._lock: seed = urandom(32) if not seed or len(seed) != 32 else seed res = lib.secp256k1_context_randomize(self.ctx, ffi.new('unsigned char [32]', seed)) if not res: raise ValueError('secp256k1_context_randomize') def __repr__(self): return self.name or super().__repr__()
(seed: Optional[bytes] = None, flag=1, name: str = '')
55,308
coincurve.context
__init__
null
def __init__(self, seed: Optional[bytes] = None, flag=CONTEXT_NONE, name: str = ''): if flag not in CONTEXT_FLAGS: raise ValueError(f'{flag} is an invalid context flag.') self._lock = Lock() self.ctx = ffi.gc(lib.secp256k1_context_create(flag), lib.secp256k1_context_destroy) self.reseed(seed) self.name = name
(self, seed: Optional[bytes] = None, flag=1, name: str = '')
55,309
coincurve.context
__repr__
null
def __repr__(self): return self.name or super().__repr__()
(self)
55,310
coincurve.context
reseed
Protects against certain possible future side-channel timing attacks.
def reseed(self, seed: Optional[bytes] = None): """ Protects against certain possible future side-channel timing attacks. """ with self._lock: seed = urandom(32) if not seed or len(seed) != 32 else seed res = lib.secp256k1_context_randomize(self.ctx, ffi.new('unsigned char [32]', seed)) if not res: raise ValueError('secp256k1_context_randomize')
(self, seed: Optional[bytes] = None)
55,311
coincurve.keys
PrivateKey
null
class PrivateKey: def __init__(self, secret: Optional[bytes] = None, context: Context = GLOBAL_CONTEXT): """ :param secret: The secret used to initialize the private key. If not provided or `None`, a new key will be generated. """ self.secret: bytes = validate_secret(secret) if secret is not None else get_valid_secret() self.context = context self.public_key: PublicKey = PublicKey.from_valid_secret(self.secret, self.context) self.public_key_xonly: PublicKeyXOnly = PublicKeyXOnly.from_valid_secret(self.secret, self.context) def sign(self, message: bytes, hasher: Hasher = sha256, custom_nonce: Nonce = DEFAULT_NONCE) -> bytes: """ Create an ECDSA signature. :param message: The message to sign. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param custom_nonce: Custom nonce data in the form `(nonce_function, input_data)`. Refer to [secp256k1.h](https://github.com/bitcoin-core/secp256k1/blob/f8c0b57e6ba202b1ce7c5357688de97c9c067697/include/secp256k1.h#L546-L547). :return: The ECDSA signature. :raises ValueError: If the message hash was not 32 bytes long, the nonce generation function failed, or the private key was invalid. """ msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') signature = ffi.new('secp256k1_ecdsa_signature *') nonce_fn, nonce_data = custom_nonce signed = lib.secp256k1_ecdsa_sign(self.context.ctx, signature, msg_hash, self.secret, nonce_fn, nonce_data) if not signed: raise ValueError('The nonce generation function failed, or the private key was invalid.') return cdata_to_der(signature, self.context) def sign_schnorr(self, message: bytes, aux_randomness: bytes = b'') -> bytes: """Create a Schnorr signature. :param message: The message to sign. :param aux_randomness: An optional 32 bytes of fresh randomness. By default (empty bytestring), this will be generated automatically. Set to `None` to disable this behavior. :return: The Schnorr signature. :raises ValueError: If the message was not 32 bytes long, the optional auxiliary random data was not 32 bytes long, signing failed, or the signature was invalid. """ if len(message) != 32: raise ValueError('Message must be 32 bytes long.') elif aux_randomness == b'': aux_randomness = os.urandom(32) elif aux_randomness is None: aux_randomness = ffi.NULL elif len(aux_randomness) != 32: raise ValueError('Auxiliary random data must be 32 bytes long.') keypair = ffi.new('secp256k1_keypair *') res = lib.secp256k1_keypair_create(self.context.ctx, keypair, self.secret) if not res: raise ValueError('Secret was invalid') signature = ffi.new('unsigned char[64]') res = lib.secp256k1_schnorrsig_sign32(self.context.ctx, signature, message, keypair, aux_randomness) if not res: raise ValueError('Signing failed') res = lib.secp256k1_schnorrsig_verify( self.context.ctx, signature, message, len(message), self.public_key_xonly.public_key ) if not res: raise ValueError('Invalid signature') return bytes(ffi.buffer(signature)) def sign_recoverable(self, message: bytes, hasher: Hasher = sha256, custom_nonce: Nonce = DEFAULT_NONCE) -> bytes: """ Create a recoverable ECDSA signature. :param message: The message to sign. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param custom_nonce: Custom nonce data in the form `(nonce_function, input_data)`. Refer to [secp256k1_recovery.h](https://github.com/bitcoin-core/secp256k1/blob/f8c0b57e6ba202b1ce7c5357688de97c9c067697/include/secp256k1_recovery.h#L78-L79). :return: The recoverable ECDSA signature. :raises ValueError: If the message hash was not 32 bytes long, the nonce generation function failed, or the private key was invalid. """ msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') signature = ffi.new('secp256k1_ecdsa_recoverable_signature *') nonce_fn, nonce_data = custom_nonce signed = lib.secp256k1_ecdsa_sign_recoverable( self.context.ctx, signature, msg_hash, self.secret, nonce_fn, nonce_data ) if not signed: raise ValueError('The nonce generation function failed, or the private key was invalid.') return serialize_recoverable(signature, self.context) def ecdh(self, public_key: bytes) -> bytes: """ Compute an EC Diffie-Hellman secret in constant time. !!! note This prevents malleability by returning `sha256(compressed_public_key)` instead of the `x` coordinate directly. See #9. :param public_key: The formatted public key. :return: The 32 byte shared secret. :raises ValueError: If the public key could not be parsed or was invalid. """ secret = ffi.new('unsigned char [32]') lib.secp256k1_ecdh(self.context.ctx, secret, PublicKey(public_key).public_key, self.secret, ffi.NULL, ffi.NULL) return bytes(ffi.buffer(secret, 32)) def add(self, scalar: bytes, update: bool = False): """ Add a scalar to the private key. :param scalar: The scalar with which to add. :param update: Whether or not to update and return the private key in-place. :return: The new private key, or the modified private key if `update` is `True`. :rtype: PrivateKey :raises ValueError: If the tweak was out of range or the resulting private key was invalid. """ scalar = pad_scalar(scalar) secret = ffi.new('unsigned char [32]', self.secret) success = lib.secp256k1_ec_seckey_tweak_add(self.context.ctx, secret, scalar) if not success: raise ValueError('The tweak was out of range, or the resulting private key is invalid.') secret = bytes(ffi.buffer(secret, 32)) if update: self.secret = secret self._update_public_key() return self return PrivateKey(secret, self.context) def multiply(self, scalar: bytes, update: bool = False): """ Multiply the private key by a scalar. :param scalar: The scalar with which to multiply. :param update: Whether or not to update and return the private key in-place. :return: The new private key, or the modified private key if `update` is `True`. :rtype: PrivateKey """ scalar = validate_secret(scalar) secret = ffi.new('unsigned char [32]', self.secret) lib.secp256k1_ec_seckey_tweak_mul(self.context.ctx, secret, scalar) secret = bytes(ffi.buffer(secret, 32)) if update: self.secret = secret self._update_public_key() return self return PrivateKey(secret, self.context) def to_hex(self) -> str: """ :return: The private key encoded as a hex string. """ return self.secret.hex() def to_int(self) -> int: """ :return: The private key as an integer. """ return bytes_to_int(self.secret) def to_pem(self) -> bytes: """ :return: The private key encoded in PEM format. """ return der_to_pem(self.to_der()) def to_der(self) -> bytes: """ :return: The private key encoded in DER format. """ pk = ECPrivateKey( { 'version': 'ecPrivkeyVer1', 'private_key': self.to_int(), 'public_key': ECPointBitString(self.public_key.format(compressed=False)), } ) return PrivateKeyInfo( { 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm( { 'algorithm': 'ec', 'parameters': ECDomainParameters(name='named', value='1.3.132.0.10'), } ), 'private_key': pk, } ).dump() @classmethod def from_hex(cls, hexed: str, context: Context = GLOBAL_CONTEXT): """ :param hexed: The private key encoded as a hex string. :param context: :return: The private key. :rtype: PrivateKey """ return PrivateKey(hex_to_bytes(hexed), context) @classmethod def from_int(cls, num: int, context: Context = GLOBAL_CONTEXT): """ :param num: The private key as an integer. :param context: :return: The private key. :rtype: PrivateKey """ return PrivateKey(int_to_bytes_padded(num), context) @classmethod def from_pem(cls, pem: bytes, context: Context = GLOBAL_CONTEXT): """ :param pem: The private key encoded in PEM format. :param context: :return: The private key. :rtype: PrivateKey """ return PrivateKey( int_to_bytes_padded(PrivateKeyInfo.load(pem_to_der(pem)).native['private_key']['private_key']), context ) @classmethod def from_der(cls, der: bytes, context: Context = GLOBAL_CONTEXT): """ :param der: The private key encoded in DER format. :param context: :return: The private key. :rtype: PrivateKey """ return PrivateKey(int_to_bytes_padded(PrivateKeyInfo.load(der).native['private_key']['private_key']), context) def _update_public_key(self): created = lib.secp256k1_ec_pubkey_create(self.context.ctx, self.public_key.public_key, self.secret) if not created: raise ValueError('Invalid secret.') def __eq__(self, other) -> bool: return self.secret == other.secret
(secret: Optional[bytes] = None, context: coincurve.context.Context = GLOBAL_CONTEXT)
55,312
coincurve.keys
__eq__
null
def __eq__(self, other) -> bool: return self.secret == other.secret
(self, other) -> bool
55,313
coincurve.keys
__init__
:param secret: The secret used to initialize the private key. If not provided or `None`, a new key will be generated.
def __init__(self, secret: Optional[bytes] = None, context: Context = GLOBAL_CONTEXT): """ :param secret: The secret used to initialize the private key. If not provided or `None`, a new key will be generated. """ self.secret: bytes = validate_secret(secret) if secret is not None else get_valid_secret() self.context = context self.public_key: PublicKey = PublicKey.from_valid_secret(self.secret, self.context) self.public_key_xonly: PublicKeyXOnly = PublicKeyXOnly.from_valid_secret(self.secret, self.context)
(self, secret: Optional[bytes] = None, context: coincurve.context.Context = GLOBAL_CONTEXT)
55,314
coincurve.keys
_update_public_key
null
def _update_public_key(self): created = lib.secp256k1_ec_pubkey_create(self.context.ctx, self.public_key.public_key, self.secret) if not created: raise ValueError('Invalid secret.')
(self)
55,315
coincurve.keys
add
Add a scalar to the private key. :param scalar: The scalar with which to add. :param update: Whether or not to update and return the private key in-place. :return: The new private key, or the modified private key if `update` is `True`. :rtype: PrivateKey :raises ValueError: If the tweak was out of range or the resulting private key was invalid.
def add(self, scalar: bytes, update: bool = False): """ Add a scalar to the private key. :param scalar: The scalar with which to add. :param update: Whether or not to update and return the private key in-place. :return: The new private key, or the modified private key if `update` is `True`. :rtype: PrivateKey :raises ValueError: If the tweak was out of range or the resulting private key was invalid. """ scalar = pad_scalar(scalar) secret = ffi.new('unsigned char [32]', self.secret) success = lib.secp256k1_ec_seckey_tweak_add(self.context.ctx, secret, scalar) if not success: raise ValueError('The tweak was out of range, or the resulting private key is invalid.') secret = bytes(ffi.buffer(secret, 32)) if update: self.secret = secret self._update_public_key() return self return PrivateKey(secret, self.context)
(self, scalar: bytes, update: bool = False)
55,316
coincurve.keys
ecdh
Compute an EC Diffie-Hellman secret in constant time. !!! note This prevents malleability by returning `sha256(compressed_public_key)` instead of the `x` coordinate directly. See #9. :param public_key: The formatted public key. :return: The 32 byte shared secret. :raises ValueError: If the public key could not be parsed or was invalid.
def ecdh(self, public_key: bytes) -> bytes: """ Compute an EC Diffie-Hellman secret in constant time. !!! note This prevents malleability by returning `sha256(compressed_public_key)` instead of the `x` coordinate directly. See #9. :param public_key: The formatted public key. :return: The 32 byte shared secret. :raises ValueError: If the public key could not be parsed or was invalid. """ secret = ffi.new('unsigned char [32]') lib.secp256k1_ecdh(self.context.ctx, secret, PublicKey(public_key).public_key, self.secret, ffi.NULL, ffi.NULL) return bytes(ffi.buffer(secret, 32))
(self, public_key: bytes) -> bytes
55,317
coincurve.keys
multiply
Multiply the private key by a scalar. :param scalar: The scalar with which to multiply. :param update: Whether or not to update and return the private key in-place. :return: The new private key, or the modified private key if `update` is `True`. :rtype: PrivateKey
def multiply(self, scalar: bytes, update: bool = False): """ Multiply the private key by a scalar. :param scalar: The scalar with which to multiply. :param update: Whether or not to update and return the private key in-place. :return: The new private key, or the modified private key if `update` is `True`. :rtype: PrivateKey """ scalar = validate_secret(scalar) secret = ffi.new('unsigned char [32]', self.secret) lib.secp256k1_ec_seckey_tweak_mul(self.context.ctx, secret, scalar) secret = bytes(ffi.buffer(secret, 32)) if update: self.secret = secret self._update_public_key() return self return PrivateKey(secret, self.context)
(self, scalar: bytes, update: bool = False)
55,318
coincurve.keys
sign
Create an ECDSA signature. :param message: The message to sign. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param custom_nonce: Custom nonce data in the form `(nonce_function, input_data)`. Refer to [secp256k1.h](https://github.com/bitcoin-core/secp256k1/blob/f8c0b57e6ba202b1ce7c5357688de97c9c067697/include/secp256k1.h#L546-L547). :return: The ECDSA signature. :raises ValueError: If the message hash was not 32 bytes long, the nonce generation function failed, or the private key was invalid.
def sign(self, message: bytes, hasher: Hasher = sha256, custom_nonce: Nonce = DEFAULT_NONCE) -> bytes: """ Create an ECDSA signature. :param message: The message to sign. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param custom_nonce: Custom nonce data in the form `(nonce_function, input_data)`. Refer to [secp256k1.h](https://github.com/bitcoin-core/secp256k1/blob/f8c0b57e6ba202b1ce7c5357688de97c9c067697/include/secp256k1.h#L546-L547). :return: The ECDSA signature. :raises ValueError: If the message hash was not 32 bytes long, the nonce generation function failed, or the private key was invalid. """ msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') signature = ffi.new('secp256k1_ecdsa_signature *') nonce_fn, nonce_data = custom_nonce signed = lib.secp256k1_ecdsa_sign(self.context.ctx, signature, msg_hash, self.secret, nonce_fn, nonce_data) if not signed: raise ValueError('The nonce generation function failed, or the private key was invalid.') return cdata_to_der(signature, self.context)
(self, message: bytes, hasher: Optional[collections.abc.Callable[[bytes], bytes]] = <function sha256 at 0x7efe512428c0>, custom_nonce: Tuple[_cffi_backend._CDataBase, _cffi_backend._CDataBase] = (<cdata 'void *' NULL>, <cdata 'void *' NULL>)) -> bytes
55,319
coincurve.keys
sign_recoverable
Create a recoverable ECDSA signature. :param message: The message to sign. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param custom_nonce: Custom nonce data in the form `(nonce_function, input_data)`. Refer to [secp256k1_recovery.h](https://github.com/bitcoin-core/secp256k1/blob/f8c0b57e6ba202b1ce7c5357688de97c9c067697/include/secp256k1_recovery.h#L78-L79). :return: The recoverable ECDSA signature. :raises ValueError: If the message hash was not 32 bytes long, the nonce generation function failed, or the private key was invalid.
def sign_recoverable(self, message: bytes, hasher: Hasher = sha256, custom_nonce: Nonce = DEFAULT_NONCE) -> bytes: """ Create a recoverable ECDSA signature. :param message: The message to sign. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param custom_nonce: Custom nonce data in the form `(nonce_function, input_data)`. Refer to [secp256k1_recovery.h](https://github.com/bitcoin-core/secp256k1/blob/f8c0b57e6ba202b1ce7c5357688de97c9c067697/include/secp256k1_recovery.h#L78-L79). :return: The recoverable ECDSA signature. :raises ValueError: If the message hash was not 32 bytes long, the nonce generation function failed, or the private key was invalid. """ msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') signature = ffi.new('secp256k1_ecdsa_recoverable_signature *') nonce_fn, nonce_data = custom_nonce signed = lib.secp256k1_ecdsa_sign_recoverable( self.context.ctx, signature, msg_hash, self.secret, nonce_fn, nonce_data ) if not signed: raise ValueError('The nonce generation function failed, or the private key was invalid.') return serialize_recoverable(signature, self.context)
(self, message: bytes, hasher: Optional[collections.abc.Callable[[bytes], bytes]] = <function sha256 at 0x7efe512428c0>, custom_nonce: Tuple[_cffi_backend._CDataBase, _cffi_backend._CDataBase] = (<cdata 'void *' NULL>, <cdata 'void *' NULL>)) -> bytes
55,320
coincurve.keys
sign_schnorr
Create a Schnorr signature. :param message: The message to sign. :param aux_randomness: An optional 32 bytes of fresh randomness. By default (empty bytestring), this will be generated automatically. Set to `None` to disable this behavior. :return: The Schnorr signature. :raises ValueError: If the message was not 32 bytes long, the optional auxiliary random data was not 32 bytes long, signing failed, or the signature was invalid.
def sign_schnorr(self, message: bytes, aux_randomness: bytes = b'') -> bytes: """Create a Schnorr signature. :param message: The message to sign. :param aux_randomness: An optional 32 bytes of fresh randomness. By default (empty bytestring), this will be generated automatically. Set to `None` to disable this behavior. :return: The Schnorr signature. :raises ValueError: If the message was not 32 bytes long, the optional auxiliary random data was not 32 bytes long, signing failed, or the signature was invalid. """ if len(message) != 32: raise ValueError('Message must be 32 bytes long.') elif aux_randomness == b'': aux_randomness = os.urandom(32) elif aux_randomness is None: aux_randomness = ffi.NULL elif len(aux_randomness) != 32: raise ValueError('Auxiliary random data must be 32 bytes long.') keypair = ffi.new('secp256k1_keypair *') res = lib.secp256k1_keypair_create(self.context.ctx, keypair, self.secret) if not res: raise ValueError('Secret was invalid') signature = ffi.new('unsigned char[64]') res = lib.secp256k1_schnorrsig_sign32(self.context.ctx, signature, message, keypair, aux_randomness) if not res: raise ValueError('Signing failed') res = lib.secp256k1_schnorrsig_verify( self.context.ctx, signature, message, len(message), self.public_key_xonly.public_key ) if not res: raise ValueError('Invalid signature') return bytes(ffi.buffer(signature))
(self, message: bytes, aux_randomness: bytes = b'') -> bytes
55,321
coincurve.keys
to_der
:return: The private key encoded in DER format.
def to_der(self) -> bytes: """ :return: The private key encoded in DER format. """ pk = ECPrivateKey( { 'version': 'ecPrivkeyVer1', 'private_key': self.to_int(), 'public_key': ECPointBitString(self.public_key.format(compressed=False)), } ) return PrivateKeyInfo( { 'version': 0, 'private_key_algorithm': PrivateKeyAlgorithm( { 'algorithm': 'ec', 'parameters': ECDomainParameters(name='named', value='1.3.132.0.10'), } ), 'private_key': pk, } ).dump()
(self) -> bytes
55,322
coincurve.keys
to_hex
:return: The private key encoded as a hex string.
def to_hex(self) -> str: """ :return: The private key encoded as a hex string. """ return self.secret.hex()
(self) -> str
55,323
coincurve.keys
to_int
:return: The private key as an integer.
def to_int(self) -> int: """ :return: The private key as an integer. """ return bytes_to_int(self.secret)
(self) -> int
55,324
coincurve.keys
to_pem
:return: The private key encoded in PEM format.
def to_pem(self) -> bytes: """ :return: The private key encoded in PEM format. """ return der_to_pem(self.to_der())
(self) -> bytes
55,325
coincurve.keys
PublicKey
null
class PublicKey: def __init__(self, data, context: Context = GLOBAL_CONTEXT): """ :param data: The formatted public key. This class supports parsing compressed (33 bytes, header byte `0x02` or `0x03`), uncompressed (65 bytes, header byte `0x04`), or hybrid (65 bytes, header byte `0x06` or `0x07`) format public keys. :type data: bytes :param context: :raises ValueError: If the public key could not be parsed or was invalid. """ if not isinstance(data, bytes): self.public_key = data else: public_key = ffi.new('secp256k1_pubkey *') parsed = lib.secp256k1_ec_pubkey_parse(context.ctx, public_key, data, len(data)) if not parsed: raise ValueError('The public key could not be parsed or is invalid.') self.public_key = public_key self.context = context @classmethod def from_secret(cls, secret: bytes, context: Context = GLOBAL_CONTEXT): """ Derive a public key from a private key secret. :param secret: The private key secret. :param context: :return: The public key. :rtype: PublicKey """ public_key = ffi.new('secp256k1_pubkey *') created = lib.secp256k1_ec_pubkey_create(context.ctx, public_key, validate_secret(secret)) if not created: # no cov raise ValueError( 'Somehow an invalid secret was used. Please ' 'submit this as an issue here: ' 'https://github.com/ofek/coincurve/issues/new' ) return PublicKey(public_key, context) @classmethod def from_valid_secret(cls, secret: bytes, context: Context = GLOBAL_CONTEXT): public_key = ffi.new('secp256k1_pubkey *') created = lib.secp256k1_ec_pubkey_create(context.ctx, public_key, secret) if not created: raise ValueError('Invalid secret.') return PublicKey(public_key, context) @classmethod def from_point(cls, x: int, y: int, context: Context = GLOBAL_CONTEXT): """ Derive a public key from a coordinate point in the form `(x, y)`. :param x: :param y: :param context: :return: The public key. :rtype: PublicKey """ return PublicKey(b'\x04' + int_to_bytes_padded(x) + int_to_bytes_padded(y), context) @classmethod def from_signature_and_message( cls, signature: bytes, message: bytes, hasher: Hasher = sha256, context: Context = GLOBAL_CONTEXT ): """ Recover an ECDSA public key from a recoverable signature. :param signature: The recoverable ECDSA signature. :param message: The message that was supposedly signed. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param context: :return: The public key that signed the message. :rtype: PublicKey :raises ValueError: If the message hash was not 32 bytes long or recovery of the ECDSA public key failed. """ return PublicKey( recover(message, deserialize_recoverable(signature, context=context), hasher=hasher, context=context) ) @classmethod def combine_keys(cls, public_keys, context: Context = GLOBAL_CONTEXT): """ Add a number of public keys together. :param public_keys: A sequence of public keys. :type public_keys: List[PublicKey] :param context: :return: The combined public key. :rtype: PublicKey :raises ValueError: If the sum of the public keys was invalid. """ public_key = ffi.new('secp256k1_pubkey *') combined = lib.secp256k1_ec_pubkey_combine( context.ctx, public_key, [pk.public_key for pk in public_keys], len(public_keys) ) if not combined: raise ValueError('The sum of the public keys is invalid.') return PublicKey(public_key, context) def format(self, compressed: bool = True) -> bytes: """ Format the public key. :param compressed: Whether or to use the compressed format. :return: The 33 byte formatted public key, or the 65 byte formatted public key if `compressed` is `False`. """ length = 33 if compressed else 65 serialized = ffi.new('unsigned char [%d]' % length) output_len = ffi.new('size_t *', length) lib.secp256k1_ec_pubkey_serialize( self.context.ctx, serialized, output_len, self.public_key, EC_COMPRESSED if compressed else EC_UNCOMPRESSED ) return bytes(ffi.buffer(serialized, length)) def point(self) -> Tuple[int, int]: """ :return: The public key as a coordinate point. """ public_key = self.format(compressed=False) return bytes_to_int(public_key[1:33]), bytes_to_int(public_key[33:]) def verify(self, signature: bytes, message: bytes, hasher: Hasher = sha256) -> bool: """ :param signature: The ECDSA signature. :param message: The message that was supposedly signed. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :return: A boolean indicating whether or not the signature is correct. :raises ValueError: If the message hash was not 32 bytes long or the DER-encoded signature could not be parsed. """ msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') verified = lib.secp256k1_ecdsa_verify(self.context.ctx, der_to_cdata(signature), msg_hash, self.public_key) # A performance hack to avoid global bool() lookup. return not not verified def add(self, scalar: bytes, update: bool = False): """ Add a scalar to the public key. :param scalar: The scalar with which to add. :param update: Whether or not to update and return the public key in-place. :return: The new public key, or the modified public key if `update` is `True`. :rtype: PublicKey :raises ValueError: If the tweak was out of range or the resulting public key was invalid. """ scalar = pad_scalar(scalar) new_key = ffi.new('secp256k1_pubkey *', self.public_key[0]) success = lib.secp256k1_ec_pubkey_tweak_add(self.context.ctx, new_key, scalar) if not success: raise ValueError('The tweak was out of range, or the resulting public key is invalid.') if update: self.public_key = new_key return self return PublicKey(new_key, self.context) def multiply(self, scalar: bytes, update: bool = False): """ Multiply the public key by a scalar. :param scalar: The scalar with which to multiply. :param update: Whether or not to update and return the public key in-place. :return: The new public key, or the modified public key if `update` is `True`. :rtype: PublicKey """ scalar = validate_secret(scalar) new_key = ffi.new('secp256k1_pubkey *', self.public_key[0]) lib.secp256k1_ec_pubkey_tweak_mul(self.context.ctx, new_key, scalar) if update: self.public_key = new_key return self return PublicKey(new_key, self.context) def combine(self, public_keys, update: bool = False): """ Add a number of public keys together. :param public_keys: A sequence of public keys. :type public_keys: List[PublicKey] :param update: Whether or not to update and return the public key in-place. :return: The combined public key, or the modified public key if `update` is `True`. :rtype: PublicKey :raises ValueError: If the sum of the public keys was invalid. """ new_key = ffi.new('secp256k1_pubkey *') combined = lib.secp256k1_ec_pubkey_combine( self.context.ctx, new_key, [pk.public_key for pk in [self, *public_keys]], len(public_keys) + 1 ) if not combined: raise ValueError('The sum of the public keys is invalid.') if update: self.public_key = new_key return self return PublicKey(new_key, self.context) def __eq__(self, other) -> bool: return self.format(compressed=False) == other.format(compressed=False)
(data, context: coincurve.context.Context = GLOBAL_CONTEXT)
55,326
coincurve.keys
__eq__
null
def __eq__(self, other) -> bool: return self.format(compressed=False) == other.format(compressed=False)
(self, other) -> bool
55,327
coincurve.keys
__init__
:param data: The formatted public key. This class supports parsing compressed (33 bytes, header byte `0x02` or `0x03`), uncompressed (65 bytes, header byte `0x04`), or hybrid (65 bytes, header byte `0x06` or `0x07`) format public keys. :type data: bytes :param context: :raises ValueError: If the public key could not be parsed or was invalid.
def __init__(self, data, context: Context = GLOBAL_CONTEXT): """ :param data: The formatted public key. This class supports parsing compressed (33 bytes, header byte `0x02` or `0x03`), uncompressed (65 bytes, header byte `0x04`), or hybrid (65 bytes, header byte `0x06` or `0x07`) format public keys. :type data: bytes :param context: :raises ValueError: If the public key could not be parsed or was invalid. """ if not isinstance(data, bytes): self.public_key = data else: public_key = ffi.new('secp256k1_pubkey *') parsed = lib.secp256k1_ec_pubkey_parse(context.ctx, public_key, data, len(data)) if not parsed: raise ValueError('The public key could not be parsed or is invalid.') self.public_key = public_key self.context = context
(self, data, context: coincurve.context.Context = GLOBAL_CONTEXT)
55,328
coincurve.keys
add
Add a scalar to the public key. :param scalar: The scalar with which to add. :param update: Whether or not to update and return the public key in-place. :return: The new public key, or the modified public key if `update` is `True`. :rtype: PublicKey :raises ValueError: If the tweak was out of range or the resulting public key was invalid.
def add(self, scalar: bytes, update: bool = False): """ Add a scalar to the public key. :param scalar: The scalar with which to add. :param update: Whether or not to update and return the public key in-place. :return: The new public key, or the modified public key if `update` is `True`. :rtype: PublicKey :raises ValueError: If the tweak was out of range or the resulting public key was invalid. """ scalar = pad_scalar(scalar) new_key = ffi.new('secp256k1_pubkey *', self.public_key[0]) success = lib.secp256k1_ec_pubkey_tweak_add(self.context.ctx, new_key, scalar) if not success: raise ValueError('The tweak was out of range, or the resulting public key is invalid.') if update: self.public_key = new_key return self return PublicKey(new_key, self.context)
(self, scalar: bytes, update: bool = False)
55,329
coincurve.keys
combine
Add a number of public keys together. :param public_keys: A sequence of public keys. :type public_keys: List[PublicKey] :param update: Whether or not to update and return the public key in-place. :return: The combined public key, or the modified public key if `update` is `True`. :rtype: PublicKey :raises ValueError: If the sum of the public keys was invalid.
def combine(self, public_keys, update: bool = False): """ Add a number of public keys together. :param public_keys: A sequence of public keys. :type public_keys: List[PublicKey] :param update: Whether or not to update and return the public key in-place. :return: The combined public key, or the modified public key if `update` is `True`. :rtype: PublicKey :raises ValueError: If the sum of the public keys was invalid. """ new_key = ffi.new('secp256k1_pubkey *') combined = lib.secp256k1_ec_pubkey_combine( self.context.ctx, new_key, [pk.public_key for pk in [self, *public_keys]], len(public_keys) + 1 ) if not combined: raise ValueError('The sum of the public keys is invalid.') if update: self.public_key = new_key return self return PublicKey(new_key, self.context)
(self, public_keys, update: bool = False)
55,330
coincurve.keys
format
Format the public key. :param compressed: Whether or to use the compressed format. :return: The 33 byte formatted public key, or the 65 byte formatted public key if `compressed` is `False`.
def format(self, compressed: bool = True) -> bytes: """ Format the public key. :param compressed: Whether or to use the compressed format. :return: The 33 byte formatted public key, or the 65 byte formatted public key if `compressed` is `False`. """ length = 33 if compressed else 65 serialized = ffi.new('unsigned char [%d]' % length) output_len = ffi.new('size_t *', length) lib.secp256k1_ec_pubkey_serialize( self.context.ctx, serialized, output_len, self.public_key, EC_COMPRESSED if compressed else EC_UNCOMPRESSED ) return bytes(ffi.buffer(serialized, length))
(self, compressed: bool = True) -> bytes
55,331
coincurve.keys
multiply
Multiply the public key by a scalar. :param scalar: The scalar with which to multiply. :param update: Whether or not to update and return the public key in-place. :return: The new public key, or the modified public key if `update` is `True`. :rtype: PublicKey
def multiply(self, scalar: bytes, update: bool = False): """ Multiply the public key by a scalar. :param scalar: The scalar with which to multiply. :param update: Whether or not to update and return the public key in-place. :return: The new public key, or the modified public key if `update` is `True`. :rtype: PublicKey """ scalar = validate_secret(scalar) new_key = ffi.new('secp256k1_pubkey *', self.public_key[0]) lib.secp256k1_ec_pubkey_tweak_mul(self.context.ctx, new_key, scalar) if update: self.public_key = new_key return self return PublicKey(new_key, self.context)
(self, scalar: bytes, update: bool = False)
55,332
coincurve.keys
point
:return: The public key as a coordinate point.
def point(self) -> Tuple[int, int]: """ :return: The public key as a coordinate point. """ public_key = self.format(compressed=False) return bytes_to_int(public_key[1:33]), bytes_to_int(public_key[33:])
(self) -> Tuple[int, int]
55,333
coincurve.keys
verify
:param signature: The ECDSA signature. :param message: The message that was supposedly signed. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :return: A boolean indicating whether or not the signature is correct. :raises ValueError: If the message hash was not 32 bytes long or the DER-encoded signature could not be parsed.
def verify(self, signature: bytes, message: bytes, hasher: Hasher = sha256) -> bool: """ :param signature: The ECDSA signature. :param message: The message that was supposedly signed. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :return: A boolean indicating whether or not the signature is correct. :raises ValueError: If the message hash was not 32 bytes long or the DER-encoded signature could not be parsed. """ msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') verified = lib.secp256k1_ecdsa_verify(self.context.ctx, der_to_cdata(signature), msg_hash, self.public_key) # A performance hack to avoid global bool() lookup. return not not verified
(self, signature: bytes, message: bytes, hasher: Optional[collections.abc.Callable[[bytes], bytes]] = <function sha256 at 0x7efe512428c0>) -> bool
55,334
coincurve.keys
PublicKeyXOnly
null
class PublicKeyXOnly: def __init__(self, data, parity: bool = False, context: Context = GLOBAL_CONTEXT): """A BIP340 `x-only` public key. :param data: The formatted public key. :type data: bytes :param parity: Whether the encoded point is the negation of the public key. :param context: """ if not isinstance(data, bytes): self.public_key = data else: public_key = ffi.new('secp256k1_xonly_pubkey *') parsed = lib.secp256k1_xonly_pubkey_parse(context.ctx, public_key, data) if not parsed: raise ValueError('The public key could not be parsed or is invalid.') self.public_key = public_key self.parity = parity self.context = context @classmethod def from_secret(cls, secret: bytes, context: Context = GLOBAL_CONTEXT): """Derive an x-only public key from a private key secret. :param secret: The private key secret. :param context: :return: The x-only public key. """ keypair = ffi.new('secp256k1_keypair *') res = lib.secp256k1_keypair_create(context.ctx, keypair, validate_secret(secret)) if not res: raise ValueError('Secret was invalid') xonly_pubkey = ffi.new('secp256k1_xonly_pubkey *') pk_parity = ffi.new('int *') res = lib.secp256k1_keypair_xonly_pub(context.ctx, xonly_pubkey, pk_parity, keypair) return cls(xonly_pubkey, parity=not not pk_parity[0], context=context) @classmethod def from_valid_secret(cls, secret: bytes, context: Context = GLOBAL_CONTEXT): keypair = ffi.new('secp256k1_keypair *') res = lib.secp256k1_keypair_create(context.ctx, keypair, secret) if not res: raise ValueError('Secret was invalid') xonly_pubkey = ffi.new('secp256k1_xonly_pubkey *') pk_parity = ffi.new('int *') res = lib.secp256k1_keypair_xonly_pub(context.ctx, xonly_pubkey, pk_parity, keypair) return cls(xonly_pubkey, parity=not not pk_parity[0], context=context) def format(self) -> bytes: """Serialize the public key. :return: The public key serialized as 32 bytes. """ output32 = ffi.new('unsigned char [32]') res = lib.secp256k1_xonly_pubkey_serialize(self.context.ctx, output32, self.public_key) if not res: raise ValueError('Public key in self.public_key must be valid') return bytes(ffi.buffer(output32, 32)) def verify(self, signature: bytes, message: bytes) -> bool: """Verify a Schnorr signature over a given message. :param signature: The 64-byte Schnorr signature to verify. :param message: The message to be verified. :return: A boolean indicating whether or not the signature is correct. """ if len(signature) != 64: raise ValueError('Signature must be 32 bytes long.') return not not lib.secp256k1_schnorrsig_verify( self.context.ctx, signature, message, len(message), self.public_key ) def tweak_add(self, scalar: bytes): """Add a scalar to the public key. :param scalar: The scalar with which to add. :return: The modified public key. :rtype: PublicKeyXOnly :raises ValueError: If the tweak was out of range or the resulting public key was invalid. """ scalar = pad_scalar(scalar) out_pubkey = ffi.new('secp256k1_pubkey *') res = lib.secp256k1_xonly_pubkey_tweak_add(self.context.ctx, out_pubkey, self.public_key, scalar) if not res: raise ValueError('The tweak was out of range, or the resulting public key would be invalid') pk_parity = ffi.new('int *') lib.secp256k1_xonly_pubkey_from_pubkey(self.context.ctx, self.public_key, pk_parity, out_pubkey) self.parity = not not pk_parity[0] def __eq__(self, other) -> bool: res = lib.secp256k1_xonly_pubkey_cmp(self.context.ctx, self.public_key, other.public_key) return res == 0
(data, parity: bool = False, context: coincurve.context.Context = GLOBAL_CONTEXT)
55,335
coincurve.keys
__eq__
null
def __eq__(self, other) -> bool: res = lib.secp256k1_xonly_pubkey_cmp(self.context.ctx, self.public_key, other.public_key) return res == 0
(self, other) -> bool
55,336
coincurve.keys
__init__
A BIP340 `x-only` public key. :param data: The formatted public key. :type data: bytes :param parity: Whether the encoded point is the negation of the public key. :param context:
def __init__(self, data, parity: bool = False, context: Context = GLOBAL_CONTEXT): """A BIP340 `x-only` public key. :param data: The formatted public key. :type data: bytes :param parity: Whether the encoded point is the negation of the public key. :param context: """ if not isinstance(data, bytes): self.public_key = data else: public_key = ffi.new('secp256k1_xonly_pubkey *') parsed = lib.secp256k1_xonly_pubkey_parse(context.ctx, public_key, data) if not parsed: raise ValueError('The public key could not be parsed or is invalid.') self.public_key = public_key self.parity = parity self.context = context
(self, data, parity: bool = False, context: coincurve.context.Context = GLOBAL_CONTEXT)
55,337
coincurve.keys
format
Serialize the public key. :return: The public key serialized as 32 bytes.
def format(self) -> bytes: """Serialize the public key. :return: The public key serialized as 32 bytes. """ output32 = ffi.new('unsigned char [32]') res = lib.secp256k1_xonly_pubkey_serialize(self.context.ctx, output32, self.public_key) if not res: raise ValueError('Public key in self.public_key must be valid') return bytes(ffi.buffer(output32, 32))
(self) -> bytes
55,338
coincurve.keys
tweak_add
Add a scalar to the public key. :param scalar: The scalar with which to add. :return: The modified public key. :rtype: PublicKeyXOnly :raises ValueError: If the tweak was out of range or the resulting public key was invalid.
def tweak_add(self, scalar: bytes): """Add a scalar to the public key. :param scalar: The scalar with which to add. :return: The modified public key. :rtype: PublicKeyXOnly :raises ValueError: If the tweak was out of range or the resulting public key was invalid. """ scalar = pad_scalar(scalar) out_pubkey = ffi.new('secp256k1_pubkey *') res = lib.secp256k1_xonly_pubkey_tweak_add(self.context.ctx, out_pubkey, self.public_key, scalar) if not res: raise ValueError('The tweak was out of range, or the resulting public key would be invalid') pk_parity = ffi.new('int *') lib.secp256k1_xonly_pubkey_from_pubkey(self.context.ctx, self.public_key, pk_parity, out_pubkey) self.parity = not not pk_parity[0]
(self, scalar: bytes)
55,339
coincurve.keys
verify
Verify a Schnorr signature over a given message. :param signature: The 64-byte Schnorr signature to verify. :param message: The message to be verified. :return: A boolean indicating whether or not the signature is correct.
def verify(self, signature: bytes, message: bytes) -> bool: """Verify a Schnorr signature over a given message. :param signature: The 64-byte Schnorr signature to verify. :param message: The message to be verified. :return: A boolean indicating whether or not the signature is correct. """ if len(signature) != 64: raise ValueError('Signature must be 32 bytes long.') return not not lib.secp256k1_schnorrsig_verify( self.context.ctx, signature, message, len(message), self.public_key )
(self, signature: bytes, message: bytes) -> bool
55,347
coincurve.utils
verify_signature
:param signature: The ECDSA signature. :param message: The message that was supposedly signed. :param public_key: The formatted public key. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param context: :return: A boolean indicating whether or not the signature is correct. :raises ValueError: If the public key could not be parsed or was invalid, the message hash was not 32 bytes long, or the DER-encoded signature could not be parsed.
def verify_signature( signature: bytes, message: bytes, public_key: bytes, hasher: Hasher = sha256, context: Context = GLOBAL_CONTEXT ) -> bool: """ :param signature: The ECDSA signature. :param message: The message that was supposedly signed. :param public_key: The formatted public key. :param hasher: The hash function to use, which must return 32 bytes. By default, the `sha256` algorithm is used. If `None`, no hashing occurs. :param context: :return: A boolean indicating whether or not the signature is correct. :raises ValueError: If the public key could not be parsed or was invalid, the message hash was not 32 bytes long, or the DER-encoded signature could not be parsed. """ pubkey = ffi.new('secp256k1_pubkey *') pubkey_parsed = lib.secp256k1_ec_pubkey_parse(context.ctx, pubkey, public_key, len(public_key)) if not pubkey_parsed: raise ValueError('The public key could not be parsed or is invalid.') msg_hash = hasher(message) if hasher is not None else message if len(msg_hash) != 32: raise ValueError('Message hash must be 32 bytes long.') sig = ffi.new('secp256k1_ecdsa_signature *') sig_parsed = lib.secp256k1_ecdsa_signature_parse_der(context.ctx, sig, signature, len(signature)) if not sig_parsed: raise ValueError('The DER-encoded signature could not be parsed.') verified = lib.secp256k1_ecdsa_verify(context.ctx, sig, msg_hash, pubkey) # A performance hack to avoid global bool() lookup. return not not verified
(signature: bytes, message: bytes, public_key: bytes, hasher: Optional[collections.abc.Callable[[bytes], bytes]] = <function sha256 at 0x7efe512428c0>, context: coincurve.context.Context = GLOBAL_CONTEXT) -> bool
55,351
distrax._src.distributions.bernoulli
Bernoulli
Bernoulli distribution. Bernoulli distribution with parameter `probs`, the probability of outcome `1`.
class Bernoulli(distribution.Distribution): """Bernoulli distribution. Bernoulli distribution with parameter `probs`, the probability of outcome `1`. """ equiv_tfp_cls = tfd.Bernoulli def __init__(self, logits: Optional[Numeric] = None, probs: Optional[Numeric] = None, dtype: Union[jnp.dtype, type[Any]] = int): """Initializes a Bernoulli distribution. Args: logits: Logit transform of the probability of a `1` event (`0` otherwise), i.e. `probs = sigmoid(logits)`. Only one of `logits` or `probs` can be specified. probs: Probability of a `1` event (`0` otherwise). Only one of `logits` or `probs` can be specified. dtype: The type of event samples. """ super().__init__() # Validate arguments. if (logits is None) == (probs is None): raise ValueError( f'One and exactly one of `logits` and `probs` should be `None`, ' f'but `logits` is {logits} and `probs` is {probs}.') if not (jnp.issubdtype(dtype, bool) or jnp.issubdtype(dtype, jnp.integer) or jnp.issubdtype(dtype, jnp.floating)): raise ValueError( f'The dtype of `{self.name}` must be boolean, integer or ' f'floating-point, instead got `{dtype}`.') # Parameters of the distribution. self._probs = None if probs is None else conversion.as_float_array(probs) self._logits = None if logits is None else conversion.as_float_array(logits) self._dtype = dtype @property def event_shape(self) -> Tuple[int, ...]: """See `Distribution.event_shape`.""" return () @property def batch_shape(self) -> Tuple[int, ...]: """See `Distribution.batch_shape`.""" if self._logits is not None: return self._logits.shape return self._probs.shape @property def logits(self) -> Array: """The logits of a `1` event.""" if self._logits is not None: return self._logits return jnp.log(self._probs) - jnp.log(1 - self._probs) @property def probs(self) -> Array: """The probabilities of a `1` event..""" if self._probs is not None: return self._probs return jax.nn.sigmoid(self._logits) def _log_probs_parameter(self) -> Tuple[Array, Array]: if self._logits is None: return (jnp.log1p(-1. * self._probs), jnp.log(self._probs)) return (-jax.nn.softplus(self._logits), -jax.nn.softplus(-1. * self._logits)) def _sample_n(self, key: PRNGKey, n: int) -> Array: """See `Distribution._sample_n`.""" probs = self.probs new_shape = (n,) + probs.shape uniform = jax.random.uniform( key=key, shape=new_shape, dtype=probs.dtype, minval=0., maxval=1.) return jnp.less(uniform, probs).astype(self._dtype) def log_prob(self, value: EventT) -> Array: """See `Distribution.log_prob`.""" log_probs0, log_probs1 = self._log_probs_parameter() return (math.multiply_no_nan(log_probs0, 1 - value) + math.multiply_no_nan(log_probs1, value)) def prob(self, value: EventT) -> Array: """See `Distribution.prob`.""" probs1 = self.probs probs0 = 1 - probs1 return (math.multiply_no_nan(probs0, 1 - value) + math.multiply_no_nan(probs1, value)) def cdf(self, value: EventT) -> Array: """See `Distribution.cdf`.""" # For value < 0 the output should be zero because support = {0, 1}. return jnp.where(value < 0, jnp.array(0., dtype=self.probs.dtype), jnp.where(value >= 1, jnp.array(1.0, dtype=self.probs.dtype), 1 - self.probs)) def log_cdf(self, value: EventT) -> Array: """See `Distribution.log_cdf`.""" return jnp.log(self.cdf(value)) def entropy(self) -> Array: """See `Distribution.entropy`.""" (probs0, probs1, log_probs0, log_probs1) = _probs_and_log_probs(self) return -1. * ( math.multiply_no_nan(log_probs0, probs0) + math.multiply_no_nan(log_probs1, probs1)) def mean(self) -> Array: """See `Distribution.mean`.""" return self.probs def variance(self) -> Array: """See `Distribution.variance`.""" return (1 - self.probs) * self.probs def mode(self) -> Array: """See `Distribution.probs`.""" return (self.probs > 0.5).astype(self._dtype) def __getitem__(self, index) -> 'Bernoulli': """See `Distribution.__getitem__`.""" index = distribution.to_batch_shape_index(self.batch_shape, index) if self._logits is not None: return Bernoulli(logits=self.logits[index], dtype=self._dtype) return Bernoulli(probs=self.probs[index], dtype=self._dtype)
(logits: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int, NoneType] = None, probs: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int, NoneType] = None, dtype: Union[numpy.dtype, type[Any]] = <class 'int'>)
55,352
distrax._src.distributions.bernoulli
__getitem__
See `Distribution.__getitem__`.
def __getitem__(self, index) -> 'Bernoulli': """See `Distribution.__getitem__`.""" index = distribution.to_batch_shape_index(self.batch_shape, index) if self._logits is not None: return Bernoulli(logits=self.logits[index], dtype=self._dtype) return Bernoulli(probs=self.probs[index], dtype=self._dtype)
(self, index) -> distrax._src.distributions.bernoulli.Bernoulli
55,353
distrax._src.distributions.bernoulli
__init__
Initializes a Bernoulli distribution. Args: logits: Logit transform of the probability of a `1` event (`0` otherwise), i.e. `probs = sigmoid(logits)`. Only one of `logits` or `probs` can be specified. probs: Probability of a `1` event (`0` otherwise). Only one of `logits` or `probs` can be specified. dtype: The type of event samples.
def __init__(self, logits: Optional[Numeric] = None, probs: Optional[Numeric] = None, dtype: Union[jnp.dtype, type[Any]] = int): """Initializes a Bernoulli distribution. Args: logits: Logit transform of the probability of a `1` event (`0` otherwise), i.e. `probs = sigmoid(logits)`. Only one of `logits` or `probs` can be specified. probs: Probability of a `1` event (`0` otherwise). Only one of `logits` or `probs` can be specified. dtype: The type of event samples. """ super().__init__() # Validate arguments. if (logits is None) == (probs is None): raise ValueError( f'One and exactly one of `logits` and `probs` should be `None`, ' f'but `logits` is {logits} and `probs` is {probs}.') if not (jnp.issubdtype(dtype, bool) or jnp.issubdtype(dtype, jnp.integer) or jnp.issubdtype(dtype, jnp.floating)): raise ValueError( f'The dtype of `{self.name}` must be boolean, integer or ' f'floating-point, instead got `{dtype}`.') # Parameters of the distribution. self._probs = None if probs is None else conversion.as_float_array(probs) self._logits = None if logits is None else conversion.as_float_array(logits) self._dtype = dtype
(self, logits: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int, NoneType] = None, probs: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int, NoneType] = None, dtype: Union[numpy.dtype, type[Any]] = <class 'int'>)
55,354
distrax._src.utils.jittable
__new__
null
def __new__(cls, *args, **kwargs): # Discard the parameters to this function because the constructor is not # called during serialization: its `__dict__` gets repopulated directly. del args, kwargs try: registered_cls = jax.tree_util.register_pytree_node_class(cls) except ValueError: registered_cls = cls # Already registered. return object.__new__(registered_cls)
(cls, *args, **kwargs)
55,355
distrax._src.distributions.bernoulli
_log_probs_parameter
null
def _log_probs_parameter(self) -> Tuple[Array, Array]: if self._logits is None: return (jnp.log1p(-1. * self._probs), jnp.log(self._probs)) return (-jax.nn.softplus(self._logits), -jax.nn.softplus(-1. * self._logits))
(self) -> Tuple[Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number], Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]]
55,356
distrax._src.distributions.distribution
_name_and_control_scope
null
def stddev(self) -> EventT: """Calculates the standard deviation.""" return jnp.sqrt(self.variance())
(self, *unused_a, **unused_k)
55,357
distrax._src.distributions.bernoulli
_sample_n
See `Distribution._sample_n`.
def _sample_n(self, key: PRNGKey, n: int) -> Array: """See `Distribution._sample_n`.""" probs = self.probs new_shape = (n,) + probs.shape uniform = jax.random.uniform( key=key, shape=new_shape, dtype=probs.dtype, minval=0., maxval=1.) return jnp.less(uniform, probs).astype(self._dtype)
(self, key: jax.Array, n: int) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,358
distrax._src.distributions.distribution
_sample_n_and_log_prob
Returns `n` samples and their log probs. By default, it just calls `log_prob` on the generated samples. However, for many distributions it's more efficient to compute the log prob of samples than of arbitrary events (for example, there's no need to check that a sample is within the distribution's domain). If that's the case, a subclass may override this method with a more efficient implementation. Args: key: PRNG key. n: Number of samples to generate. Returns: A tuple of `n` samples and their log probs.
def _sample_n_and_log_prob( self, key: PRNGKey, n: int, ) -> Tuple[EventT, Array]: """Returns `n` samples and their log probs. By default, it just calls `log_prob` on the generated samples. However, for many distributions it's more efficient to compute the log prob of samples than of arbitrary events (for example, there's no need to check that a sample is within the distribution's domain). If that's the case, a subclass may override this method with a more efficient implementation. Args: key: PRNG key. n: Number of samples to generate. Returns: A tuple of `n` samples and their log probs. """ samples = self._sample_n(key, n) log_prob = self.log_prob(samples) return samples, log_prob
(self, key: jax.Array, n: int) -> Tuple[~EventT, Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]]
55,359
distrax._src.distributions.bernoulli
cdf
See `Distribution.cdf`.
def cdf(self, value: EventT) -> Array: """See `Distribution.cdf`.""" # For value < 0 the output should be zero because support = {0, 1}. return jnp.where(value < 0, jnp.array(0., dtype=self.probs.dtype), jnp.where(value >= 1, jnp.array(1.0, dtype=self.probs.dtype), 1 - self.probs))
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,360
distrax._src.distributions.distribution
cross_entropy
Calculates the cross entropy to another distribution. Args: other_dist: A compatible Distax or TFP Distribution. **kwargs: Additional kwargs. Returns: The cross entropy `H(self || other_dist)`.
def cross_entropy(self, other_dist, **kwargs) -> Array: """Calculates the cross entropy to another distribution. Args: other_dist: A compatible Distax or TFP Distribution. **kwargs: Additional kwargs. Returns: The cross entropy `H(self || other_dist)`. """ return self.kl_divergence(other_dist, **kwargs) + self.entropy()
(self, other_dist, **kwargs) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,361
distrax._src.distributions.bernoulli
entropy
See `Distribution.entropy`.
def entropy(self) -> Array: """See `Distribution.entropy`.""" (probs0, probs1, log_probs0, log_probs1) = _probs_and_log_probs(self) return -1. * ( math.multiply_no_nan(log_probs0, probs0) + math.multiply_no_nan(log_probs1, probs1))
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,362
distrax._src.distributions.distribution
kl_divergence
Calculates the KL divergence to another distribution. Args: other_dist: A compatible Distax or TFP Distribution. **kwargs: Additional kwargs. Returns: The KL divergence `KL(self || other_dist)`.
def kl_divergence(self, other_dist, **kwargs) -> Array: """Calculates the KL divergence to another distribution. Args: other_dist: A compatible Distax or TFP Distribution. **kwargs: Additional kwargs. Returns: The KL divergence `KL(self || other_dist)`. """ return tfd.kullback_leibler.kl_divergence(self, other_dist, **kwargs)
(self, other_dist, **kwargs) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,363
distrax._src.distributions.bernoulli
log_cdf
See `Distribution.log_cdf`.
def log_cdf(self, value: EventT) -> Array: """See `Distribution.log_cdf`.""" return jnp.log(self.cdf(value))
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,364
distrax._src.distributions.bernoulli
log_prob
See `Distribution.log_prob`.
def log_prob(self, value: EventT) -> Array: """See `Distribution.log_prob`.""" log_probs0, log_probs1 = self._log_probs_parameter() return (math.multiply_no_nan(log_probs0, 1 - value) + math.multiply_no_nan(log_probs1, value))
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,365
distrax._src.distributions.distribution
log_survival_function
Evaluates the log of the survival function at `value`. Note that by default we use a numerically not necessarily stable definition of the log of the survival function in terms of the CDF. More stable definitions should be implemented in subclasses for distributions for which they exist. Args: value: An event. Returns: The log of the survival function evaluated at `value`, i.e. log P[X > value]
def log_survival_function(self, value: EventT) -> Array: """Evaluates the log of the survival function at `value`. Note that by default we use a numerically not necessarily stable definition of the log of the survival function in terms of the CDF. More stable definitions should be implemented in subclasses for distributions for which they exist. Args: value: An event. Returns: The log of the survival function evaluated at `value`, i.e. log P[X > value] """ if not self.event_shape: # Defined for univariate distributions only. return jnp.log1p(-self.cdf(value)) else: raise NotImplementedError('`log_survival_function` is not defined for ' f'distribution `{self.name}`.')
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,366
distrax._src.distributions.bernoulli
mean
See `Distribution.mean`.
def mean(self) -> Array: """See `Distribution.mean`.""" return self.probs
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,367
distrax._src.distributions.distribution
median
Calculates the median.
def median(self) -> EventT: """Calculates the median.""" raise NotImplementedError( f'Distribution `{self.name}` does not implement `median`.')
(self) -> ~EventT
55,368
distrax._src.distributions.bernoulli
mode
See `Distribution.probs`.
def mode(self) -> Array: """See `Distribution.probs`.""" return (self.probs > 0.5).astype(self._dtype)
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,369
distrax._src.distributions.bernoulli
prob
See `Distribution.prob`.
def prob(self, value: EventT) -> Array: """See `Distribution.prob`.""" probs1 = self.probs probs0 = 1 - probs1 return (math.multiply_no_nan(probs0, 1 - value) + math.multiply_no_nan(probs1, value))
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,370
distrax._src.distributions.distribution
sample
Samples an event. Args: seed: PRNG key or integer seed. sample_shape: Additional leading dimensions for sample. Returns: A sample of shape `sample_shape + self.batch_shape + self.event_shape`.
def sample(self, *, seed: Union[IntLike, PRNGKey], sample_shape: Union[IntLike, Sequence[IntLike]] = ()) -> EventT: """Samples an event. Args: seed: PRNG key or integer seed. sample_shape: Additional leading dimensions for sample. Returns: A sample of shape `sample_shape + self.batch_shape + self.event_shape`. """ rng, sample_shape = convert_seed_and_sample_shape(seed, sample_shape) num_samples = functools.reduce(operator.mul, sample_shape, 1) # product samples = self._sample_n(rng, num_samples) return jax.tree_util.tree_map( lambda t: t.reshape(sample_shape + t.shape[1:]), samples)
(self, *, seed: Union[int, numpy.int16, numpy.int32, numpy.int64, jax.Array], sample_shape: Union[int, numpy.int16, numpy.int32, numpy.int64, Sequence[Union[int, numpy.int16, numpy.int32, numpy.int64]]] = ()) -> ~EventT
55,371
distrax._src.distributions.distribution
sample_and_log_prob
Returns a sample and associated log probability. See `sample`.
def sample_and_log_prob( self, *, seed: Union[IntLike, PRNGKey], sample_shape: Union[IntLike, Sequence[IntLike]] = () ) -> Tuple[EventT, Array]: """Returns a sample and associated log probability. See `sample`.""" rng, sample_shape = convert_seed_and_sample_shape(seed, sample_shape) num_samples = functools.reduce(operator.mul, sample_shape, 1) # product samples, log_prob = self._sample_n_and_log_prob(rng, num_samples) samples, log_prob = jax.tree_util.tree_map( lambda t: t.reshape(sample_shape + t.shape[1:]), (samples, log_prob)) return samples, log_prob
(self, *, seed: Union[int, numpy.int16, numpy.int32, numpy.int64, jax.Array], sample_shape: Union[int, numpy.int16, numpy.int32, numpy.int64, Sequence[Union[int, numpy.int16, numpy.int32, numpy.int64]]] = ()) -> Tuple[~EventT, Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]]
55,372
distrax._src.distributions.distribution
stddev
Calculates the standard deviation.
def stddev(self) -> EventT: """Calculates the standard deviation.""" return jnp.sqrt(self.variance())
(self) -> ~EventT
55,373
distrax._src.distributions.distribution
survival_function
Evaluates the survival function at `value`. Note that by default we use a numerically not necessarily stable definition of the survival function in terms of the CDF. More stable definitions should be implemented in subclasses for distributions for which they exist. Args: value: An event. Returns: The survival function evaluated at `value`, i.e. P[X > value]
def survival_function(self, value: EventT) -> Array: """Evaluates the survival function at `value`. Note that by default we use a numerically not necessarily stable definition of the survival function in terms of the CDF. More stable definitions should be implemented in subclasses for distributions for which they exist. Args: value: An event. Returns: The survival function evaluated at `value`, i.e. P[X > value] """ if not self.event_shape: # Defined for univariate distributions only. return 1. - self.cdf(value) else: raise NotImplementedError('`survival_function` is not defined for ' f'distribution `{self.name}`.')
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,374
distrax._src.utils.jittable
tree_flatten
null
def tree_flatten(self): leaves, treedef = jax.tree_util.tree_flatten(self.__dict__) switch = list(map(_is_jax_data, leaves)) children = [leaf if s else None for leaf, s in zip(leaves, switch)] metadata = [None if s else leaf for leaf, s in zip(leaves, switch)] return children, (metadata, switch, treedef)
(self)
55,375
distrax._src.distributions.bernoulli
variance
See `Distribution.variance`.
def variance(self) -> Array: """See `Distribution.variance`.""" return (1 - self.probs) * self.probs
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,376
distrax._src.distributions.beta
Beta
Beta distribution with parameters `alpha` and `beta`. The PDF of a Beta distributed random variable `X` is defined on the interval `0 <= X <= 1` and has the form: ``` p(x; alpha, beta) = x ** {alpha - 1} * (1 - x) ** (beta - 1) / B(alpha, beta) ``` where `B(alpha, beta)` is the beta function, and the `alpha, beta > 0` are the shape parameters. Note that the support of the distribution does not include `x = 0` or `x = 1` if `alpha < 1` or `beta < 1`, respectively.
class Beta(distribution.Distribution): """Beta distribution with parameters `alpha` and `beta`. The PDF of a Beta distributed random variable `X` is defined on the interval `0 <= X <= 1` and has the form: ``` p(x; alpha, beta) = x ** {alpha - 1} * (1 - x) ** (beta - 1) / B(alpha, beta) ``` where `B(alpha, beta)` is the beta function, and the `alpha, beta > 0` are the shape parameters. Note that the support of the distribution does not include `x = 0` or `x = 1` if `alpha < 1` or `beta < 1`, respectively. """ equiv_tfp_cls = tfd.Beta def __init__(self, alpha: Numeric, beta: Numeric): """Initializes a Beta distribution. Args: alpha: Shape parameter `alpha` of the distribution. Must be positive. beta: Shape parameter `beta` of the distribution. Must be positive. """ super().__init__() self._alpha = conversion.as_float_array(alpha) self._beta = conversion.as_float_array(beta) self._batch_shape = jax.lax.broadcast_shapes( self._alpha.shape, self._beta.shape) self._log_normalization_constant = math.log_beta(self._alpha, self._beta) @property def event_shape(self) -> Tuple[int, ...]: """Shape of event of distribution samples.""" return () @property def batch_shape(self) -> Tuple[int, ...]: """Shape of batch of distribution samples.""" return self._batch_shape @property def alpha(self) -> Array: """Shape parameter `alpha` of the distribution.""" return jnp.broadcast_to(self._alpha, self.batch_shape) @property def beta(self) -> Array: """Shape parameter `beta` of the distribution.""" return jnp.broadcast_to(self._beta, self.batch_shape) def _sample_n(self, key: PRNGKey, n: int) -> Array: """See `Distribution._sample_n`.""" out_shape = (n,) + self.batch_shape dtype = jnp.result_type(self._alpha, self._beta) rnd = jax.random.beta( key, a=self._alpha, b=self._beta, shape=out_shape, dtype=dtype) return rnd def log_prob(self, value: EventT) -> Array: """See `Distribution.log_prob`.""" result = ((self._alpha - 1.) * jnp.log(value) + (self._beta - 1.) * jnp.log(1. - value) - self._log_normalization_constant) return jnp.where( jnp.logical_or(jnp.logical_and(self._alpha == 1., value == 0.), jnp.logical_and(self._beta == 1., value == 1.)), -self._log_normalization_constant, result ) def cdf(self, value: EventT) -> Array: """See `Distribution.cdf`.""" return jax.scipy.special.betainc(self._alpha, self._beta, value) def log_cdf(self, value: EventT) -> Array: """See `Distribution.log_cdf`.""" return jnp.log(self.cdf(value)) def entropy(self) -> Array: """Calculates the Shannon entropy (in nats).""" return ( self._log_normalization_constant - (self._alpha - 1.) * jax.lax.digamma(self._alpha) - (self._beta - 1.) * jax.lax.digamma(self._beta) + (self._alpha + self._beta - 2.) * jax.lax.digamma( self._alpha + self._beta) ) def mean(self) -> Array: """Calculates the mean.""" return self._alpha / (self._alpha + self._beta) def variance(self) -> Array: """Calculates the variance.""" sum_alpha_beta = self._alpha + self._beta return self._alpha * self._beta / ( jnp.square(sum_alpha_beta) * (sum_alpha_beta + 1.)) def mode(self) -> Array: """Calculates the mode. Returns: The mode, an array of shape `batch_shape`. The mode is not defined if `alpha = beta = 1`, or if `alpha < 1` and `beta < 1`. For these cases, the returned value is `jnp.nan`. """ return jnp.where( jnp.logical_and(self._alpha > 1., self._beta > 1.), (self._alpha - 1.) / (self._alpha + self._beta - 2.), jnp.where( jnp.logical_and(self._alpha <= 1., self._beta > 1.), 0., jnp.where( jnp.logical_and(self._alpha > 1., self._beta <= 1.), 1., jnp.nan))) def __getitem__(self, index) -> 'Beta': """See `Distribution.__getitem__`.""" index = distribution.to_batch_shape_index(self.batch_shape, index) return Beta(alpha=self.alpha[index], beta=self.beta[index])
(alpha: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int], beta: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int])
55,377
distrax._src.distributions.beta
__getitem__
See `Distribution.__getitem__`.
def __getitem__(self, index) -> 'Beta': """See `Distribution.__getitem__`.""" index = distribution.to_batch_shape_index(self.batch_shape, index) return Beta(alpha=self.alpha[index], beta=self.beta[index])
(self, index) -> distrax._src.distributions.beta.Beta
55,378
distrax._src.distributions.beta
__init__
Initializes a Beta distribution. Args: alpha: Shape parameter `alpha` of the distribution. Must be positive. beta: Shape parameter `beta` of the distribution. Must be positive.
def __init__(self, alpha: Numeric, beta: Numeric): """Initializes a Beta distribution. Args: alpha: Shape parameter `alpha` of the distribution. Must be positive. beta: Shape parameter `beta` of the distribution. Must be positive. """ super().__init__() self._alpha = conversion.as_float_array(alpha) self._beta = conversion.as_float_array(beta) self._batch_shape = jax.lax.broadcast_shapes( self._alpha.shape, self._beta.shape) self._log_normalization_constant = math.log_beta(self._alpha, self._beta)
(self, alpha: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int], beta: Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number, float, int])
55,381
distrax._src.distributions.beta
_sample_n
See `Distribution._sample_n`.
def _sample_n(self, key: PRNGKey, n: int) -> Array: """See `Distribution._sample_n`.""" out_shape = (n,) + self.batch_shape dtype = jnp.result_type(self._alpha, self._beta) rnd = jax.random.beta( key, a=self._alpha, b=self._beta, shape=out_shape, dtype=dtype) return rnd
(self, key: jax.Array, n: int) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,383
distrax._src.distributions.beta
cdf
See `Distribution.cdf`.
def cdf(self, value: EventT) -> Array: """See `Distribution.cdf`.""" return jax.scipy.special.betainc(self._alpha, self._beta, value)
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,385
distrax._src.distributions.beta
entropy
Calculates the Shannon entropy (in nats).
def entropy(self) -> Array: """Calculates the Shannon entropy (in nats).""" return ( self._log_normalization_constant - (self._alpha - 1.) * jax.lax.digamma(self._alpha) - (self._beta - 1.) * jax.lax.digamma(self._beta) + (self._alpha + self._beta - 2.) * jax.lax.digamma( self._alpha + self._beta) )
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,388
distrax._src.distributions.beta
log_prob
See `Distribution.log_prob`.
def log_prob(self, value: EventT) -> Array: """See `Distribution.log_prob`.""" result = ((self._alpha - 1.) * jnp.log(value) + (self._beta - 1.) * jnp.log(1. - value) - self._log_normalization_constant) return jnp.where( jnp.logical_or(jnp.logical_and(self._alpha == 1., value == 0.), jnp.logical_and(self._beta == 1., value == 1.)), -self._log_normalization_constant, result )
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,390
distrax._src.distributions.beta
mean
Calculates the mean.
def mean(self) -> Array: """Calculates the mean.""" return self._alpha / (self._alpha + self._beta)
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,392
distrax._src.distributions.beta
mode
Calculates the mode. Returns: The mode, an array of shape `batch_shape`. The mode is not defined if `alpha = beta = 1`, or if `alpha < 1` and `beta < 1`. For these cases, the returned value is `jnp.nan`.
def mode(self) -> Array: """Calculates the mode. Returns: The mode, an array of shape `batch_shape`. The mode is not defined if `alpha = beta = 1`, or if `alpha < 1` and `beta < 1`. For these cases, the returned value is `jnp.nan`. """ return jnp.where( jnp.logical_and(self._alpha > 1., self._beta > 1.), (self._alpha - 1.) / (self._alpha + self._beta - 2.), jnp.where( jnp.logical_and(self._alpha <= 1., self._beta > 1.), 0., jnp.where( jnp.logical_and(self._alpha > 1., self._beta <= 1.), 1., jnp.nan)))
(self) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]
55,393
distrax._src.distributions.distribution
prob
Calculates the probability of an event. Args: value: An event. Returns: The probability P(value).
def prob(self, value: EventT) -> Array: """Calculates the probability of an event. Args: value: An event. Returns: The probability P(value). """ return jnp.exp(self.log_prob(value))
(self, value: ~EventT) -> Union[jax.Array, numpy.ndarray, numpy.bool_, numpy.number]