near_api/signer/
secret_key.rs

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
use near_crypto::{PublicKey, SecretKey};
use near_primitives::{transaction::Transaction, types::Nonce};
use tracing::{debug, instrument, trace};

use crate::{
    errors::SignerError,
    types::{transactions::PrepopulateTransaction, CryptoHash},
};

use super::SignerTrait;

const SECRET_KEY_SIGNER_TARGET: &str = "near_api::signer::secret_key";

#[derive(Debug, Clone)]
pub struct SecretKeySigner {
    secret_key: SecretKey,
    public_key: PublicKey,
}

#[async_trait::async_trait]
impl SignerTrait for SecretKeySigner {
    #[instrument(skip(self, tr), fields(signer_id = %tr.signer_id, receiver_id = %tr.receiver_id))]
    fn tx_and_secret(
        &self,
        tr: PrepopulateTransaction,
        public_key: PublicKey,
        nonce: Nonce,
        block_hash: CryptoHash,
    ) -> Result<(Transaction, SecretKey), SignerError> {
        debug!(target: SECRET_KEY_SIGNER_TARGET, "Creating transaction");
        let mut transaction = Transaction::new_v0(
            tr.signer_id.clone(),
            public_key,
            tr.receiver_id,
            nonce,
            block_hash.into(),
        );
        *transaction.actions_mut() = tr.actions;

        trace!(target: SECRET_KEY_SIGNER_TARGET, "Transaction created, returning with secret key");
        Ok((transaction, self.secret_key.clone()))
    }

    #[instrument(skip(self))]
    fn get_public_key(&self) -> Result<PublicKey, SignerError> {
        Ok(self.public_key.clone())
    }
}

impl SecretKeySigner {
    pub fn new(secret_key: SecretKey) -> Self {
        let public_key = secret_key.public_key();
        Self {
            secret_key,
            public_key,
        }
    }
}