1use crate::xdr::{
2 self, AccountId, DecoratedSignature, Hash, HashIdPreimage, HashIdPreimageSorobanAuthorization,
3 InvokeHostFunctionOp, Limits, Operation, OperationBody, PublicKey, ScAddress, ScMap, ScSymbol,
4 ScVal, Signature, SignatureHint, SorobanAddressCredentials, SorobanAuthorizationEntry,
5 SorobanAuthorizedFunction, SorobanCredentials, Transaction, TransactionEnvelope,
6 TransactionV1Envelope, Uint256, VecM, WriteXdr,
7};
8use ed25519_dalek::ed25519::signature::Signer as _;
9use sha2::{Digest, Sha256};
10
11use crate::{config::network::Network, print::Print, utils::transaction_hash};
12
13pub mod ledger;
14
15#[cfg(feature = "additional-libs")]
16mod keyring;
17pub mod secure_store;
18
19#[derive(thiserror::Error, Debug)]
20pub enum Error {
21 #[error("Contract addresses are not supported to sign auth entries {address}")]
22 ContractAddressAreNotSupported { address: String },
23 #[error(transparent)]
24 Ed25519(#[from] ed25519_dalek::SignatureError),
25 #[error("Missing signing key for account {address}")]
26 MissingSignerForAddress { address: String },
27 #[error(transparent)]
28 TryFromSlice(#[from] std::array::TryFromSliceError),
29 #[error("User cancelled signing, perhaps need to add -y")]
30 UserCancelledSigning,
31 #[error(transparent)]
32 Xdr(#[from] xdr::Error),
33 #[error("Only Transaction envelope V1 type is supported")]
34 UnsupportedTransactionEnvelopeType,
35 #[error(transparent)]
36 Url(#[from] url::ParseError),
37 #[error(transparent)]
38 Open(#[from] std::io::Error),
39 #[error("Returning a signature from Lab is not yet supported; Transaction can be found and submitted in lab")]
40 ReturningSignatureFromLab,
41 #[error(transparent)]
42 SecureStore(#[from] secure_store::Error),
43 #[error(transparent)]
44 Ledger(#[from] ledger::Error),
45}
46
47fn requires_auth(txn: &Transaction) -> Option<xdr::Operation> {
48 let [op @ Operation {
49 body: OperationBody::InvokeHostFunction(InvokeHostFunctionOp { auth, .. }),
50 ..
51 }] = txn.operations.as_slice()
52 else {
53 return None;
54 };
55 matches!(
56 auth.first().map(|x| &x.root_invocation.function),
57 Some(&SorobanAuthorizedFunction::ContractFn(_))
58 )
59 .then(move || op.clone())
60}
61
62pub fn sign_soroban_authorizations(
65 raw: &Transaction,
66 source_key: &ed25519_dalek::SigningKey,
67 signers: &[ed25519_dalek::SigningKey],
68 signature_expiration_ledger: u32,
69 network_passphrase: &str,
70) -> Result<Option<Transaction>, Error> {
71 let mut tx = raw.clone();
72 let Some(mut op) = requires_auth(&tx) else {
73 return Ok(None);
74 };
75
76 let Operation {
77 body: OperationBody::InvokeHostFunction(ref mut body),
78 ..
79 } = op
80 else {
81 return Ok(None);
82 };
83
84 let network_id = Hash(Sha256::digest(network_passphrase.as_bytes()).into());
85
86 let verification_key = source_key.verifying_key();
87 let source_address = verification_key.as_bytes();
88
89 let signed_auths = body
90 .auth
91 .as_slice()
92 .iter()
93 .map(|raw_auth| {
94 let mut auth = raw_auth.clone();
95 let SorobanAuthorizationEntry {
96 credentials: SorobanCredentials::Address(ref mut credentials),
97 ..
98 } = auth
99 else {
100 return Ok(auth);
102 };
103 let SorobanAddressCredentials { ref address, .. } = credentials;
104
105 let needle = match address {
108 ScAddress::Account(AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(ref a)))) => a,
109 ScAddress::Contract(Hash(c)) => {
110 return Err(Error::MissingSignerForAddress {
113 address: stellar_strkey::Strkey::Contract(stellar_strkey::Contract(*c))
114 .to_string(),
115 });
116 }
117 };
118 let signer = if let Some(s) = signers
119 .iter()
120 .find(|s| needle == s.verifying_key().as_bytes())
121 {
122 s
123 } else if needle == source_address {
124 source_key
126 } else {
127 return Err(Error::MissingSignerForAddress {
129 address: stellar_strkey::Strkey::PublicKeyEd25519(
130 stellar_strkey::ed25519::PublicKey(*needle),
131 )
132 .to_string(),
133 });
134 };
135
136 sign_soroban_authorization_entry(
137 raw_auth,
138 signer,
139 signature_expiration_ledger,
140 &network_id,
141 )
142 })
143 .collect::<Result<Vec<_>, Error>>()?;
144
145 body.auth = signed_auths.try_into()?;
146 tx.operations = vec![op].try_into()?;
147 Ok(Some(tx))
148}
149
150fn sign_soroban_authorization_entry(
151 raw: &SorobanAuthorizationEntry,
152 signer: &ed25519_dalek::SigningKey,
153 signature_expiration_ledger: u32,
154 network_id: &Hash,
155) -> Result<SorobanAuthorizationEntry, Error> {
156 let mut auth = raw.clone();
157 let SorobanAuthorizationEntry {
158 credentials: SorobanCredentials::Address(ref mut credentials),
159 ..
160 } = auth
161 else {
162 return Ok(auth);
164 };
165 let SorobanAddressCredentials { nonce, .. } = credentials;
166
167 let preimage = HashIdPreimage::SorobanAuthorization(HashIdPreimageSorobanAuthorization {
168 network_id: network_id.clone(),
169 invocation: auth.root_invocation.clone(),
170 nonce: *nonce,
171 signature_expiration_ledger,
172 })
173 .to_xdr(Limits::none())?;
174
175 let payload = Sha256::digest(preimage);
176 let signature = signer.sign(&payload);
177
178 let map = ScMap::sorted_from(vec![
179 (
180 ScVal::Symbol(ScSymbol("public_key".try_into()?)),
181 ScVal::Bytes(
182 signer
183 .verifying_key()
184 .to_bytes()
185 .to_vec()
186 .try_into()
187 .map_err(Error::Xdr)?,
188 ),
189 ),
190 (
191 ScVal::Symbol(ScSymbol("signature".try_into()?)),
192 ScVal::Bytes(
193 signature
194 .to_bytes()
195 .to_vec()
196 .try_into()
197 .map_err(Error::Xdr)?,
198 ),
199 ),
200 ])
201 .map_err(Error::Xdr)?;
202 credentials.signature = ScVal::Vec(Some(
203 vec![ScVal::Map(Some(map))].try_into().map_err(Error::Xdr)?,
204 ));
205 credentials.signature_expiration_ledger = signature_expiration_ledger;
206 auth.credentials = SorobanCredentials::Address(credentials.clone());
207 Ok(auth)
208}
209
210pub struct Signer {
211 pub kind: SignerKind,
212 pub print: Print,
213}
214
215#[allow(clippy::module_name_repetitions, clippy::large_enum_variant)]
216pub enum SignerKind {
217 Local(LocalKey),
218 Ledger(ledger::LedgerType),
219 Lab,
220 SecureStore(SecureStoreEntry),
221}
222
223impl Signer {
224 pub async fn sign_tx(
225 &self,
226 tx: Transaction,
227 network: &Network,
228 ) -> Result<TransactionEnvelope, Error> {
229 let tx_env = TransactionEnvelope::Tx(TransactionV1Envelope {
230 tx,
231 signatures: VecM::default(),
232 });
233 self.sign_tx_env(&tx_env, network).await
234 }
235
236 pub async fn sign_tx_env(
237 &self,
238 tx_env: &TransactionEnvelope,
239 network: &Network,
240 ) -> Result<TransactionEnvelope, Error> {
241 match &tx_env {
242 TransactionEnvelope::Tx(TransactionV1Envelope { tx, signatures }) => {
243 let tx_hash = transaction_hash(tx, &network.network_passphrase)?;
244 self.print
245 .infoln(format!("Signing transaction: {}", hex::encode(tx_hash),));
246 let decorated_signature = match &self.kind {
247 SignerKind::Local(key) => key.sign_tx_hash(tx_hash)?,
248 SignerKind::Lab => Lab::sign_tx_env(tx_env, network, &self.print)?,
249 SignerKind::Ledger(ledger) => ledger.sign_transaction_hash(&tx_hash).await?,
250 SignerKind::SecureStore(entry) => entry.sign_tx_hash(tx_hash)?,
251 };
252 let mut sigs = signatures.clone().into_vec();
253 sigs.push(decorated_signature);
254 Ok(TransactionEnvelope::Tx(TransactionV1Envelope {
255 tx: tx.clone(),
256 signatures: sigs.try_into()?,
257 }))
258 }
259 _ => Err(Error::UnsupportedTransactionEnvelopeType),
260 }
261 }
262}
263
264pub struct LocalKey {
265 pub key: ed25519_dalek::SigningKey,
266}
267
268impl LocalKey {
269 pub fn sign_tx_hash(&self, tx_hash: [u8; 32]) -> Result<DecoratedSignature, Error> {
270 let hint = SignatureHint(self.key.verifying_key().to_bytes()[28..].try_into()?);
271 let signature = Signature(self.key.sign(&tx_hash).to_bytes().to_vec().try_into()?);
272 Ok(DecoratedSignature { hint, signature })
273 }
274}
275
276pub struct Lab;
277
278impl Lab {
279 const URL: &str = "https://lab.stellar.org/transaction/cli-sign";
280
281 pub fn sign_tx_env(
282 tx_env: &TransactionEnvelope,
283 network: &Network,
284 printer: &Print,
285 ) -> Result<DecoratedSignature, Error> {
286 let xdr = tx_env.to_xdr_base64(Limits::none())?;
287
288 let mut url = url::Url::parse(Self::URL)?;
289 url.query_pairs_mut()
290 .append_pair("networkPassphrase", &network.network_passphrase)
291 .append_pair("xdr", &xdr);
292 let url = url.to_string();
293
294 printer.globeln(format!("Opening lab to sign transaction: {url}"));
295 open::that(url)?;
296
297 Err(Error::ReturningSignatureFromLab)
298 }
299}
300
301pub struct SecureStoreEntry {
302 pub name: String,
303 pub hd_path: Option<usize>,
304}
305
306impl SecureStoreEntry {
307 pub fn sign_tx_hash(&self, tx_hash: [u8; 32]) -> Result<DecoratedSignature, Error> {
308 let hint = SignatureHint(
309 secure_store::get_public_key(&self.name, self.hd_path)?.0[28..].try_into()?,
310 );
311
312 let signed_tx_hash = secure_store::sign_tx_data(&self.name, self.hd_path, &tx_hash)?;
313
314 let signature = Signature(signed_tx_hash.clone().try_into()?);
315 Ok(DecoratedSignature { hint, signature })
316 }
317}