1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
 * Copyright 2017 Intel Corporation
 * Copyright 2018-2020 Cargill Incorporated
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ------------------------------------------------------------------------------
 */

mod error;
#[cfg(feature = "hash")]
#[cfg_attr(docsrs, doc(cfg(feature = "hash")))]
pub mod hash;
mod hex;
mod key;
pub mod secp256k1;
mod signature;

pub use error::{ContextError, SignatureParseError, SigningError, VerificationError};
pub use key::{KeyParseError, PrivateKey, PublicKey};
pub use signature::Signature;

/// A signer for arbitrary messages
pub trait Signer: Send {
    /// Signs the given message
    fn sign(&self, message: &[u8]) -> Result<Signature, SigningError>;

    /// Returns the signer's public key
    fn public_key(&self) -> Result<PublicKey, SigningError>;

    /// Clone implementation for `Signer`. The implementation of the `Clone` trait for
    /// `Box<dyn Signer>` calls this method.
    fn clone_box(&self) -> Box<dyn Signer>;
}

impl Clone for Box<dyn Signer> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

/// Verifies message signatures
pub trait Verifier: Send {
    /// Verifies that the provided signature is valid for the given message and public key
    fn verify(
        &self,
        message: &[u8],
        signature: &Signature,
        public_key: &PublicKey,
    ) -> Result<bool, VerificationError>;
}

/// A context for creating signers and verifiers
pub trait Context {
    /// Creates a new signer with the given private key
    fn new_signer(&self, key: PrivateKey) -> Box<dyn Signer>;

    /// Creates a new signature verifier
    fn new_verifier(&self) -> Box<dyn Verifier>;

    /// Generates a new random private key
    fn new_random_private_key(&self) -> PrivateKey;

    /// Computes the public key that corresponds to the given private key
    fn get_public_key(&self, private_key: &PrivateKey) -> Result<PublicKey, ContextError>;
}