-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathmod.rs
More file actions
377 lines (339 loc) · 13.8 KB
/
mod.rs
File metadata and controls
377 lines (339 loc) · 13.8 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use crate::{
utils::fee_bump_transaction_hash,
xdr::{
self, AccountId, DecoratedSignature, FeeBumpTransactionEnvelope, Hash, HashIdPreimage,
HashIdPreimageSorobanAuthorization, Limits, Operation, OperationBody, PublicKey, ScAddress,
ScMap, ScSymbol, ScVal, Signature, SignatureHint, SorobanAddressCredentials,
SorobanAuthorizationEntry, SorobanCredentials, Transaction, TransactionEnvelope,
TransactionV1Envelope, Uint256, VecM, WriteXdr,
},
};
use ed25519_dalek::{ed25519::signature::Signer as _, Signature as Ed25519Signature};
use sha2::{Digest, Sha256};
use crate::{config::network::Network, print::Print, utils::transaction_hash};
pub mod ledger;
#[cfg(feature = "additional-libs")]
mod keyring;
pub mod secure_store;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("Contract addresses are not supported to sign auth entries {address}")]
ContractAddressAreNotSupported { address: String },
#[error(transparent)]
Ed25519(#[from] ed25519_dalek::SignatureError),
#[error("Missing signing key for account {address}")]
MissingSignerForAddress { address: String },
#[error(transparent)]
TryFromSlice(#[from] std::array::TryFromSliceError),
#[error("User cancelled signing, perhaps need to add -y")]
UserCancelledSigning,
#[error(transparent)]
Xdr(#[from] xdr::Error),
#[error("Transaction envelope type not supported")]
UnsupportedTransactionEnvelopeType,
#[error(transparent)]
Url(#[from] url::ParseError),
#[error(transparent)]
Open(#[from] std::io::Error),
#[error("Returning a signature from Lab is not yet supported; Transaction can be found and submitted in lab")]
ReturningSignatureFromLab,
#[error(transparent)]
SecureStore(#[from] secure_store::Error),
#[error(transparent)]
Ledger(#[from] ledger::Error),
#[error(transparent)]
Decode(#[from] stellar_strkey::DecodeError),
}
/// Sign all SorobanAuthorizationEntry's in the transaction with the given signers. Returns a new
/// transaction with the signatures added to each SorobanAuthorizationEntry.
///
/// If no SorobanAuthorizationEntry's need signing (including if none exist), return Ok(None).
///
/// If a SorobanAuthorizationEntry needs signing, but a signature cannot be produced for it,
/// return an Error
pub fn sign_soroban_authorizations(
raw: &Transaction,
signers: &[Signer],
signature_expiration_ledger: u32,
network_passphrase: &str,
) -> Result<Option<Transaction>, Error> {
// Check if we have exactly one operation and it's InvokeHostFunction
let [op @ Operation {
body: OperationBody::InvokeHostFunction(body),
..
}] = raw.operations.as_slice()
else {
return Ok(None);
};
let network_id = Hash(Sha256::digest(network_passphrase.as_bytes()).into());
let mut signed_auths = Vec::with_capacity(body.auth.len());
for raw_auth in body.auth.as_slice() {
let mut auth = raw_auth.clone();
let SorobanAuthorizationEntry {
credentials: SorobanCredentials::Address(ref mut credentials),
..
} = auth
else {
// Doesn't need special signing
signed_auths.push(auth);
continue;
};
let SorobanAddressCredentials { ref address, .. } = credentials;
// See if we have a signer for this authorizationEntry
// If not, then we Error
let needle: &[u8; 32] = match address {
ScAddress::MuxedAccount(_) => todo!("muxed accounts are not supported"),
ScAddress::ClaimableBalance(_) => todo!("claimable balance not supported"),
ScAddress::LiquidityPool(_) => todo!("liquidity pool not supported"),
ScAddress::Account(AccountId(PublicKey::PublicKeyTypeEd25519(Uint256(ref a)))) => a,
ScAddress::Contract(stellar_xdr::curr::ContractId(Hash(c))) => {
// This address is for a contract. This means we're using a custom
// smart-contract account. Currently the CLI doesn't support that yet.
return Err(Error::MissingSignerForAddress {
address: stellar_strkey::Strkey::Contract(stellar_strkey::Contract(*c))
.to_string(),
});
}
};
let mut signer: Option<&Signer> = None;
for s in signers {
if needle == &s.get_public_key()?.0 {
signer = Some(s);
}
}
match signer {
Some(signer) => {
let signed_entry = sign_soroban_authorization_entry(
raw_auth,
signer,
signature_expiration_ledger,
&network_id,
)?;
signed_auths.push(signed_entry);
}
None => {
return Err(Error::MissingSignerForAddress {
address: stellar_strkey::Strkey::PublicKeyEd25519(
stellar_strkey::ed25519::PublicKey(*needle),
)
.to_string(),
});
}
}
}
// No signatures were made, return None to indicate no change to the transaction
if signed_auths.is_empty() {
return Ok(None);
}
// Build updated transaction with signed auth entries
let mut updated_op = op.clone();
if let OperationBody::InvokeHostFunction(ref mut updated_body) = updated_op.body {
let mut tx = raw.clone();
updated_body.auth = signed_auths.try_into()?;
tx.operations = vec![updated_op].try_into()?;
Ok(Some(tx))
} else {
Ok(None)
}
}
fn sign_soroban_authorization_entry(
raw: &SorobanAuthorizationEntry,
signer: &Signer,
signature_expiration_ledger: u32,
network_id: &Hash,
) -> Result<SorobanAuthorizationEntry, Error> {
let mut auth = raw.clone();
let SorobanAuthorizationEntry {
credentials: SorobanCredentials::Address(ref mut credentials),
..
} = auth
else {
// Doesn't need special signing
return Ok(auth);
};
let SorobanAddressCredentials { nonce, .. } = credentials;
let preimage = HashIdPreimage::SorobanAuthorization(HashIdPreimageSorobanAuthorization {
network_id: network_id.clone(),
invocation: auth.root_invocation.clone(),
nonce: *nonce,
signature_expiration_ledger,
})
.to_xdr(Limits::none())?;
let payload = Sha256::digest(preimage);
let p: [u8; 32] = payload.as_slice().try_into()?;
let signature = signer.sign_payload(p)?;
let public_key_vec = signer.get_public_key()?.0.to_vec();
let map = ScMap::sorted_from(vec![
(
ScVal::Symbol(ScSymbol("public_key".try_into()?)),
ScVal::Bytes(public_key_vec.try_into().map_err(Error::Xdr)?),
),
(
ScVal::Symbol(ScSymbol("signature".try_into()?)),
ScVal::Bytes(
signature
.to_bytes()
.to_vec()
.try_into()
.map_err(Error::Xdr)?,
),
),
])
.map_err(Error::Xdr)?;
credentials.signature = ScVal::Vec(Some(
vec![ScVal::Map(Some(map))].try_into().map_err(Error::Xdr)?,
));
credentials.signature_expiration_ledger = signature_expiration_ledger;
auth.credentials = SorobanCredentials::Address(credentials.clone());
Ok(auth)
}
pub struct Signer {
pub kind: SignerKind,
pub print: Print,
}
#[allow(clippy::module_name_repetitions, clippy::large_enum_variant)]
pub enum SignerKind {
Local(LocalKey),
Ledger(ledger::LedgerType),
Lab,
SecureStore(SecureStoreEntry),
}
// It is advised to use the sign_with module, which handles creating a Signer with the appropriate SignerKind
impl Signer {
pub async fn sign_tx(
&self,
tx: Transaction,
network: &Network,
) -> Result<TransactionEnvelope, Error> {
let tx_env = TransactionEnvelope::Tx(TransactionV1Envelope {
tx,
signatures: VecM::default(),
});
self.sign_tx_env(&tx_env, network).await
}
pub async fn sign_tx_env(
&self,
tx_env: &TransactionEnvelope,
network: &Network,
) -> Result<TransactionEnvelope, Error> {
match &tx_env {
TransactionEnvelope::Tx(TransactionV1Envelope { tx, signatures }) => {
let tx_hash = transaction_hash(tx, &network.network_passphrase)?;
self.print
.infoln(format!("Signing transaction: {}", hex::encode(tx_hash),));
let decorated_signature = self.sign_tx_hash(tx_hash, tx_env, network).await?;
let mut sigs = signatures.clone().into_vec();
sigs.push(decorated_signature);
Ok(TransactionEnvelope::Tx(TransactionV1Envelope {
tx: tx.clone(),
signatures: sigs.try_into()?,
}))
}
TransactionEnvelope::TxFeeBump(FeeBumpTransactionEnvelope { tx, signatures }) => {
let tx_hash = fee_bump_transaction_hash(tx, &network.network_passphrase)?;
self.print.infoln(format!(
"Signing fee bump transaction: {}",
hex::encode(tx_hash),
));
let decorated_signature = self.sign_tx_hash(tx_hash, tx_env, network).await?;
let mut sigs = signatures.clone().into_vec();
sigs.push(decorated_signature);
Ok(TransactionEnvelope::TxFeeBump(FeeBumpTransactionEnvelope {
tx: tx.clone(),
signatures: sigs.try_into()?,
}))
}
TransactionEnvelope::TxV0(_) => Err(Error::UnsupportedTransactionEnvelopeType),
}
}
// when we implement this for ledger we'll need it to be async so we can await for the ledger's public key
pub fn get_public_key(&self) -> Result<stellar_strkey::ed25519::PublicKey, Error> {
match &self.kind {
SignerKind::Local(local_key) => Ok(stellar_strkey::ed25519::PublicKey::from_payload(
local_key.key.verifying_key().as_bytes(),
)?),
SignerKind::Ledger(_ledger) => todo!("ledger device is not implemented"),
SignerKind::Lab => Err(Error::ReturningSignatureFromLab),
SignerKind::SecureStore(secure_store_entry) => secure_store_entry.get_public_key(),
}
}
// when we implement this for ledger we'll need it to be async so we can await the user approved the tx on the ledger device
pub fn sign_payload(&self, payload: [u8; 32]) -> Result<Ed25519Signature, Error> {
match &self.kind {
SignerKind::Local(local_key) => local_key.sign_payload(payload),
SignerKind::Ledger(_ledger) => todo!("ledger device is not implemented"),
SignerKind::Lab => Err(Error::ReturningSignatureFromLab),
SignerKind::SecureStore(secure_store_entry) => secure_store_entry.sign_payload(payload),
}
}
async fn sign_tx_hash(
&self,
tx_hash: [u8; 32],
tx_env: &TransactionEnvelope,
network: &Network,
) -> Result<DecoratedSignature, Error> {
match &self.kind {
SignerKind::Local(key) => key.sign_tx_hash(tx_hash),
SignerKind::Lab => Lab::sign_tx_env(tx_env, network, &self.print),
SignerKind::Ledger(ledger) => ledger
.sign_transaction_hash(&tx_hash)
.await
.map_err(Error::from),
SignerKind::SecureStore(entry) => entry.sign_tx_hash(tx_hash),
}
}
}
pub struct LocalKey {
pub key: ed25519_dalek::SigningKey,
}
impl LocalKey {
pub fn sign_tx_hash(&self, tx_hash: [u8; 32]) -> Result<DecoratedSignature, Error> {
let hint = SignatureHint(self.key.verifying_key().to_bytes()[28..].try_into()?);
let signature = Signature(self.key.sign(&tx_hash).to_bytes().to_vec().try_into()?);
Ok(DecoratedSignature { hint, signature })
}
pub fn sign_payload(&self, payload: [u8; 32]) -> Result<Ed25519Signature, Error> {
Ok(self.key.sign(&payload))
}
}
pub struct Lab;
impl Lab {
const URL: &str = "https://lab.stellar.org/transaction/cli-sign";
pub fn sign_tx_env(
tx_env: &TransactionEnvelope,
network: &Network,
printer: &Print,
) -> Result<DecoratedSignature, Error> {
let xdr = tx_env.to_xdr_base64(Limits::none())?;
let mut url = url::Url::parse(Self::URL)?;
url.query_pairs_mut()
.append_pair("networkPassphrase", &network.network_passphrase)
.append_pair("xdr", &xdr);
let url = url.to_string();
printer.globeln(format!("Opening lab to sign transaction: {url}"));
open::that(url)?;
Err(Error::ReturningSignatureFromLab)
}
}
pub struct SecureStoreEntry {
pub name: String,
pub hd_path: Option<usize>,
}
impl SecureStoreEntry {
pub fn get_public_key(&self) -> Result<stellar_strkey::ed25519::PublicKey, Error> {
Ok(secure_store::get_public_key(&self.name, self.hd_path)?)
}
pub fn sign_tx_hash(&self, tx_hash: [u8; 32]) -> Result<DecoratedSignature, Error> {
let hint = SignatureHint(
secure_store::get_public_key(&self.name, self.hd_path)?.0[28..].try_into()?,
);
let signed_tx_hash = secure_store::sign_tx_data(&self.name, self.hd_path, &tx_hash)?;
let signature = Signature(signed_tx_hash.clone().try_into()?);
Ok(DecoratedSignature { hint, signature })
}
pub fn sign_payload(&self, payload: [u8; 32]) -> Result<Ed25519Signature, Error> {
let signed_bytes = secure_store::sign_tx_data(&self.name, self.hd_path, &payload)?;
let sig = Ed25519Signature::from_bytes(signed_bytes.as_slice().try_into()?);
Ok(sig)
}
}