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