near_api/signer/
ledger.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use near_crypto::{PublicKey, SecretKey};
use near_primitives::{
    action::delegate::SignedDelegateAction, hash::CryptoHash, transaction::Transaction,
    types::Nonce,
};
use slipped10::BIP32Path;
use tracing::{debug, info, instrument, trace, warn};

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

use super::SignerTrait;

const LEDGER_SIGNER_TARGET: &str = "near_api::signer::ledger";

#[derive(Debug, Clone)]
pub struct LedgerSigner {
    hd_path: BIP32Path,
}

impl LedgerSigner {
    pub const fn new(hd_path: BIP32Path) -> Self {
        Self { hd_path }
    }
}

#[async_trait::async_trait]
impl SignerTrait for LedgerSigner {
    #[instrument(skip(self, tr), fields(signer_id = %tr.signer_id, receiver_id = %tr.receiver_id))]
    async fn sign(
        &self,
        tr: PrepopulateTransaction,
        public_key: PublicKey,
        nonce: Nonce,
        block_hash: CryptoHash,
    ) -> Result<near_primitives::transaction::SignedTransaction, SignerError> {
        debug!(target: LEDGER_SIGNER_TARGET, "Preparing unsigned transaction");
        let mut unsigned_tx = Transaction::new_v0(
            tr.signer_id.clone(),
            public_key,
            tr.receiver_id,
            nonce,
            block_hash,
        );
        *unsigned_tx.actions_mut() = tr.actions;
        let unsigned_tx_bytes = borsh::to_vec(&unsigned_tx).map_err(LedgerError::from)?;
        let hd_path = self.hd_path.clone();

        info!(target: LEDGER_SIGNER_TARGET, "Signing transaction with Ledger");
        let signature = tokio::task::spawn_blocking(move || {
            let unsigned_tx_bytes = unsigned_tx_bytes;
            let signature = near_ledger::sign_transaction(&unsigned_tx_bytes, hd_path)
                .map_err(LedgerError::from)?;

            Ok::<_, LedgerError>(signature)
        })
        .await
        .map_err(LedgerError::from)?;

        let signature = signature?;

        debug!(target: LEDGER_SIGNER_TARGET, "Creating Signature object");
        let signature =
            near_crypto::Signature::from_parts(near_crypto::KeyType::ED25519, &signature)
                .map_err(LedgerError::from)?;

        info!(target: LEDGER_SIGNER_TARGET, "Transaction signed successfully");
        Ok(near_primitives::transaction::SignedTransaction::new(
            signature,
            unsigned_tx,
        ))
    }

    #[instrument(skip(self, tr), fields(signer_id = %tr.signer_id, receiver_id = %tr.receiver_id))]
    async fn sign_meta(
        &self,
        tr: PrepopulateTransaction,
        public_key: PublicKey,
        nonce: Nonce,
        _block_hash: CryptoHash,
        max_block_height: near_primitives::types::BlockHeight,
    ) -> Result<near_primitives::action::delegate::SignedDelegateAction, MetaSignError> {
        debug!(target: LEDGER_SIGNER_TARGET, "Preparing delegate action");
        let actions = tr
            .actions
            .into_iter()
            .map(near_primitives::action::delegate::NonDelegateAction::try_from)
            .collect::<Result<_, _>>()
            .map_err(|_| MetaSignError::DelegateActionIsNotSupported)?;
        let delegate_action = near_primitives::action::delegate::DelegateAction {
            sender_id: tr.signer_id,
            receiver_id: tr.receiver_id,
            actions,
            nonce,
            max_block_height,
            public_key,
        };

        let delegate_action_bytes = borsh::to_vec(&delegate_action)
            .map_err(LedgerError::from)
            .map_err(SignerError::from)?;
        let hd_path = self.hd_path.clone();

        info!(target: LEDGER_SIGNER_TARGET, "Signing delegate action with Ledger");
        let signature = tokio::task::spawn_blocking(move || {
            let delegate_action_bytes = delegate_action_bytes;
            let signature =
                near_ledger::sign_message_nep366_delegate_action(&delegate_action_bytes, hd_path)
                    .map_err(LedgerError::from)?;

            Ok::<_, LedgerError>(signature)
        })
        .await
        .map_err(LedgerError::from)
        .map_err(SignerError::from)?;

        let signature = signature.map_err(SignerError::from)?;

        debug!(target: LEDGER_SIGNER_TARGET, "Creating Signature object for delegate action");
        let signature =
            near_crypto::Signature::from_parts(near_crypto::KeyType::ED25519, &signature)
                .map_err(LedgerError::from)
                .map_err(SignerError::from)?;

        info!(target: LEDGER_SIGNER_TARGET, "Delegate action signed successfully");
        Ok(SignedDelegateAction {
            delegate_action,
            signature,
        })
    }

    fn tx_and_secret(
        &self,
        _tr: PrepopulateTransaction,
        _public_key: PublicKey,
        _nonce: Nonce,
        _block_hash: CryptoHash,
    ) -> Result<(Transaction, SecretKey), SignerError> {
        warn!(target: LEDGER_SIGNER_TARGET, "Attempted to access secret key, which is not available for Ledger signer");
        Err(SignerError::SecretKeyIsNotAvailable)
    }

    #[instrument(skip(self))]
    fn get_public_key(&self) -> Result<PublicKey, SignerError> {
        let public_key = near_ledger::get_wallet_id(self.hd_path.clone())
            .map_err(|_| SignerError::PublicKeyIsNotAvailable)?;

        trace!(target: LEDGER_SIGNER_TARGET, "Public key retrieved successfully");
        Ok(near_crypto::PublicKey::ED25519(
            near_crypto::ED25519PublicKey::from(public_key.to_bytes()),
        ))
    }
}