Package: secp256k1
secp256k1-pyPython FFI bindings forlibsecp256k1(an experimental and optimized C library for EC operations on curve secp256k1).Previously maintained by Ludvig Broberg, now athttps://github.com/rustyrussell/secp256k1-py.Installationpip install secp256k1Precompiled binary packages (wheels)Precompiled binary wheels is available for Python 2.7, 3.3, 3.4, and 3.5 on Linux. To take advantage of those you need to use pip >= 8.1.0.In case you don't want to use the binary packages you can prevent pip from
using them with the following command:pip install --no-binary :all: secp256k1Installation with compilationIf you either can't or don't want to use the binary package options described
above read on to learn what is needed to install the source pacakge.The library bundles its own libsecp256k1 currently, as there is no
versioning to allow us to safely determine compatibility with an
installed library, especially as we also build all the experimental
modules.For the bundled version to compile successfully you need to have a C compiler
as well as the development headers forlibffiandlibgmpinstalled.On Debian / Ubuntu for example the necessary packages are:build-essentialautomakepkg-configlibtoollibffi-devOn OS X the necessary homebrew packages are:automakepkg-configlibtoollibffiCommand line usageGenerate a private key and show the corresponding public key$ python -m secp256k1 privkey -p

a1455c78a922c52f391c5784f8ca1457367fa57f9d7a74fdab7d2c90ca05c02e
Public key: 02477ce3b986ab14d123d6c4167b085f4d08c1569963a0201b2ffc7d9d6086d2f3Sign a message$ python -m secp256k1 sign \
	-k a1455c78a922c52f391c5784f8ca1457367fa57f9d7a74fdab7d2c90ca05c02e \
	-m hello

3045022100a71d86190354d64e5b3eb2bd656313422cdf7def69bf3669cdbfd09a9162c96e0220713b81f3440bff0b639d2f29b2c48494b812fa89b754b7b6cdc9eaa8027cf369Check signature$ python -m secp256k1 checksig \
	-p 02477ce3b986ab14d123d6c4167b085f4d08c1569963a0201b2ffc7d9d6086d2f3 \
	-m hello \
	-s 3045022100a71d86190354d64e5b3eb2bd656313422cdf7def69bf3669cdbfd09a9162c96e0220713b81f3440bff0b639d2f29b2c48494b812fa89b754b7b6cdc9eaa8027cf369

TrueGenerate a signature that allows recovering the public key$ python -m secp256k1 signrec \
	-k a1455c78a922c52f391c5784f8ca1457367fa57f9d7a74fdab7d2c90ca05c02e \
	-m hello

515fe95d0780b11633f3352deb064f1517d58f295a99131e9389da8bfacd64422513d0cd4e18a58d9f4873b592afe54cf63e8f294351d1e612c8a297b5255079 1Recover public key$ python -m secp256k1 recpub \
	-s 515fe95d0780b11633f3352deb064f1517d58f295a99131e9389da8bfacd64422513d0cd4e18a58d9f4873b592afe54cf63e8f294351d1e612c8a297b5255079 \
	-i 1 \
	-m hello

Public key: 02477ce3b986ab14d123d6c4167b085f4d08c1569963a0201b2ffc7d9d6086d2f3It is easier to get started with command line, but it is more common to use this as a library. For that, check the next sections.APIclasssecp256k1.PrivateKey(privkey, raw)ThePrivateKeyclass loads or creates a private key by obtaining 32 bytes from urandom and operates over it.Instantiation parametersprivkey=None- generate a new private key if None, otherwise load a private key.raw=True- ifTrue, it is assumed thatprivkeyis just a sequence of bytes, otherwise it is assumed that it is in the DER format. This is not used whenprivkeyis not specified.Methods and instance attributespubkey: an instance ofsecp256k1.PublicKey.private_key: raw bytes for the private key.set_raw_privkey(privkey)update theprivate_keyfor this instance with the bytes specified byprivkey. Ifprivkeyis invalid, an Exception is raised. Thepubkeyis also updated based on the new private key.serialize()-> bytesconvert the raw bytes present inprivate keyto a hexadecimal string.deserialize(privkey_ser)-> bytesconvert from a hexadecimal string to raw bytes and update thepubkeyandprivate_keyfor this instance.tweak_add(scalar)-> bytestweak the current private key by adding a 32 byte scalar to it and return a new raw private key composed of 32 bytes.tweak_mul(scalar)-> bytestweak the current private key by multiplying it by a 32 byte scalar and return a new raw private key composed of 32 bytes.ecdsa_sign(msg, raw=False, digest=hashlib.sha256)-> internal objectby default, create an ECDSA-SHA256 signature from the bytes inmsg. Ifrawis True, then thedigestfunction is not applied overmsg, otherwise thedigestmust produce 256 bits or anExceptionwill be raised.The returned object is a structure from the C lib. If you want to store it (on a disk or similar), useecdsa_serializeand later on useecdsa_deserializewhen loading.ecdsa_sign_recoverable(msg, raw=False, digest=hashlib.sha256)-> internal objectcreate a recoverable ECDSA signature. Seeecdsa_signfor parameters description.schnorr_sign(msg, bip340tag, raw=False)-> bytescreate a BIP-340 signature formsg;bip340tagshould be a string
or byte value which distinguishes this usage from any other usage of
signatures (e.g. your program name, or full protocol name).  Ifrawis specified, thenbip340tagis not used, and themsg(usually
a 32-byte hash) is signed directly.It produces non-malleable 64-byte signatures which support batch
validation.classsecp256k1.PublicKey(pubkey, raw)ThePublicKeyclass loads an existing public key and operates over it.Instantiation parameterspubkey=None- do not load a public key if None, otherwise do.raw=False- ifFalse, it is assumed thatpubkeyhas gone throughPublicKey.deserializealready, otherwise it must be specified as bytes.Methods and instance attributespublic_key: an internal object representing the public key.serialize(compressed=True)-> bytesconvert thepublic_keyto bytes. Ifcompressedis True, 33 bytes will be produced, otherwise 65 will be.deserialize(pubkey_ser)-> internal objectconvert the bytes resulting from a previousserializecall back to an internal object and update thepublic_keyfor this instance. The length ofpubkey_serdetermines if it was serialized withcompressed=Trueor not. This will raise an Exception if the size is invalid or if the key is invalid.combine(pubkeys)-> internal objectcombine multiple public keys (those returned fromPublicKey.deserialize) and return a public key (which can be serialized as any other regular public key). Thepublic_keyfor this instance is updated to use the resulting combined key. If it is not possible the combine the keys, an Exception is raised.tweak_add(scalar)-> internal objecttweak the current public key by adding a 32 byte scalar times the generator to it and return a new PublicKey instance.tweak_mul(scalar)-> internal objecttweak the current public key by multiplying it by a 32 byte scalar and return a new PublicKey instance.ecdsa_verify(msg, raw_sig, raw=False, digest=hashlib.sha256)-> boolverify an ECDSA signature and return True if the signature is correct, False otherwise.raw_sigis expected to be an object returned fromecdsa_sign(or if it was serialized usingecdsa_serialize, then first run it throughecdsa_deserialize).msg,raw, anddigestare used as described inecdsa_sign.schnorr_verify(msg, schnorr_sig, bip340tag, raw=False)-> boolverify a Schnorr signature and return True if the signature is correct, False otherwise.schnorr_sigis expected to be the result fromschnorr_sign,msg,bip340tagandrawmust match those used inschnorr_sign.ecdh(scalar, hashfn=ffi.NULL, hasharg=ffi.NULL)-> bytescompute an EC Diffie-Hellman secret in constant time. The instancepublic_keyis used as the public point, and thescalarspecified must be composed of 32 bytes. It outputs 32 bytes representing the ECDH secret computed. The hashing function can be overridden, but (unlike libsecp256k1 itself) we insist that it produce 32-bytes of output. If thescalaris invalid, an Exception is raised.classsecp256k1.ECDSATheECDSAclass is intended to be used as a mix in. Its methods can be accessed from anysecp256k1.PrivateKeyorsecp256k1.PublicKeyinstances.Methodsecdsa_serialize(raw_sig)-> bytesconvert the result fromecdsa_signto DER.ecdsa_deserialie(ser_sig)-> internal objectconvert DER bytes to an internal object.ecdsa_serialize_compact(raw_sig)-> bytesconvert the result fromecdsa_signto a compact serialization of 64 bytes.ecdsa_deserialize_compact(ser_sig)-> internal objectconvert a compact serialization of 64 bytes to an internal object.ecdsa_signature_normalize(raw_sig, check_only=False)-> (bool, internal object | None)check and optionally convert a signature to a normalized lower-S form. Ifcheck_onlyis True then the normalized signature is not returned.This function always return a tuple containing a boolean (True if not previously normalized or False if signature was already normalized), and the normalized signature. Whencheck_onlyis True, the normalized signature returned is always None.ecdsa_recover(msg, recover_sig, raw=False, digest=hashlib.sha256)-> internal objectrecover an ECDSA public key from a signature generated byecdsa_sign_recoverable.recover_sigis expected to be an object returned fromecdsa_sign_recoverable(or if it was serialized usingecdsa_recoverable_serialize, then first run it throughecdsa_recoverable_deserialize).msg,raw, anddigestare used as described inecdsa_sign.ecdsa_recoverable_serialize(recover_sig)-> (bytes, int)convert the result fromecdsa_sign_recoverableto a tuple composed of 65 bytesand an integer denominated as recovery id.ecdsa_recoverable_deserialize(ser_sig, rec_id)-> internal objectconvert the result fromecdsa_recoverable_serializeback to an internal object that can be used byecdsa_recover.ecdsa_recoverable_convert(recover_sig)-> internal objectconvert a recoverable signature to a normal signature, i.e. one that can be used byecdsa_serializeand related methods.Examplefromsecp256k1importPrivateKey,PublicKeyprivkey=PrivateKey()privkey_der=privkey.serialize()assertprivkey.deserialize(privkey_der)==privkey.private_keysig=privkey.ecdsa_sign(b'hello')verified=privkey.pubkey.ecdsa_verify(b'hello',sig)assertverifiedsig_der=privkey.ecdsa_serialize(sig)sig2=privkey.ecdsa_deserialize(sig_der)vrf2=privkey.pubkey.ecdsa_verify(b'hello',sig2)assertvrf2pubkey=privkey.pubkeypub=pubkey.serialize()pubkey2=PublicKey(pub,raw=True)assertpubkey2.serialize()==pubassertpubkey2.ecdsa_verify(b'hello',sig)fromsecp256k1importPrivateKeykey='31a84594060e103f5a63eb742bd46cf5f5900d8406e2726dedfc61c7cf43ebad'msg='9e5755ec2f328cc8635a55415d0e9a09c2b6f2c9b0343c945fbbfe08247a4cbe'sig='30440220132382ca59240c2e14ee7ff61d90fc63276325f4cbe8169fc53ade4a407c2fc802204d86fbe3bde6975dd5a91fdc95ad6544dcdf0dab206f02224ce7e2b151bd82ab'privkey=PrivateKey(bytes(bytearray.fromhex(key)),raw=True)sig_check=privkey.ecdsa_sign(bytes(bytearray.fromhex(msg)),raw=True)sig_ser=privkey.ecdsa_serialize(sig_check)assertsig_ser==bytes(bytearray.fromhex(sig))fromsecp256k1importPrivateKeykey='7ccca75d019dbae79ac4266501578684ee64eeb3c9212105f7a3bdc0ddb0f27e'pub_compressed='03e9a06e539d6bf5cf1ca5c41b59121fa3df07a338322405a312c67b6349a707e9'pub_uncompressed='04e9a06e539d6bf5cf1ca5c41b59121fa3df07a338322405a312c67b6349a707e94c181c5fe89306493dd5677143a329065606740ee58b873e01642228a09ecf9d'privkey=PrivateKey(bytes(bytearray.fromhex(key)))pubkey_ser=privkey.pubkey.serialize()pubkey_ser_uncompressed=privkey.pubkey.serialize(compressed=False)assertpubkey_ser==bytes(bytearray.fromhex(pub_compressed))assertpubkey_ser_uncompressed==bytes(bytearray.fromhex(pub_uncompressed))Technical details about the bundled libsecp256k1The bundling of libsecp256k1 is handled by the various setup.py build phases:During 'sdist':
If the directorylibsecp256k1doesn't exist in the
source directory it is downloaded from the location specified
by theLIB_TARBALL_URLconstant insetup.pyand extracted into
a directory calledlibsecp256k1To upgrade to a newer version of the bundled libsecp256k1 source
simply delete thelibsecp256k1directory and update theLIB_TARBALL_URLto point to a newer commit.During 'install':
To support (future) use of system libsecp256k1, and because of the
way the way cffi modules are implemented it is necessary
to perform system library detection in the cffi build module_cffi_build/build.pyas well as insetup.py. For that reason
some utility functions have been moved into asetup_support.pymodule which is imported from both.By default, the bundled source code is used to build a library
locally that will be statically linked into the CFFI extension.You can set the environment variableSECP_BUNDLED_NO_EXPERIMENTALto disable all experimental modules except therecoverymodule.