clone_solana_transaction/lib.rs
1#![cfg_attr(feature = "frozen-abi", feature(min_specialization))]
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3//! Atomically-committed sequences of instructions.
4//!
5//! While [`Instruction`]s are the basic unit of computation in Solana, they are
6//! submitted by clients in [`Transaction`]s containing one or more
7//! instructions, and signed by one or more [`Signer`]s. Solana executes the
8//! instructions in a transaction in order, and only commits any changes if all
9//! instructions terminate without producing an error or exception.
10//!
11//! Transactions do not directly contain their instructions but instead include
12//! a [`Message`], a precompiled representation of a sequence of instructions.
13//! `Message`'s constructors handle the complex task of reordering the
14//! individual lists of accounts required by each instruction into a single flat
15//! list of deduplicated accounts required by the Solana runtime. The
16//! `Transaction` type has constructors that build the `Message` so that clients
17//! don't need to interact with them directly.
18//!
19//! Prior to submission to the network, transactions must be signed by one or
20//! more keypairs, and this signing is typically performed by an abstract
21//! [`Signer`], which may be a [`Keypair`] but may also be other types of
22//! signers including remote wallets, such as Ledger devices, as represented by
23//! the [`RemoteKeypair`] type in the [`solana-remote-wallet`] crate.
24//!
25//! [`Signer`]: https://docs.rs/solana-signer/latest/clone_solana_signer/trait.Signer.html
26//! [`Keypair`]: https://docs.rs/solana-keypair/latest/clone_solana_keypair/struct.Keypair.html
27//! [`solana-remote-wallet`]: https://docs.rs/solana-remote-wallet/latest/
28//! [`RemoteKeypair`]: https://docs.rs/solana-remote-wallet/latest/clone_solana_remote_wallet/remote_keypair/struct.RemoteKeypair.html
29//!
30//! Every transaction must be signed by a fee-paying account, the account from
31//! which the cost of executing the transaction is withdrawn. Other required
32//! signatures are determined by the requirements of the programs being executed
33//! by each instruction, and are conventionally specified by that program's
34//! documentation.
35//!
36//! When signing a transaction, a recent blockhash must be provided (which can
37//! be retrieved with [`RpcClient::get_latest_blockhash`]). This allows
38//! validators to drop old but unexecuted transactions; and to distinguish
39//! between accidentally duplicated transactions and intentionally duplicated
40//! transactions — any identical transactions will not be executed more
41//! than once, so updating the blockhash between submitting otherwise identical
42//! transactions makes them unique. If a client must sign a transaction long
43//! before submitting it to the network, then it can use the _[durable
44//! transaction nonce]_ mechanism instead of a recent blockhash to ensure unique
45//! transactions.
46//!
47//! [`RpcClient::get_latest_blockhash`]: https://docs.rs/solana-rpc-client/latest/clone_solana_rpc_client/rpc_client/struct.RpcClient.html#method.get_latest_blockhash
48//! [durable transaction nonce]: https://docs.solanalabs.com/implemented-proposals/durable-tx-nonces
49//!
50//! # Examples
51//!
52//! This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
53//!
54//! [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
55//! [`anyhow`]: https://docs.rs/anyhow
56//!
57//! ```
58//! # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
59//! use anyhow::Result;
60//! use borsh::{BorshSerialize, BorshDeserialize};
61//! use clone_solana_instruction::Instruction;
62//! use clone_solana_keypair::Keypair;
63//! use clone_solana_message::Message;
64//! use clone_solana_pubkey::Pubkey;
65//! use clone_solana_rpc_client::rpc_client::RpcClient;
66//! use clone_solana_signer::Signer;
67//! use clone_solana_transaction::Transaction;
68//!
69//! // A custom program instruction. This would typically be defined in
70//! // another crate so it can be shared between the on-chain program and
71//! // the client.
72//! #[derive(BorshSerialize, BorshDeserialize)]
73//! enum BankInstruction {
74//! Initialize,
75//! Deposit { lamports: u64 },
76//! Withdraw { lamports: u64 },
77//! }
78//!
79//! fn send_initialize_tx(
80//! client: &RpcClient,
81//! program_id: Pubkey,
82//! payer: &Keypair
83//! ) -> Result<()> {
84//!
85//! let bank_instruction = BankInstruction::Initialize;
86//!
87//! let instruction = Instruction::new_with_borsh(
88//! program_id,
89//! &bank_instruction,
90//! vec![],
91//! );
92//!
93//! let blockhash = client.get_latest_blockhash()?;
94//! let mut tx = Transaction::new_signed_with_payer(
95//! &[instruction],
96//! Some(&payer.pubkey()),
97//! &[payer],
98//! blockhash,
99//! );
100//! client.send_and_confirm_transaction(&tx)?;
101//!
102//! Ok(())
103//! }
104//! #
105//! # let client = RpcClient::new(String::new());
106//! # let program_id = Pubkey::new_unique();
107//! # let payer = Keypair::new();
108//! # send_initialize_tx(&client, program_id, &payer)?;
109//! #
110//! # Ok::<(), anyhow::Error>(())
111//! ```
112
113#[cfg(target_arch = "wasm32")]
114use wasm_bindgen::prelude::wasm_bindgen;
115#[cfg(feature = "bincode")]
116use {
117 clone_solana_bincode::limited_deserialize,
118 clone_solana_hash::Hash,
119 clone_solana_message::compiled_instruction::CompiledInstruction,
120 clone_solana_sdk_ids::system_program,
121 clone_solana_signer::{signers::Signers, SignerError},
122 clone_solana_system_interface::instruction::SystemInstruction,
123};
124use {
125 clone_solana_instruction::Instruction,
126 clone_solana_message::Message,
127 clone_solana_pubkey::Pubkey,
128 clone_solana_sanitize::{Sanitize, SanitizeError},
129 clone_solana_signature::Signature,
130 clone_solana_transaction_error::{TransactionError, TransactionResult as Result},
131 std::result,
132};
133#[cfg(feature = "serde")]
134use {
135 clone_solana_short_vec as short_vec,
136 serde_derive::{Deserialize, Serialize},
137};
138
139pub mod sanitized;
140pub mod simple_vote_transaction_checker;
141pub mod versioned;
142mod wasm;
143
144#[derive(PartialEq, Eq, Clone, Copy, Debug)]
145pub enum TransactionVerificationMode {
146 HashOnly,
147 HashAndVerifyPrecompiles,
148 FullVerification,
149}
150
151// inlined to avoid solana-nonce dep
152#[cfg(test)]
153static_assertions::const_assert_eq!(
154 NONCED_TX_MARKER_IX_INDEX,
155 clone_solana_nonce::NONCED_TX_MARKER_IX_INDEX
156);
157#[cfg(feature = "bincode")]
158const NONCED_TX_MARKER_IX_INDEX: u8 = 0;
159// inlined to avoid solana-packet dep
160#[cfg(test)]
161static_assertions::const_assert_eq!(PACKET_DATA_SIZE, clone_solana_packet::PACKET_DATA_SIZE);
162#[cfg(feature = "bincode")]
163const PACKET_DATA_SIZE: usize = 1280 - 40 - 8;
164
165/// An atomically-committed sequence of instructions.
166///
167/// While [`Instruction`]s are the basic unit of computation in Solana,
168/// they are submitted by clients in [`Transaction`]s containing one or
169/// more instructions, and signed by one or more [`Signer`]s.
170///
171/// [`Signer`]: https://docs.rs/solana-signer/latest/clone_solana_signer/trait.Signer.html
172///
173/// See the [module documentation] for more details about transactions.
174///
175/// [module documentation]: self
176///
177/// Some constructors accept an optional `payer`, the account responsible for
178/// paying the cost of executing a transaction. In most cases, callers should
179/// specify the payer explicitly in these constructors. In some cases though,
180/// the caller is not _required_ to specify the payer, but is still allowed to:
181/// in the [`Message`] structure, the first account is always the fee-payer, so
182/// if the caller has knowledge that the first account of the constructed
183/// transaction's `Message` is both a signer and the expected fee-payer, then
184/// redundantly specifying the fee-payer is not strictly required.
185#[cfg(not(target_arch = "wasm32"))]
186#[cfg_attr(
187 feature = "frozen-abi",
188 derive(clone_solana_frozen_abi_macro::AbiExample),
189 clone_solana_frozen_abi_macro::frozen_abi(
190 digest = "76BDTr3Xm3VP7h4eSiw6pZHKc5yYewDufyia3Yedh6GG"
191 )
192)]
193#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
194#[derive(Debug, PartialEq, Default, Eq, Clone)]
195pub struct Transaction {
196 /// A set of signatures of a serialized [`Message`], signed by the first
197 /// keys of the `Message`'s [`account_keys`], where the number of signatures
198 /// is equal to [`num_required_signatures`] of the `Message`'s
199 /// [`MessageHeader`].
200 ///
201 /// [`account_keys`]: https://docs.rs/solana-message/latest/clone_solana_message/legacy/struct.Message.html#structfield.account_keys
202 /// [`MessageHeader`]: https://docs.rs/solana-message/latest/clone_solana_message/struct.MessageHeader.html
203 /// [`num_required_signatures`]: https://docs.rs/solana-message/latest/clone_solana_message/struct.MessageHeader.html#structfield.num_required_signatures
204 // NOTE: Serialization-related changes must be paired with the direct read at sigverify.
205 #[cfg_attr(feature = "serde", serde(with = "short_vec"))]
206 pub signatures: Vec<Signature>,
207
208 /// The message to sign.
209 pub message: Message,
210}
211
212/// wasm-bindgen version of the Transaction struct.
213/// This duplication is required until https://github.com/rustwasm/wasm-bindgen/issues/3671
214/// is fixed. This must not diverge from the regular non-wasm Transaction struct.
215#[cfg(target_arch = "wasm32")]
216#[wasm_bindgen]
217#[cfg_attr(
218 feature = "frozen-abi",
219 derive(AbiExample),
220 frozen_abi(digest = "H7xQFcd1MtMv9QKZWGatBAXwhg28tpeX59P3s8ZZLAY4")
221)]
222#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
223#[derive(Debug, PartialEq, Default, Eq, Clone)]
224pub struct Transaction {
225 #[wasm_bindgen(skip)]
226 #[cfg_attr(feature = "serde", serde(with = "short_vec"))]
227 pub signatures: Vec<Signature>,
228
229 #[wasm_bindgen(skip)]
230 pub message: Message,
231}
232
233impl Sanitize for Transaction {
234 fn sanitize(&self) -> result::Result<(), SanitizeError> {
235 if self.message.header.num_required_signatures as usize > self.signatures.len() {
236 return Err(SanitizeError::IndexOutOfBounds);
237 }
238 if self.signatures.len() > self.message.account_keys.len() {
239 return Err(SanitizeError::IndexOutOfBounds);
240 }
241 self.message.sanitize()
242 }
243}
244
245impl Transaction {
246 /// Create an unsigned transaction from a [`Message`].
247 ///
248 /// # Examples
249 ///
250 /// This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
251 ///
252 /// [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
253 /// [`anyhow`]: https://docs.rs/anyhow
254 ///
255 /// ```
256 /// # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
257 /// use anyhow::Result;
258 /// use borsh::{BorshSerialize, BorshDeserialize};
259 /// use clone_solana_instruction::Instruction;
260 /// use clone_solana_keypair::Keypair;
261 /// use clone_solana_message::Message;
262 /// use clone_solana_pubkey::Pubkey;
263 /// use clone_solana_rpc_client::rpc_client::RpcClient;
264 /// use clone_solana_signer::Signer;
265 /// use clone_solana_transaction::Transaction;
266 ///
267 /// // A custom program instruction. This would typically be defined in
268 /// // another crate so it can be shared between the on-chain program and
269 /// // the client.
270 /// #[derive(BorshSerialize, BorshDeserialize)]
271 /// enum BankInstruction {
272 /// Initialize,
273 /// Deposit { lamports: u64 },
274 /// Withdraw { lamports: u64 },
275 /// }
276 ///
277 /// fn send_initialize_tx(
278 /// client: &RpcClient,
279 /// program_id: Pubkey,
280 /// payer: &Keypair
281 /// ) -> Result<()> {
282 ///
283 /// let bank_instruction = BankInstruction::Initialize;
284 ///
285 /// let instruction = Instruction::new_with_borsh(
286 /// program_id,
287 /// &bank_instruction,
288 /// vec![],
289 /// );
290 ///
291 /// let message = Message::new(
292 /// &[instruction],
293 /// Some(&payer.pubkey()),
294 /// );
295 ///
296 /// let mut tx = Transaction::new_unsigned(message);
297 /// let blockhash = client.get_latest_blockhash()?;
298 /// tx.sign(&[payer], blockhash);
299 /// client.send_and_confirm_transaction(&tx)?;
300 ///
301 /// Ok(())
302 /// }
303 /// #
304 /// # let client = RpcClient::new(String::new());
305 /// # let program_id = Pubkey::new_unique();
306 /// # let payer = Keypair::new();
307 /// # send_initialize_tx(&client, program_id, &payer)?;
308 /// #
309 /// # Ok::<(), anyhow::Error>(())
310 /// ```
311 pub fn new_unsigned(message: Message) -> Self {
312 Self {
313 signatures: vec![Signature::default(); message.header.num_required_signatures as usize],
314 message,
315 }
316 }
317
318 /// Create a fully-signed transaction from a [`Message`].
319 ///
320 /// # Panics
321 ///
322 /// Panics when signing fails. See [`Transaction::try_sign`] and
323 /// [`Transaction::try_partial_sign`] for a full description of failure
324 /// scenarios.
325 ///
326 /// # Examples
327 ///
328 /// This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
329 ///
330 /// [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
331 /// [`anyhow`]: https://docs.rs/anyhow
332 ///
333 /// ```
334 /// # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
335 /// use anyhow::Result;
336 /// use borsh::{BorshSerialize, BorshDeserialize};
337 /// use clone_solana_instruction::Instruction;
338 /// use clone_solana_keypair::Keypair;
339 /// use clone_solana_message::Message;
340 /// use clone_solana_pubkey::Pubkey;
341 /// use clone_solana_rpc_client::rpc_client::RpcClient;
342 /// use clone_solana_signer::Signer;
343 /// use clone_solana_transaction::Transaction;
344 ///
345 /// // A custom program instruction. This would typically be defined in
346 /// // another crate so it can be shared between the on-chain program and
347 /// // the client.
348 /// #[derive(BorshSerialize, BorshDeserialize)]
349 /// enum BankInstruction {
350 /// Initialize,
351 /// Deposit { lamports: u64 },
352 /// Withdraw { lamports: u64 },
353 /// }
354 ///
355 /// fn send_initialize_tx(
356 /// client: &RpcClient,
357 /// program_id: Pubkey,
358 /// payer: &Keypair
359 /// ) -> Result<()> {
360 ///
361 /// let bank_instruction = BankInstruction::Initialize;
362 ///
363 /// let instruction = Instruction::new_with_borsh(
364 /// program_id,
365 /// &bank_instruction,
366 /// vec![],
367 /// );
368 ///
369 /// let message = Message::new(
370 /// &[instruction],
371 /// Some(&payer.pubkey()),
372 /// );
373 ///
374 /// let blockhash = client.get_latest_blockhash()?;
375 /// let mut tx = Transaction::new(&[payer], message, blockhash);
376 /// client.send_and_confirm_transaction(&tx)?;
377 ///
378 /// Ok(())
379 /// }
380 /// #
381 /// # let client = RpcClient::new(String::new());
382 /// # let program_id = Pubkey::new_unique();
383 /// # let payer = Keypair::new();
384 /// # send_initialize_tx(&client, program_id, &payer)?;
385 /// #
386 /// # Ok::<(), anyhow::Error>(())
387 /// ```
388 #[cfg(feature = "bincode")]
389 pub fn new<T: Signers + ?Sized>(
390 from_keypairs: &T,
391 message: Message,
392 recent_blockhash: Hash,
393 ) -> Transaction {
394 let mut tx = Self::new_unsigned(message);
395 tx.sign(from_keypairs, recent_blockhash);
396 tx
397 }
398
399 /// Create an unsigned transaction from a list of [`Instruction`]s.
400 ///
401 /// `payer` is the account responsible for paying the cost of executing the
402 /// transaction. It is typically provided, but is optional in some cases.
403 /// See the [`Transaction`] docs for more.
404 ///
405 /// # Examples
406 ///
407 /// This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
408 ///
409 /// [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
410 /// [`anyhow`]: https://docs.rs/anyhow
411 ///
412 /// ```
413 /// # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
414 /// use anyhow::Result;
415 /// use borsh::{BorshSerialize, BorshDeserialize};
416 /// use clone_solana_instruction::Instruction;
417 /// use clone_solana_keypair::Keypair;
418 /// use clone_solana_message::Message;
419 /// use clone_solana_pubkey::Pubkey;
420 /// use clone_solana_rpc_client::rpc_client::RpcClient;
421 /// use clone_solana_signer::Signer;
422 /// use clone_solana_transaction::Transaction;
423 ///
424 /// // A custom program instruction. This would typically be defined in
425 /// // another crate so it can be shared between the on-chain program and
426 /// // the client.
427 /// #[derive(BorshSerialize, BorshDeserialize)]
428 /// enum BankInstruction {
429 /// Initialize,
430 /// Deposit { lamports: u64 },
431 /// Withdraw { lamports: u64 },
432 /// }
433 ///
434 /// fn send_initialize_tx(
435 /// client: &RpcClient,
436 /// program_id: Pubkey,
437 /// payer: &Keypair
438 /// ) -> Result<()> {
439 ///
440 /// let bank_instruction = BankInstruction::Initialize;
441 ///
442 /// let instruction = Instruction::new_with_borsh(
443 /// program_id,
444 /// &bank_instruction,
445 /// vec![],
446 /// );
447 ///
448 /// let mut tx = Transaction::new_with_payer(&[instruction], Some(&payer.pubkey()));
449 /// let blockhash = client.get_latest_blockhash()?;
450 /// tx.sign(&[payer], blockhash);
451 /// client.send_and_confirm_transaction(&tx)?;
452 ///
453 /// Ok(())
454 /// }
455 /// #
456 /// # let client = RpcClient::new(String::new());
457 /// # let program_id = Pubkey::new_unique();
458 /// # let payer = Keypair::new();
459 /// # send_initialize_tx(&client, program_id, &payer)?;
460 /// #
461 /// # Ok::<(), anyhow::Error>(())
462 /// ```
463 pub fn new_with_payer(instructions: &[Instruction], payer: Option<&Pubkey>) -> Self {
464 let message = Message::new(instructions, payer);
465 Self::new_unsigned(message)
466 }
467
468 /// Create a fully-signed transaction from a list of [`Instruction`]s.
469 ///
470 /// `payer` is the account responsible for paying the cost of executing the
471 /// transaction. It is typically provided, but is optional in some cases.
472 /// See the [`Transaction`] docs for more.
473 ///
474 /// # Panics
475 ///
476 /// Panics when signing fails. See [`Transaction::try_sign`] and
477 /// [`Transaction::try_partial_sign`] for a full description of failure
478 /// scenarios.
479 ///
480 /// # Examples
481 ///
482 /// This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
483 ///
484 /// [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
485 /// [`anyhow`]: https://docs.rs/anyhow
486 ///
487 /// ```
488 /// # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
489 /// use anyhow::Result;
490 /// use borsh::{BorshSerialize, BorshDeserialize};
491 /// use clone_solana_instruction::Instruction;
492 /// use clone_solana_keypair::Keypair;
493 /// use clone_solana_message::Message;
494 /// use clone_solana_pubkey::Pubkey;
495 /// use clone_solana_rpc_client::rpc_client::RpcClient;
496 /// use clone_solana_signer::Signer;
497 /// use clone_solana_transaction::Transaction;
498 ///
499 /// // A custom program instruction. This would typically be defined in
500 /// // another crate so it can be shared between the on-chain program and
501 /// // the client.
502 /// #[derive(BorshSerialize, BorshDeserialize)]
503 /// enum BankInstruction {
504 /// Initialize,
505 /// Deposit { lamports: u64 },
506 /// Withdraw { lamports: u64 },
507 /// }
508 ///
509 /// fn send_initialize_tx(
510 /// client: &RpcClient,
511 /// program_id: Pubkey,
512 /// payer: &Keypair
513 /// ) -> Result<()> {
514 ///
515 /// let bank_instruction = BankInstruction::Initialize;
516 ///
517 /// let instruction = Instruction::new_with_borsh(
518 /// program_id,
519 /// &bank_instruction,
520 /// vec![],
521 /// );
522 ///
523 /// let blockhash = client.get_latest_blockhash()?;
524 /// let mut tx = Transaction::new_signed_with_payer(
525 /// &[instruction],
526 /// Some(&payer.pubkey()),
527 /// &[payer],
528 /// blockhash,
529 /// );
530 /// client.send_and_confirm_transaction(&tx)?;
531 ///
532 /// Ok(())
533 /// }
534 /// #
535 /// # let client = RpcClient::new(String::new());
536 /// # let program_id = Pubkey::new_unique();
537 /// # let payer = Keypair::new();
538 /// # send_initialize_tx(&client, program_id, &payer)?;
539 /// #
540 /// # Ok::<(), anyhow::Error>(())
541 /// ```
542 #[cfg(feature = "bincode")]
543 pub fn new_signed_with_payer<T: Signers + ?Sized>(
544 instructions: &[Instruction],
545 payer: Option<&Pubkey>,
546 signing_keypairs: &T,
547 recent_blockhash: Hash,
548 ) -> Self {
549 let message = Message::new(instructions, payer);
550 Self::new(signing_keypairs, message, recent_blockhash)
551 }
552
553 /// Create a fully-signed transaction from pre-compiled instructions.
554 ///
555 /// # Arguments
556 ///
557 /// * `from_keypairs` - The keys used to sign the transaction.
558 /// * `keys` - The keys for the transaction. These are the program state
559 /// instances or lamport recipient keys.
560 /// * `recent_blockhash` - The PoH hash.
561 /// * `program_ids` - The keys that identify programs used in the `instruction` vector.
562 /// * `instructions` - Instructions that will be executed atomically.
563 ///
564 /// # Panics
565 ///
566 /// Panics when signing fails. See [`Transaction::try_sign`] and for a full
567 /// description of failure conditions.
568 #[cfg(feature = "bincode")]
569 pub fn new_with_compiled_instructions<T: Signers + ?Sized>(
570 from_keypairs: &T,
571 keys: &[Pubkey],
572 recent_blockhash: Hash,
573 program_ids: Vec<Pubkey>,
574 instructions: Vec<CompiledInstruction>,
575 ) -> Self {
576 let mut account_keys = from_keypairs.pubkeys();
577 let from_keypairs_len = account_keys.len();
578 account_keys.extend_from_slice(keys);
579 account_keys.extend(&program_ids);
580 let message = Message::new_with_compiled_instructions(
581 from_keypairs_len as u8,
582 0,
583 program_ids.len() as u8,
584 account_keys,
585 Hash::default(),
586 instructions,
587 );
588 Transaction::new(from_keypairs, message, recent_blockhash)
589 }
590
591 /// Get the data for an instruction at the given index.
592 ///
593 /// The `instruction_index` corresponds to the [`instructions`] vector of
594 /// the `Transaction`'s [`Message`] value.
595 ///
596 /// [`instructions`]: Message::instructions
597 ///
598 /// # Panics
599 ///
600 /// Panics if `instruction_index` is greater than or equal to the number of
601 /// instructions in the transaction.
602 pub fn data(&self, instruction_index: usize) -> &[u8] {
603 &self.message.instructions[instruction_index].data
604 }
605
606 fn key_index(&self, instruction_index: usize, accounts_index: usize) -> Option<usize> {
607 self.message
608 .instructions
609 .get(instruction_index)
610 .and_then(|instruction| instruction.accounts.get(accounts_index))
611 .map(|&account_keys_index| account_keys_index as usize)
612 }
613
614 /// Get the `Pubkey` of an account required by one of the instructions in
615 /// the transaction.
616 ///
617 /// The `instruction_index` corresponds to the [`instructions`] vector of
618 /// the `Transaction`'s [`Message`] value; and the `account_index` to the
619 /// [`accounts`] vector of the message's [`CompiledInstruction`]s.
620 ///
621 /// [`instructions`]: Message::instructions
622 /// [`accounts`]: CompiledInstruction::accounts
623 /// [`CompiledInstruction`]: CompiledInstruction
624 ///
625 /// Returns `None` if `instruction_index` is greater than or equal to the
626 /// number of instructions in the transaction; or if `accounts_index` is
627 /// greater than or equal to the number of accounts in the instruction.
628 pub fn key(&self, instruction_index: usize, accounts_index: usize) -> Option<&Pubkey> {
629 self.key_index(instruction_index, accounts_index)
630 .and_then(|account_keys_index| self.message.account_keys.get(account_keys_index))
631 }
632
633 /// Get the `Pubkey` of a signing account required by one of the
634 /// instructions in the transaction.
635 ///
636 /// The transaction does not need to be signed for this function to return a
637 /// signing account's pubkey.
638 ///
639 /// Returns `None` if the indexed account is not required to sign the
640 /// transaction. Returns `None` if the [`signatures`] field does not contain
641 /// enough elements to hold a signature for the indexed account (this should
642 /// only be possible if `Transaction` has been manually constructed).
643 ///
644 /// [`signatures`]: Transaction::signatures
645 ///
646 /// Returns `None` if `instruction_index` is greater than or equal to the
647 /// number of instructions in the transaction; or if `accounts_index` is
648 /// greater than or equal to the number of accounts in the instruction.
649 pub fn signer_key(&self, instruction_index: usize, accounts_index: usize) -> Option<&Pubkey> {
650 match self.key_index(instruction_index, accounts_index) {
651 None => None,
652 Some(signature_index) => {
653 if signature_index >= self.signatures.len() {
654 return None;
655 }
656 self.message.account_keys.get(signature_index)
657 }
658 }
659 }
660
661 /// Return the message containing all data that should be signed.
662 pub fn message(&self) -> &Message {
663 &self.message
664 }
665
666 #[cfg(feature = "bincode")]
667 /// Return the serialized message data to sign.
668 pub fn message_data(&self) -> Vec<u8> {
669 self.message().serialize()
670 }
671
672 /// Sign the transaction.
673 ///
674 /// This method fully signs a transaction with all required signers, which
675 /// must be present in the `keypairs` slice. To sign with only some of the
676 /// required signers, use [`Transaction::partial_sign`].
677 ///
678 /// If `recent_blockhash` is different than recorded in the transaction message's
679 /// [`recent_blockhash`] field, then the message's `recent_blockhash` will be updated
680 /// to the provided `recent_blockhash`, and any prior signatures will be cleared.
681 ///
682 /// [`recent_blockhash`]: Message::recent_blockhash
683 ///
684 /// # Panics
685 ///
686 /// Panics when signing fails. Use [`Transaction::try_sign`] to handle the
687 /// error. See the documentation for [`Transaction::try_sign`] for a full description of
688 /// failure conditions.
689 ///
690 /// # Examples
691 ///
692 /// This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
693 ///
694 /// [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
695 /// [`anyhow`]: https://docs.rs/anyhow
696 ///
697 /// ```
698 /// # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
699 /// use anyhow::Result;
700 /// use borsh::{BorshSerialize, BorshDeserialize};
701 /// use clone_solana_instruction::Instruction;
702 /// use clone_solana_keypair::Keypair;
703 /// use clone_solana_message::Message;
704 /// use clone_solana_pubkey::Pubkey;
705 /// use clone_solana_rpc_client::rpc_client::RpcClient;
706 /// use clone_solana_signer::Signer;
707 /// use clone_solana_transaction::Transaction;
708 ///
709 /// // A custom program instruction. This would typically be defined in
710 /// // another crate so it can be shared between the on-chain program and
711 /// // the client.
712 /// #[derive(BorshSerialize, BorshDeserialize)]
713 /// enum BankInstruction {
714 /// Initialize,
715 /// Deposit { lamports: u64 },
716 /// Withdraw { lamports: u64 },
717 /// }
718 ///
719 /// fn send_initialize_tx(
720 /// client: &RpcClient,
721 /// program_id: Pubkey,
722 /// payer: &Keypair
723 /// ) -> Result<()> {
724 ///
725 /// let bank_instruction = BankInstruction::Initialize;
726 ///
727 /// let instruction = Instruction::new_with_borsh(
728 /// program_id,
729 /// &bank_instruction,
730 /// vec![],
731 /// );
732 ///
733 /// let mut tx = Transaction::new_with_payer(&[instruction], Some(&payer.pubkey()));
734 /// let blockhash = client.get_latest_blockhash()?;
735 /// tx.sign(&[payer], blockhash);
736 /// client.send_and_confirm_transaction(&tx)?;
737 ///
738 /// Ok(())
739 /// }
740 /// #
741 /// # let client = RpcClient::new(String::new());
742 /// # let program_id = Pubkey::new_unique();
743 /// # let payer = Keypair::new();
744 /// # send_initialize_tx(&client, program_id, &payer)?;
745 /// #
746 /// # Ok::<(), anyhow::Error>(())
747 /// ```
748 #[cfg(feature = "bincode")]
749 pub fn sign<T: Signers + ?Sized>(&mut self, keypairs: &T, recent_blockhash: Hash) {
750 if let Err(e) = self.try_sign(keypairs, recent_blockhash) {
751 panic!("Transaction::sign failed with error {e:?}");
752 }
753 }
754
755 /// Sign the transaction with a subset of required keys.
756 ///
757 /// Unlike [`Transaction::sign`], this method does not require all keypairs
758 /// to be provided, allowing a transaction to be signed in multiple steps.
759 ///
760 /// It is permitted to sign a transaction with the same keypair multiple
761 /// times.
762 ///
763 /// If `recent_blockhash` is different than recorded in the transaction message's
764 /// [`recent_blockhash`] field, then the message's `recent_blockhash` will be updated
765 /// to the provided `recent_blockhash`, and any prior signatures will be cleared.
766 ///
767 /// [`recent_blockhash`]: Message::recent_blockhash
768 ///
769 /// # Panics
770 ///
771 /// Panics when signing fails. Use [`Transaction::try_partial_sign`] to
772 /// handle the error. See the documentation for
773 /// [`Transaction::try_partial_sign`] for a full description of failure
774 /// conditions.
775 #[cfg(feature = "bincode")]
776 pub fn partial_sign<T: Signers + ?Sized>(&mut self, keypairs: &T, recent_blockhash: Hash) {
777 if let Err(e) = self.try_partial_sign(keypairs, recent_blockhash) {
778 panic!("Transaction::partial_sign failed with error {e:?}");
779 }
780 }
781
782 /// Sign the transaction with a subset of required keys.
783 ///
784 /// This places each of the signatures created from `keypairs` in the
785 /// corresponding position, as specified in the `positions` vector, in the
786 /// transactions [`signatures`] field. It does not verify that the signature
787 /// positions are correct.
788 ///
789 /// [`signatures`]: Transaction::signatures
790 ///
791 /// # Panics
792 ///
793 /// Panics if signing fails. Use [`Transaction::try_partial_sign_unchecked`]
794 /// to handle the error.
795 #[cfg(feature = "bincode")]
796 pub fn partial_sign_unchecked<T: Signers + ?Sized>(
797 &mut self,
798 keypairs: &T,
799 positions: Vec<usize>,
800 recent_blockhash: Hash,
801 ) {
802 if let Err(e) = self.try_partial_sign_unchecked(keypairs, positions, recent_blockhash) {
803 panic!("Transaction::partial_sign_unchecked failed with error {e:?}");
804 }
805 }
806
807 /// Sign the transaction, returning any errors.
808 ///
809 /// This method fully signs a transaction with all required signers, which
810 /// must be present in the `keypairs` slice. To sign with only some of the
811 /// required signers, use [`Transaction::try_partial_sign`].
812 ///
813 /// If `recent_blockhash` is different than recorded in the transaction message's
814 /// [`recent_blockhash`] field, then the message's `recent_blockhash` will be updated
815 /// to the provided `recent_blockhash`, and any prior signatures will be cleared.
816 ///
817 /// [`recent_blockhash`]: Message::recent_blockhash
818 ///
819 /// # Errors
820 ///
821 /// Signing will fail if some required signers are not provided in
822 /// `keypairs`; or, if the transaction has previously been partially signed,
823 /// some of the remaining required signers are not provided in `keypairs`.
824 /// In other words, the transaction must be fully signed as a result of
825 /// calling this function. The error is [`SignerError::NotEnoughSigners`].
826 ///
827 /// Signing will fail for any of the reasons described in the documentation
828 /// for [`Transaction::try_partial_sign`].
829 ///
830 /// # Examples
831 ///
832 /// This example uses the [`clone_solana_rpc_client`] and [`anyhow`] crates.
833 ///
834 /// [`clone_solana_rpc_client`]: https://docs.rs/solana-rpc-client
835 /// [`anyhow`]: https://docs.rs/anyhow
836 ///
837 /// ```
838 /// # use clone_solana_sdk::example_mocks::clone_solana_rpc_client;
839 /// use anyhow::Result;
840 /// use borsh::{BorshSerialize, BorshDeserialize};
841 /// use clone_solana_instruction::Instruction;
842 /// use clone_solana_keypair::Keypair;
843 /// use clone_solana_message::Message;
844 /// use clone_solana_pubkey::Pubkey;
845 /// use clone_solana_rpc_client::rpc_client::RpcClient;
846 /// use clone_solana_signer::Signer;
847 /// use clone_solana_transaction::Transaction;
848 ///
849 /// // A custom program instruction. This would typically be defined in
850 /// // another crate so it can be shared between the on-chain program and
851 /// // the client.
852 /// #[derive(BorshSerialize, BorshDeserialize)]
853 /// enum BankInstruction {
854 /// Initialize,
855 /// Deposit { lamports: u64 },
856 /// Withdraw { lamports: u64 },
857 /// }
858 ///
859 /// fn send_initialize_tx(
860 /// client: &RpcClient,
861 /// program_id: Pubkey,
862 /// payer: &Keypair
863 /// ) -> Result<()> {
864 ///
865 /// let bank_instruction = BankInstruction::Initialize;
866 ///
867 /// let instruction = Instruction::new_with_borsh(
868 /// program_id,
869 /// &bank_instruction,
870 /// vec![],
871 /// );
872 ///
873 /// let mut tx = Transaction::new_with_payer(&[instruction], Some(&payer.pubkey()));
874 /// let blockhash = client.get_latest_blockhash()?;
875 /// tx.try_sign(&[payer], blockhash)?;
876 /// client.send_and_confirm_transaction(&tx)?;
877 ///
878 /// Ok(())
879 /// }
880 /// #
881 /// # let client = RpcClient::new(String::new());
882 /// # let program_id = Pubkey::new_unique();
883 /// # let payer = Keypair::new();
884 /// # send_initialize_tx(&client, program_id, &payer)?;
885 /// #
886 /// # Ok::<(), anyhow::Error>(())
887 /// ```
888 #[cfg(feature = "bincode")]
889 pub fn try_sign<T: Signers + ?Sized>(
890 &mut self,
891 keypairs: &T,
892 recent_blockhash: Hash,
893 ) -> result::Result<(), SignerError> {
894 self.try_partial_sign(keypairs, recent_blockhash)?;
895
896 if !self.is_signed() {
897 Err(SignerError::NotEnoughSigners)
898 } else {
899 Ok(())
900 }
901 }
902
903 /// Sign the transaction with a subset of required keys, returning any errors.
904 ///
905 /// Unlike [`Transaction::try_sign`], this method does not require all
906 /// keypairs to be provided, allowing a transaction to be signed in multiple
907 /// steps.
908 ///
909 /// It is permitted to sign a transaction with the same keypair multiple
910 /// times.
911 ///
912 /// If `recent_blockhash` is different than recorded in the transaction message's
913 /// [`recent_blockhash`] field, then the message's `recent_blockhash` will be updated
914 /// to the provided `recent_blockhash`, and any prior signatures will be cleared.
915 ///
916 /// [`recent_blockhash`]: Message::recent_blockhash
917 ///
918 /// # Errors
919 ///
920 /// Signing will fail if
921 ///
922 /// - The transaction's [`Message`] is malformed such that the number of
923 /// required signatures recorded in its header
924 /// ([`num_required_signatures`]) is greater than the length of its
925 /// account keys ([`account_keys`]). The error is
926 /// [`SignerError::TransactionError`] where the interior
927 /// [`TransactionError`] is [`TransactionError::InvalidAccountIndex`].
928 /// - Any of the provided signers in `keypairs` is not a required signer of
929 /// the message. The error is [`SignerError::KeypairPubkeyMismatch`].
930 /// - Any of the signers is a [`Presigner`], and its provided signature is
931 /// incorrect. The error is [`SignerError::PresignerError`] where the
932 /// interior [`PresignerError`] is
933 /// [`PresignerError::VerificationFailure`].
934 /// - The signer is a [`RemoteKeypair`] and
935 /// - It does not understand the input provided ([`SignerError::InvalidInput`]).
936 /// - The device cannot be found ([`SignerError::NoDeviceFound`]).
937 /// - The user cancels the signing ([`SignerError::UserCancel`]).
938 /// - An error was encountered connecting ([`SignerError::Connection`]).
939 /// - Some device-specific protocol error occurs ([`SignerError::Protocol`]).
940 /// - Some other error occurs ([`SignerError::Custom`]).
941 ///
942 /// See the documentation for the [`solana-remote-wallet`] crate for details
943 /// on the operation of [`RemoteKeypair`] signers.
944 ///
945 /// [`num_required_signatures`]: https://docs.rs/solana-message/latest/clone_solana_message/struct.MessageHeader.html#structfield.num_required_signatures
946 /// [`account_keys`]: https://docs.rs/solana-message/latest/clone_solana_message/legacy/struct.Message.html#structfield.account_keys
947 /// [`Presigner`]: https://docs.rs/solana-presigner/latest/clone_solana_presigner/struct.Presigner.html
948 /// [`PresignerError`]: https://docs.rs/solana-signer/latest/clone_solana_signer/enum.PresignerError.html
949 /// [`PresignerError::VerificationFailure`]: https://docs.rs/solana-signer/latest/clone_solana_signer/enum.PresignerError.html#variant.WrongSize
950 /// [`solana-remote-wallet`]: https://docs.rs/solana-remote-wallet/latest/
951 /// [`RemoteKeypair`]: https://docs.rs/solana-remote-wallet/latest/clone_solana_remote_wallet/remote_keypair/struct.RemoteKeypair.html
952 #[cfg(feature = "bincode")]
953 pub fn try_partial_sign<T: Signers + ?Sized>(
954 &mut self,
955 keypairs: &T,
956 recent_blockhash: Hash,
957 ) -> result::Result<(), SignerError> {
958 let positions: Vec<usize> = self
959 .get_signing_keypair_positions(&keypairs.pubkeys())?
960 .into_iter()
961 .collect::<Option<_>>()
962 .ok_or(SignerError::KeypairPubkeyMismatch)?;
963 self.try_partial_sign_unchecked(keypairs, positions, recent_blockhash)
964 }
965
966 /// Sign the transaction with a subset of required keys, returning any
967 /// errors.
968 ///
969 /// This places each of the signatures created from `keypairs` in the
970 /// corresponding position, as specified in the `positions` vector, in the
971 /// transactions [`signatures`] field. It does not verify that the signature
972 /// positions are correct.
973 ///
974 /// [`signatures`]: Transaction::signatures
975 ///
976 /// # Errors
977 ///
978 /// Returns an error if signing fails.
979 #[cfg(feature = "bincode")]
980 pub fn try_partial_sign_unchecked<T: Signers + ?Sized>(
981 &mut self,
982 keypairs: &T,
983 positions: Vec<usize>,
984 recent_blockhash: Hash,
985 ) -> result::Result<(), SignerError> {
986 // if you change the blockhash, you're re-signing...
987 if recent_blockhash != self.message.recent_blockhash {
988 self.message.recent_blockhash = recent_blockhash;
989 self.signatures
990 .iter_mut()
991 .for_each(|signature| *signature = Signature::default());
992 }
993
994 let signatures = keypairs.try_sign_message(&self.message_data())?;
995 for i in 0..positions.len() {
996 self.signatures[positions[i]] = signatures[i];
997 }
998 Ok(())
999 }
1000
1001 /// Returns a signature that is not valid for signing this transaction.
1002 pub fn get_invalid_signature() -> Signature {
1003 Signature::default()
1004 }
1005
1006 #[cfg(feature = "verify")]
1007 /// Verifies that all signers have signed the message.
1008 ///
1009 /// # Errors
1010 ///
1011 /// Returns [`TransactionError::SignatureFailure`] on error.
1012 pub fn verify(&self) -> Result<()> {
1013 let message_bytes = self.message_data();
1014 if !self
1015 ._verify_with_results(&message_bytes)
1016 .iter()
1017 .all(|verify_result| *verify_result)
1018 {
1019 Err(TransactionError::SignatureFailure)
1020 } else {
1021 Ok(())
1022 }
1023 }
1024
1025 #[cfg(feature = "verify")]
1026 /// Verify the transaction and hash its message.
1027 ///
1028 /// # Errors
1029 ///
1030 /// Returns [`TransactionError::SignatureFailure`] on error.
1031 pub fn verify_and_hash_message(&self) -> Result<Hash> {
1032 let message_bytes = self.message_data();
1033 if !self
1034 ._verify_with_results(&message_bytes)
1035 .iter()
1036 .all(|verify_result| *verify_result)
1037 {
1038 Err(TransactionError::SignatureFailure)
1039 } else {
1040 Ok(Message::hash_raw_message(&message_bytes))
1041 }
1042 }
1043
1044 #[cfg(feature = "verify")]
1045 /// Verifies that all signers have signed the message.
1046 ///
1047 /// Returns a vector with the length of required signatures, where each
1048 /// element is either `true` if that signer has signed, or `false` if not.
1049 pub fn verify_with_results(&self) -> Vec<bool> {
1050 self._verify_with_results(&self.message_data())
1051 }
1052
1053 #[cfg(feature = "verify")]
1054 pub(crate) fn _verify_with_results(&self, message_bytes: &[u8]) -> Vec<bool> {
1055 self.signatures
1056 .iter()
1057 .zip(&self.message.account_keys)
1058 .map(|(signature, pubkey)| signature.verify(pubkey.as_ref(), message_bytes))
1059 .collect()
1060 }
1061
1062 #[cfg(feature = "precompiles")]
1063 /// Verify the precompiled programs in this transaction.
1064 pub fn verify_precompiles(
1065 &self,
1066 feature_set: &clone_solana_feature_set::FeatureSet,
1067 ) -> Result<()> {
1068 for instruction in &self.message().instructions {
1069 // The Transaction may not be sanitized at this point
1070 if instruction.program_id_index as usize >= self.message().account_keys.len() {
1071 return Err(TransactionError::AccountNotFound);
1072 }
1073 let program_id = &self.message().account_keys[instruction.program_id_index as usize];
1074
1075 clone_solana_precompiles::verify_if_precompile(
1076 program_id,
1077 instruction,
1078 &self.message().instructions,
1079 feature_set,
1080 )
1081 .map_err(|_| TransactionError::InvalidAccountIndex)?;
1082 }
1083 Ok(())
1084 }
1085
1086 /// Get the positions of the pubkeys in `account_keys` associated with signing keypairs.
1087 ///
1088 /// [`account_keys`]: Message::account_keys
1089 pub fn get_signing_keypair_positions(&self, pubkeys: &[Pubkey]) -> Result<Vec<Option<usize>>> {
1090 if self.message.account_keys.len() < self.message.header.num_required_signatures as usize {
1091 return Err(TransactionError::InvalidAccountIndex);
1092 }
1093 let signed_keys =
1094 &self.message.account_keys[0..self.message.header.num_required_signatures as usize];
1095
1096 Ok(pubkeys
1097 .iter()
1098 .map(|pubkey| signed_keys.iter().position(|x| x == pubkey))
1099 .collect())
1100 }
1101
1102 #[cfg(feature = "verify")]
1103 /// Replace all the signatures and pubkeys.
1104 pub fn replace_signatures(&mut self, signers: &[(Pubkey, Signature)]) -> Result<()> {
1105 let num_required_signatures = self.message.header.num_required_signatures as usize;
1106 if signers.len() != num_required_signatures
1107 || self.signatures.len() != num_required_signatures
1108 || self.message.account_keys.len() < num_required_signatures
1109 {
1110 return Err(TransactionError::InvalidAccountIndex);
1111 }
1112
1113 for (index, account_key) in self
1114 .message
1115 .account_keys
1116 .iter()
1117 .enumerate()
1118 .take(num_required_signatures)
1119 {
1120 if let Some((_pubkey, signature)) =
1121 signers.iter().find(|(key, _signature)| account_key == key)
1122 {
1123 self.signatures[index] = *signature
1124 } else {
1125 return Err(TransactionError::InvalidAccountIndex);
1126 }
1127 }
1128
1129 self.verify()
1130 }
1131
1132 pub fn is_signed(&self) -> bool {
1133 self.signatures
1134 .iter()
1135 .all(|signature| *signature != Signature::default())
1136 }
1137}
1138
1139#[cfg(feature = "bincode")]
1140/// Returns true if transaction begins with an advance nonce instruction.
1141pub fn uses_durable_nonce(tx: &Transaction) -> Option<&CompiledInstruction> {
1142 let message = tx.message();
1143 message
1144 .instructions
1145 .get(NONCED_TX_MARKER_IX_INDEX as usize)
1146 .filter(|instruction| {
1147 // Is system program
1148 matches!(
1149 message.account_keys.get(instruction.program_id_index as usize),
1150 Some(program_id) if system_program::check_id(program_id)
1151 )
1152 // Is a nonce advance instruction
1153 && matches!(
1154 limited_deserialize(&instruction.data, PACKET_DATA_SIZE as u64),
1155 Ok(SystemInstruction::AdvanceNonceAccount)
1156 )
1157 })
1158}
1159
1160#[cfg(test)]
1161mod tests {
1162 #![allow(deprecated)]
1163
1164 use {
1165 super::*,
1166 bincode::{deserialize, serialize, serialized_size},
1167 clone_solana_instruction::AccountMeta,
1168 clone_solana_keypair::Keypair,
1169 clone_solana_presigner::Presigner,
1170 clone_solana_sha256_hasher::hash,
1171 clone_solana_signer::Signer,
1172 clone_solana_system_interface::instruction as system_instruction,
1173 std::mem::size_of,
1174 };
1175
1176 fn get_program_id(tx: &Transaction, instruction_index: usize) -> &Pubkey {
1177 let message = tx.message();
1178 let instruction = &message.instructions[instruction_index];
1179 instruction.program_id(&message.account_keys)
1180 }
1181
1182 #[test]
1183 fn test_refs() {
1184 let key = Keypair::new();
1185 let key1 = clone_solana_pubkey::new_rand();
1186 let key2 = clone_solana_pubkey::new_rand();
1187 let prog1 = clone_solana_pubkey::new_rand();
1188 let prog2 = clone_solana_pubkey::new_rand();
1189 let instructions = vec![
1190 CompiledInstruction::new(3, &(), vec![0, 1]),
1191 CompiledInstruction::new(4, &(), vec![0, 2]),
1192 ];
1193 let tx = Transaction::new_with_compiled_instructions(
1194 &[&key],
1195 &[key1, key2],
1196 Hash::default(),
1197 vec![prog1, prog2],
1198 instructions,
1199 );
1200 assert!(tx.sanitize().is_ok());
1201
1202 assert_eq!(tx.key(0, 0), Some(&key.pubkey()));
1203 assert_eq!(tx.signer_key(0, 0), Some(&key.pubkey()));
1204
1205 assert_eq!(tx.key(1, 0), Some(&key.pubkey()));
1206 assert_eq!(tx.signer_key(1, 0), Some(&key.pubkey()));
1207
1208 assert_eq!(tx.key(0, 1), Some(&key1));
1209 assert_eq!(tx.signer_key(0, 1), None);
1210
1211 assert_eq!(tx.key(1, 1), Some(&key2));
1212 assert_eq!(tx.signer_key(1, 1), None);
1213
1214 assert_eq!(tx.key(2, 0), None);
1215 assert_eq!(tx.signer_key(2, 0), None);
1216
1217 assert_eq!(tx.key(0, 2), None);
1218 assert_eq!(tx.signer_key(0, 2), None);
1219
1220 assert_eq!(*get_program_id(&tx, 0), prog1);
1221 assert_eq!(*get_program_id(&tx, 1), prog2);
1222 }
1223
1224 #[test]
1225 fn test_refs_invalid_program_id() {
1226 let key = Keypair::new();
1227 let instructions = vec![CompiledInstruction::new(1, &(), vec![])];
1228 let tx = Transaction::new_with_compiled_instructions(
1229 &[&key],
1230 &[],
1231 Hash::default(),
1232 vec![],
1233 instructions,
1234 );
1235 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1236 }
1237 #[test]
1238 fn test_refs_invalid_account() {
1239 let key = Keypair::new();
1240 let instructions = vec![CompiledInstruction::new(1, &(), vec![2])];
1241 let tx = Transaction::new_with_compiled_instructions(
1242 &[&key],
1243 &[],
1244 Hash::default(),
1245 vec![Pubkey::default()],
1246 instructions,
1247 );
1248 assert_eq!(*get_program_id(&tx, 0), Pubkey::default());
1249 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1250 }
1251
1252 #[test]
1253 fn test_sanitize_txs() {
1254 let key = Keypair::new();
1255 let id0 = Pubkey::default();
1256 let program_id = clone_solana_pubkey::new_rand();
1257 let ix = Instruction::new_with_bincode(
1258 program_id,
1259 &0,
1260 vec![
1261 AccountMeta::new(key.pubkey(), true),
1262 AccountMeta::new(id0, true),
1263 ],
1264 );
1265 let mut tx = Transaction::new_with_payer(&[ix], Some(&key.pubkey()));
1266 let o = tx.clone();
1267 assert_eq!(tx.sanitize(), Ok(()));
1268 assert_eq!(tx.message.account_keys.len(), 3);
1269
1270 tx = o.clone();
1271 tx.message.header.num_required_signatures = 3;
1272 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1273
1274 tx = o.clone();
1275 tx.message.header.num_readonly_signed_accounts = 4;
1276 tx.message.header.num_readonly_unsigned_accounts = 0;
1277 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1278
1279 tx = o.clone();
1280 tx.message.header.num_readonly_signed_accounts = 2;
1281 tx.message.header.num_readonly_unsigned_accounts = 2;
1282 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1283
1284 tx = o.clone();
1285 tx.message.header.num_readonly_signed_accounts = 0;
1286 tx.message.header.num_readonly_unsigned_accounts = 4;
1287 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1288
1289 tx = o.clone();
1290 tx.message.instructions[0].program_id_index = 3;
1291 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1292
1293 tx = o.clone();
1294 tx.message.instructions[0].accounts[0] = 3;
1295 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1296
1297 tx = o.clone();
1298 tx.message.instructions[0].program_id_index = 0;
1299 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1300
1301 tx = o.clone();
1302 tx.message.header.num_readonly_signed_accounts = 2;
1303 tx.message.header.num_readonly_unsigned_accounts = 3;
1304 tx.message.account_keys.resize(4, Pubkey::default());
1305 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1306
1307 tx = o;
1308 tx.message.header.num_readonly_signed_accounts = 2;
1309 tx.message.header.num_required_signatures = 1;
1310 assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1311 }
1312
1313 fn create_sample_transaction() -> Transaction {
1314 let keypair = Keypair::from_bytes(&[
1315 255, 101, 36, 24, 124, 23, 167, 21, 132, 204, 155, 5, 185, 58, 121, 75, 156, 227, 116,
1316 193, 215, 38, 142, 22, 8, 14, 229, 239, 119, 93, 5, 218, 36, 100, 158, 252, 33, 161,
1317 97, 185, 62, 89, 99, 195, 250, 249, 187, 189, 171, 118, 241, 90, 248, 14, 68, 219, 231,
1318 62, 157, 5, 142, 27, 210, 117,
1319 ])
1320 .unwrap();
1321 let to = Pubkey::from([
1322 1, 1, 1, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 7, 6, 5, 4,
1323 1, 1, 1,
1324 ]);
1325
1326 let program_id = Pubkey::from([
1327 2, 2, 2, 4, 5, 6, 7, 8, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 8, 7, 6, 5, 4,
1328 2, 2, 2,
1329 ]);
1330 let account_metas = vec![
1331 AccountMeta::new(keypair.pubkey(), true),
1332 AccountMeta::new(to, false),
1333 ];
1334 let instruction =
1335 Instruction::new_with_bincode(program_id, &(1u8, 2u8, 3u8), account_metas);
1336 let message = Message::new(&[instruction], Some(&keypair.pubkey()));
1337 let tx = Transaction::new(&[&keypair], message, Hash::default());
1338 tx.verify().expect("valid sample transaction signatures");
1339 tx
1340 }
1341
1342 #[test]
1343 fn test_transaction_serialize() {
1344 let tx = create_sample_transaction();
1345 let ser = serialize(&tx).unwrap();
1346 let deser = deserialize(&ser).unwrap();
1347 assert_eq!(tx, deser);
1348 }
1349
1350 /// Detect changes to the serialized size of payment transactions, which affects TPS.
1351 #[test]
1352 fn test_transaction_minimum_serialized_size() {
1353 let alice_keypair = Keypair::new();
1354 let alice_pubkey = alice_keypair.pubkey();
1355 let bob_pubkey = clone_solana_pubkey::new_rand();
1356 let ix = system_instruction::transfer(&alice_pubkey, &bob_pubkey, 42);
1357
1358 let expected_data_size = size_of::<u32>() + size_of::<u64>();
1359 assert_eq!(expected_data_size, 12);
1360 assert_eq!(
1361 ix.data.len(),
1362 expected_data_size,
1363 "unexpected system instruction size"
1364 );
1365
1366 let expected_instruction_size = 1 + 1 + ix.accounts.len() + 1 + expected_data_size;
1367 assert_eq!(expected_instruction_size, 17);
1368
1369 let message = Message::new(&[ix], Some(&alice_pubkey));
1370 assert_eq!(
1371 serialized_size(&message.instructions[0]).unwrap() as usize,
1372 expected_instruction_size,
1373 "unexpected Instruction::serialized_size"
1374 );
1375
1376 let tx = Transaction::new(&[&alice_keypair], message, Hash::default());
1377
1378 let len_size = 1;
1379 let num_required_sigs_size = 1;
1380 let num_readonly_accounts_size = 2;
1381 let blockhash_size = size_of::<Hash>();
1382 let expected_transaction_size = len_size
1383 + (tx.signatures.len() * size_of::<Signature>())
1384 + num_required_sigs_size
1385 + num_readonly_accounts_size
1386 + len_size
1387 + (tx.message.account_keys.len() * size_of::<Pubkey>())
1388 + blockhash_size
1389 + len_size
1390 + expected_instruction_size;
1391 assert_eq!(expected_transaction_size, 215);
1392
1393 assert_eq!(
1394 serialized_size(&tx).unwrap() as usize,
1395 expected_transaction_size,
1396 "unexpected serialized transaction size"
1397 );
1398 }
1399
1400 /// Detect binary changes in the serialized transaction data, which could have a downstream
1401 /// affect on SDKs and applications
1402 #[test]
1403 fn test_sdk_serialize() {
1404 assert_eq!(
1405 serialize(&create_sample_transaction()).unwrap(),
1406 vec![
1407 1, 120, 138, 162, 185, 59, 209, 241, 157, 71, 157, 74, 131, 4, 87, 54, 28, 38, 180,
1408 222, 82, 64, 62, 61, 62, 22, 46, 17, 203, 187, 136, 62, 43, 11, 38, 235, 17, 239,
1409 82, 240, 139, 130, 217, 227, 214, 9, 242, 141, 223, 94, 29, 184, 110, 62, 32, 87,
1410 137, 63, 139, 100, 221, 20, 137, 4, 5, 1, 0, 1, 3, 36, 100, 158, 252, 33, 161, 97,
1411 185, 62, 89, 99, 195, 250, 249, 187, 189, 171, 118, 241, 90, 248, 14, 68, 219, 231,
1412 62, 157, 5, 142, 27, 210, 117, 1, 1, 1, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
1413 9, 9, 9, 9, 9, 9, 9, 8, 7, 6, 5, 4, 1, 1, 1, 2, 2, 2, 4, 5, 6, 7, 8, 9, 1, 1, 1, 1,
1414 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 8, 7, 6, 5, 4, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1415 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 1,
1416 3, 1, 2, 3
1417 ]
1418 );
1419 }
1420
1421 #[test]
1422 #[should_panic]
1423 fn test_transaction_missing_key() {
1424 let keypair = Keypair::new();
1425 let message = Message::new(&[], None);
1426 Transaction::new_unsigned(message).sign(&[&keypair], Hash::default());
1427 }
1428
1429 #[test]
1430 #[should_panic]
1431 fn test_partial_sign_mismatched_key() {
1432 let keypair = Keypair::new();
1433 let fee_payer = clone_solana_pubkey::new_rand();
1434 let ix = Instruction::new_with_bincode(
1435 Pubkey::default(),
1436 &0,
1437 vec![AccountMeta::new(fee_payer, true)],
1438 );
1439 let message = Message::new(&[ix], Some(&fee_payer));
1440 Transaction::new_unsigned(message).partial_sign(&[&keypair], Hash::default());
1441 }
1442
1443 #[test]
1444 fn test_partial_sign() {
1445 let keypair0 = Keypair::new();
1446 let keypair1 = Keypair::new();
1447 let keypair2 = Keypair::new();
1448 let ix = Instruction::new_with_bincode(
1449 Pubkey::default(),
1450 &0,
1451 vec![
1452 AccountMeta::new(keypair0.pubkey(), true),
1453 AccountMeta::new(keypair1.pubkey(), true),
1454 AccountMeta::new(keypair2.pubkey(), true),
1455 ],
1456 );
1457 let message = Message::new(&[ix], Some(&keypair0.pubkey()));
1458 let mut tx = Transaction::new_unsigned(message);
1459
1460 tx.partial_sign(&[&keypair0, &keypair2], Hash::default());
1461 assert!(!tx.is_signed());
1462 tx.partial_sign(&[&keypair1], Hash::default());
1463 assert!(tx.is_signed());
1464
1465 let hash = hash(&[1]);
1466 tx.partial_sign(&[&keypair1], hash);
1467 assert!(!tx.is_signed());
1468 tx.partial_sign(&[&keypair0, &keypair2], hash);
1469 assert!(tx.is_signed());
1470 }
1471
1472 #[test]
1473 #[should_panic]
1474 fn test_transaction_missing_keypair() {
1475 let program_id = Pubkey::default();
1476 let keypair0 = Keypair::new();
1477 let id0 = keypair0.pubkey();
1478 let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]);
1479 let message = Message::new(&[ix], Some(&id0));
1480 Transaction::new_unsigned(message).sign(&Vec::<&Keypair>::new(), Hash::default());
1481 }
1482
1483 #[test]
1484 #[should_panic]
1485 fn test_transaction_wrong_key() {
1486 let program_id = Pubkey::default();
1487 let keypair0 = Keypair::new();
1488 let wrong_id = Pubkey::default();
1489 let ix =
1490 Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(wrong_id, true)]);
1491 let message = Message::new(&[ix], Some(&wrong_id));
1492 Transaction::new_unsigned(message).sign(&[&keypair0], Hash::default());
1493 }
1494
1495 #[test]
1496 fn test_transaction_correct_key() {
1497 let program_id = Pubkey::default();
1498 let keypair0 = Keypair::new();
1499 let id0 = keypair0.pubkey();
1500 let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]);
1501 let message = Message::new(&[ix], Some(&id0));
1502 let mut tx = Transaction::new_unsigned(message);
1503 tx.sign(&[&keypair0], Hash::default());
1504 assert_eq!(
1505 tx.message.instructions[0],
1506 CompiledInstruction::new(1, &0, vec![0])
1507 );
1508 assert!(tx.is_signed());
1509 }
1510
1511 #[test]
1512 fn test_transaction_instruction_with_duplicate_keys() {
1513 let program_id = Pubkey::default();
1514 let keypair0 = Keypair::new();
1515 let id0 = keypair0.pubkey();
1516 let id1 = clone_solana_pubkey::new_rand();
1517 let ix = Instruction::new_with_bincode(
1518 program_id,
1519 &0,
1520 vec![
1521 AccountMeta::new(id0, true),
1522 AccountMeta::new(id1, false),
1523 AccountMeta::new(id0, false),
1524 AccountMeta::new(id1, false),
1525 ],
1526 );
1527 let message = Message::new(&[ix], Some(&id0));
1528 let mut tx = Transaction::new_unsigned(message);
1529 tx.sign(&[&keypair0], Hash::default());
1530 assert_eq!(
1531 tx.message.instructions[0],
1532 CompiledInstruction::new(2, &0, vec![0, 1, 0, 1])
1533 );
1534 assert!(tx.is_signed());
1535 }
1536
1537 #[test]
1538 fn test_try_sign_dyn_keypairs() {
1539 let program_id = Pubkey::default();
1540 let keypair = Keypair::new();
1541 let pubkey = keypair.pubkey();
1542 let presigner_keypair = Keypair::new();
1543 let presigner_pubkey = presigner_keypair.pubkey();
1544
1545 let ix = Instruction::new_with_bincode(
1546 program_id,
1547 &0,
1548 vec![
1549 AccountMeta::new(pubkey, true),
1550 AccountMeta::new(presigner_pubkey, true),
1551 ],
1552 );
1553 let message = Message::new(&[ix], Some(&pubkey));
1554 let mut tx = Transaction::new_unsigned(message);
1555
1556 let presigner_sig = presigner_keypair.sign_message(&tx.message_data());
1557 let presigner = Presigner::new(&presigner_pubkey, &presigner_sig);
1558
1559 let signers: Vec<&dyn Signer> = vec![&keypair, &presigner];
1560
1561 let res = tx.try_sign(&signers, Hash::default());
1562 assert_eq!(res, Ok(()));
1563 assert_eq!(tx.signatures[0], keypair.sign_message(&tx.message_data()));
1564 assert_eq!(tx.signatures[1], presigner_sig);
1565
1566 // Wrong key should error, not panic
1567 let another_pubkey = clone_solana_pubkey::new_rand();
1568 let ix = Instruction::new_with_bincode(
1569 program_id,
1570 &0,
1571 vec![
1572 AccountMeta::new(another_pubkey, true),
1573 AccountMeta::new(presigner_pubkey, true),
1574 ],
1575 );
1576 let message = Message::new(&[ix], Some(&another_pubkey));
1577 let mut tx = Transaction::new_unsigned(message);
1578
1579 let res = tx.try_sign(&signers, Hash::default());
1580 assert!(res.is_err());
1581 assert_eq!(
1582 tx.signatures,
1583 vec![Signature::default(), Signature::default()]
1584 );
1585 }
1586
1587 fn nonced_transfer_tx() -> (Pubkey, Pubkey, Transaction) {
1588 let from_keypair = Keypair::new();
1589 let from_pubkey = from_keypair.pubkey();
1590 let nonce_keypair = Keypair::new();
1591 let nonce_pubkey = nonce_keypair.pubkey();
1592 let instructions = [
1593 system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
1594 system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42),
1595 ];
1596 let message = Message::new(&instructions, Some(&nonce_pubkey));
1597 let tx = Transaction::new(&[&from_keypair, &nonce_keypair], message, Hash::default());
1598 (from_pubkey, nonce_pubkey, tx)
1599 }
1600
1601 #[test]
1602 fn tx_uses_nonce_ok() {
1603 let (_, _, tx) = nonced_transfer_tx();
1604 assert!(uses_durable_nonce(&tx).is_some());
1605 }
1606
1607 #[test]
1608 fn tx_uses_nonce_empty_ix_fail() {
1609 assert!(uses_durable_nonce(&Transaction::default()).is_none());
1610 }
1611
1612 #[test]
1613 fn tx_uses_nonce_bad_prog_id_idx_fail() {
1614 let (_, _, mut tx) = nonced_transfer_tx();
1615 tx.message.instructions.get_mut(0).unwrap().program_id_index = 255u8;
1616 assert!(uses_durable_nonce(&tx).is_none());
1617 }
1618
1619 #[test]
1620 fn tx_uses_nonce_first_prog_id_not_nonce_fail() {
1621 let from_keypair = Keypair::new();
1622 let from_pubkey = from_keypair.pubkey();
1623 let nonce_keypair = Keypair::new();
1624 let nonce_pubkey = nonce_keypair.pubkey();
1625 let instructions = [
1626 system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42),
1627 system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
1628 ];
1629 let message = Message::new(&instructions, Some(&from_pubkey));
1630 let tx = Transaction::new(&[&from_keypair, &nonce_keypair], message, Hash::default());
1631 assert!(uses_durable_nonce(&tx).is_none());
1632 }
1633
1634 #[test]
1635 fn tx_uses_nonce_wrong_first_nonce_ix_fail() {
1636 let from_keypair = Keypair::new();
1637 let from_pubkey = from_keypair.pubkey();
1638 let nonce_keypair = Keypair::new();
1639 let nonce_pubkey = nonce_keypair.pubkey();
1640 let instructions = [
1641 system_instruction::withdraw_nonce_account(
1642 &nonce_pubkey,
1643 &nonce_pubkey,
1644 &from_pubkey,
1645 42,
1646 ),
1647 system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42),
1648 ];
1649 let message = Message::new(&instructions, Some(&nonce_pubkey));
1650 let tx = Transaction::new(&[&from_keypair, &nonce_keypair], message, Hash::default());
1651 assert!(uses_durable_nonce(&tx).is_none());
1652 }
1653
1654 #[test]
1655 fn tx_keypair_pubkey_mismatch() {
1656 let from_keypair = Keypair::new();
1657 let from_pubkey = from_keypair.pubkey();
1658 let to_pubkey = Pubkey::new_unique();
1659 let instructions = [system_instruction::transfer(&from_pubkey, &to_pubkey, 42)];
1660 let mut tx = Transaction::new_with_payer(&instructions, Some(&from_pubkey));
1661 let unused_keypair = Keypair::new();
1662 let err = tx
1663 .try_partial_sign(&[&from_keypair, &unused_keypair], Hash::default())
1664 .unwrap_err();
1665 assert_eq!(err, SignerError::KeypairPubkeyMismatch);
1666 }
1667
1668 #[test]
1669 fn test_unsized_signers() {
1670 fn instructions_to_tx(
1671 instructions: &[Instruction],
1672 signers: Box<dyn Signers>,
1673 ) -> Transaction {
1674 let pubkeys = signers.pubkeys();
1675 let first_signer = pubkeys.first().expect("should exist");
1676 let message = Message::new(instructions, Some(first_signer));
1677 Transaction::new(signers.as_ref(), message, Hash::default())
1678 }
1679
1680 let signer: Box<dyn Signer> = Box::new(Keypair::new());
1681 let tx = instructions_to_tx(&[], Box::new(vec![signer]));
1682
1683 assert!(tx.is_signed());
1684 }
1685
1686 #[test]
1687 fn test_replace_signatures() {
1688 let program_id = Pubkey::default();
1689 let keypair0 = Keypair::new();
1690 let keypair1 = Keypair::new();
1691 let pubkey0 = keypair0.pubkey();
1692 let pubkey1 = keypair1.pubkey();
1693 let ix = Instruction::new_with_bincode(
1694 program_id,
1695 &0,
1696 vec![
1697 AccountMeta::new(pubkey0, true),
1698 AccountMeta::new(pubkey1, true),
1699 ],
1700 );
1701 let message = Message::new(&[ix], Some(&pubkey0));
1702 let expected_account_keys = message.account_keys.clone();
1703 let mut tx = Transaction::new_unsigned(message);
1704 tx.sign(&[&keypair0, &keypair1], Hash::new_unique());
1705
1706 let signature0 = keypair0.sign_message(&tx.message_data());
1707 let signature1 = keypair1.sign_message(&tx.message_data());
1708
1709 // Replace signatures with order swapped
1710 tx.replace_signatures(&[(pubkey1, signature1), (pubkey0, signature0)])
1711 .unwrap();
1712 // Order of account_keys should not change
1713 assert_eq!(tx.message.account_keys, expected_account_keys);
1714 // Order of signatures should match original account_keys list
1715 assert_eq!(tx.signatures, &[signature0, signature1]);
1716 }
1717}