def verify(self, signature, digest) -> bool: """ Verify that a signature is valid for a 32 byte digest. """ if len(signature) != 64: raise ValueError('Signature must be 64 bytes long.') if len(digest) != 32: raise ValueError('Digest must be 32 bytes long.') key = self.verifying_key raw_signature = libsecp256k1_ffi.new('secp256k1_ecdsa_signature *') parsed = libsecp256k1.secp256k1_ecdsa_signature_parse_compact( key.context.ctx, raw_signature, signature) assert parsed == 1 normalized_signature = libsecp256k1_ffi.new( 'secp256k1_ecdsa_signature *') libsecp256k1.secp256k1_ecdsa_signature_normalize( key.context.ctx, normalized_signature, raw_signature) verified = libsecp256k1.secp256k1_ecdsa_verify(key.context.ctx, normalized_signature, digest, key.public_key) return bool(verified)
def sign_compact(self, digest): """ Produce a compact signature. """ key = self.signing_key signature = libsecp256k1_ffi.new('secp256k1_ecdsa_signature *') signed = libsecp256k1.secp256k1_ecdsa_sign(key.context.ctx, signature, digest, key.secret, libsecp256k1_ffi.NULL, libsecp256k1_ffi.NULL) if not signed: raise ValueError('The private key was invalid.') serialized = libsecp256k1_ffi.new('unsigned char[%d]' % CDATA_SIG_LENGTH) compacted = libsecp256k1.secp256k1_ecdsa_signature_serialize_compact( key.context.ctx, serialized, signature) if compacted != 1: raise ValueError('The signature could not be compacted.') return bytes(libsecp256k1_ffi.buffer(serialized, CDATA_SIG_LENGTH))