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    /// Verify the precompiled programs in this transaction.
1062    pub fn verify_precompiles(&self, feature_set: &solana_feature_set::FeatureSet) -> Result<()> {
1063        for instruction in &self.message().instructions {
1064            // The Transaction may not be sanitized at this point
1065            if instruction.program_id_index as usize >= self.message().account_keys.len() {
1066                return Err(TransactionError::AccountNotFound);
1067            }
1068            let program_id = &self.message().account_keys[instruction.program_id_index as usize];
1069
1070            solana_precompiles::verify_if_precompile(
1071                program_id,
1072                instruction,
1073                &self.message().instructions,
1074                feature_set,
1075            )
1076            .map_err(|_| TransactionError::InvalidAccountIndex)?;
1077        }
1078        Ok(())
1079    }
1080
1081    /// Get the positions of the pubkeys in `account_keys` associated with signing keypairs.
1082    ///
1083    /// [`account_keys`]: Message::account_keys
1084    pub fn get_signing_keypair_positions(&self, pubkeys: &[Pubkey]) -> Result<Vec<Option<usize>>> {
1085        if self.message.account_keys.len() < self.message.header.num_required_signatures as usize {
1086            return Err(TransactionError::InvalidAccountIndex);
1087        }
1088        let signed_keys =
1089            &self.message.account_keys[0..self.message.header.num_required_signatures as usize];
1090
1091        Ok(pubkeys
1092            .iter()
1093            .map(|pubkey| signed_keys.iter().position(|x| x == pubkey))
1094            .collect())
1095    }
1096
1097    #[cfg(feature = "verify")]
1098    /// Replace all the signatures and pubkeys.
1099    pub fn replace_signatures(&mut self, signers: &[(Pubkey, Signature)]) -> Result<()> {
1100        let num_required_signatures = self.message.header.num_required_signatures as usize;
1101        if signers.len() != num_required_signatures
1102            || self.signatures.len() != num_required_signatures
1103            || self.message.account_keys.len() < num_required_signatures
1104        {
1105            return Err(TransactionError::InvalidAccountIndex);
1106        }
1107
1108        for (index, account_key) in self
1109            .message
1110            .account_keys
1111            .iter()
1112            .enumerate()
1113            .take(num_required_signatures)
1114        {
1115            if let Some((_pubkey, signature)) =
1116                signers.iter().find(|(key, _signature)| account_key == key)
1117            {
1118                self.signatures[index] = *signature
1119            } else {
1120                return Err(TransactionError::InvalidAccountIndex);
1121            }
1122        }
1123
1124        self.verify()
1125    }
1126
1127    pub fn is_signed(&self) -> bool {
1128        self.signatures
1129            .iter()
1130            .all(|signature| *signature != Signature::default())
1131    }
1132}
1133
1134#[cfg(feature = "bincode")]
1135/// Returns true if transaction begins with an advance nonce instruction.
1136pub fn uses_durable_nonce(tx: &Transaction) -> Option<&CompiledInstruction> {
1137    let message = tx.message();
1138    message
1139        .instructions
1140        .get(NONCED_TX_MARKER_IX_INDEX as usize)
1141        .filter(|instruction| {
1142            // Is system program
1143            matches!(
1144                message.account_keys.get(instruction.program_id_index as usize),
1145                Some(program_id) if system_program::check_id(program_id)
1146            )
1147            // Is a nonce advance instruction
1148            && matches!(
1149                limited_deserialize(&instruction.data, PACKET_DATA_SIZE as u64),
1150                Ok(SystemInstruction::AdvanceNonceAccount)
1151            )
1152        })
1153}
1154
1155#[cfg(test)]
1156mod tests {
1157    #![allow(deprecated)]
1158
1159    use {
1160        super::*,
1161        bincode::{deserialize, serialize, serialized_size},
1162        solana_instruction::AccountMeta,
1163        solana_keypair::Keypair,
1164        solana_presigner::Presigner,
1165        solana_sha256_hasher::hash,
1166        solana_signer::Signer,
1167        solana_system_interface::instruction as system_instruction,
1168        std::mem::size_of,
1169    };
1170
1171    fn get_program_id(tx: &Transaction, instruction_index: usize) -> &Pubkey {
1172        let message = tx.message();
1173        let instruction = &message.instructions[instruction_index];
1174        instruction.program_id(&message.account_keys)
1175    }
1176
1177    #[test]
1178    fn test_refs() {
1179        let key = Keypair::new();
1180        let key1 = solana_pubkey::new_rand();
1181        let key2 = solana_pubkey::new_rand();
1182        let prog1 = solana_pubkey::new_rand();
1183        let prog2 = solana_pubkey::new_rand();
1184        let instructions = vec![
1185            CompiledInstruction::new(3, &(), vec![0, 1]),
1186            CompiledInstruction::new(4, &(), vec![0, 2]),
1187        ];
1188        let tx = Transaction::new_with_compiled_instructions(
1189            &[&key],
1190            &[key1, key2],
1191            Hash::default(),
1192            vec![prog1, prog2],
1193            instructions,
1194        );
1195        assert!(tx.sanitize().is_ok());
1196
1197        assert_eq!(tx.key(0, 0), Some(&key.pubkey()));
1198        assert_eq!(tx.signer_key(0, 0), Some(&key.pubkey()));
1199
1200        assert_eq!(tx.key(1, 0), Some(&key.pubkey()));
1201        assert_eq!(tx.signer_key(1, 0), Some(&key.pubkey()));
1202
1203        assert_eq!(tx.key(0, 1), Some(&key1));
1204        assert_eq!(tx.signer_key(0, 1), None);
1205
1206        assert_eq!(tx.key(1, 1), Some(&key2));
1207        assert_eq!(tx.signer_key(1, 1), None);
1208
1209        assert_eq!(tx.key(2, 0), None);
1210        assert_eq!(tx.signer_key(2, 0), None);
1211
1212        assert_eq!(tx.key(0, 2), None);
1213        assert_eq!(tx.signer_key(0, 2), None);
1214
1215        assert_eq!(*get_program_id(&tx, 0), prog1);
1216        assert_eq!(*get_program_id(&tx, 1), prog2);
1217    }
1218
1219    #[test]
1220    fn test_refs_invalid_program_id() {
1221        let key = Keypair::new();
1222        let instructions = vec![CompiledInstruction::new(1, &(), vec![])];
1223        let tx = Transaction::new_with_compiled_instructions(
1224            &[&key],
1225            &[],
1226            Hash::default(),
1227            vec![],
1228            instructions,
1229        );
1230        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1231    }
1232    #[test]
1233    fn test_refs_invalid_account() {
1234        let key = Keypair::new();
1235        let instructions = vec![CompiledInstruction::new(1, &(), vec![2])];
1236        let tx = Transaction::new_with_compiled_instructions(
1237            &[&key],
1238            &[],
1239            Hash::default(),
1240            vec![Pubkey::default()],
1241            instructions,
1242        );
1243        assert_eq!(*get_program_id(&tx, 0), Pubkey::default());
1244        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1245    }
1246
1247    #[test]
1248    fn test_sanitize_txs() {
1249        let key = Keypair::new();
1250        let id0 = Pubkey::default();
1251        let program_id = solana_pubkey::new_rand();
1252        let ix = Instruction::new_with_bincode(
1253            program_id,
1254            &0,
1255            vec![
1256                AccountMeta::new(key.pubkey(), true),
1257                AccountMeta::new(id0, true),
1258            ],
1259        );
1260        let mut tx = Transaction::new_with_payer(&[ix], Some(&key.pubkey()));
1261        let o = tx.clone();
1262        assert_eq!(tx.sanitize(), Ok(()));
1263        assert_eq!(tx.message.account_keys.len(), 3);
1264
1265        tx = o.clone();
1266        tx.message.header.num_required_signatures = 3;
1267        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1268
1269        tx = o.clone();
1270        tx.message.header.num_readonly_signed_accounts = 4;
1271        tx.message.header.num_readonly_unsigned_accounts = 0;
1272        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1273
1274        tx = o.clone();
1275        tx.message.header.num_readonly_signed_accounts = 2;
1276        tx.message.header.num_readonly_unsigned_accounts = 2;
1277        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1278
1279        tx = o.clone();
1280        tx.message.header.num_readonly_signed_accounts = 0;
1281        tx.message.header.num_readonly_unsigned_accounts = 4;
1282        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1283
1284        tx = o.clone();
1285        tx.message.instructions[0].program_id_index = 3;
1286        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1287
1288        tx = o.clone();
1289        tx.message.instructions[0].accounts[0] = 3;
1290        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1291
1292        tx = o.clone();
1293        tx.message.instructions[0].program_id_index = 0;
1294        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1295
1296        tx = o.clone();
1297        tx.message.header.num_readonly_signed_accounts = 2;
1298        tx.message.header.num_readonly_unsigned_accounts = 3;
1299        tx.message.account_keys.resize(4, Pubkey::default());
1300        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1301
1302        tx = o;
1303        tx.message.header.num_readonly_signed_accounts = 2;
1304        tx.message.header.num_required_signatures = 1;
1305        assert_eq!(tx.sanitize(), Err(SanitizeError::IndexOutOfBounds));
1306    }
1307
1308    fn create_sample_transaction() -> Transaction {
1309        let keypair = Keypair::from_bytes(&[
1310            255, 101, 36, 24, 124, 23, 167, 21, 132, 204, 155, 5, 185, 58, 121, 75, 156, 227, 116,
1311            193, 215, 38, 142, 22, 8, 14, 229, 239, 119, 93, 5, 218, 36, 100, 158, 252, 33, 161,
1312            97, 185, 62, 89, 99, 195, 250, 249, 187, 189, 171, 118, 241, 90, 248, 14, 68, 219, 231,
1313            62, 157, 5, 142, 27, 210, 117,
1314        ])
1315        .unwrap();
1316        let to = Pubkey::from([
1317            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,
1318            1, 1, 1,
1319        ]);
1320
1321        let program_id = Pubkey::from([
1322            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,
1323            2, 2, 2,
1324        ]);
1325        let account_metas = vec![
1326            AccountMeta::new(keypair.pubkey(), true),
1327            AccountMeta::new(to, false),
1328        ];
1329        let instruction =
1330            Instruction::new_with_bincode(program_id, &(1u8, 2u8, 3u8), account_metas);
1331        let message = Message::new(&[instruction], Some(&keypair.pubkey()));
1332        let tx = Transaction::new(&[&keypair], message, Hash::default());
1333        tx.verify().expect("valid sample transaction signatures");
1334        tx
1335    }
1336
1337    #[test]
1338    fn test_transaction_serialize() {
1339        let tx = create_sample_transaction();
1340        let ser = serialize(&tx).unwrap();
1341        let deser = deserialize(&ser).unwrap();
1342        assert_eq!(tx, deser);
1343    }
1344
1345    /// Detect changes to the serialized size of payment transactions, which affects TPS.
1346    #[test]
1347    fn test_transaction_minimum_serialized_size() {
1348        let alice_keypair = Keypair::new();
1349        let alice_pubkey = alice_keypair.pubkey();
1350        let bob_pubkey = solana_pubkey::new_rand();
1351        let ix = system_instruction::transfer(&alice_pubkey, &bob_pubkey, 42);
1352
1353        let expected_data_size = size_of::<u32>() + size_of::<u64>();
1354        assert_eq!(expected_data_size, 12);
1355        assert_eq!(
1356            ix.data.len(),
1357            expected_data_size,
1358            "unexpected system instruction size"
1359        );
1360
1361        let expected_instruction_size = 1 + 1 + ix.accounts.len() + 1 + expected_data_size;
1362        assert_eq!(expected_instruction_size, 17);
1363
1364        let message = Message::new(&[ix], Some(&alice_pubkey));
1365        assert_eq!(
1366            serialized_size(&message.instructions[0]).unwrap() as usize,
1367            expected_instruction_size,
1368            "unexpected Instruction::serialized_size"
1369        );
1370
1371        let tx = Transaction::new(&[&alice_keypair], message, Hash::default());
1372
1373        let len_size = 1;
1374        let num_required_sigs_size = 1;
1375        let num_readonly_accounts_size = 2;
1376        let blockhash_size = size_of::<Hash>();
1377        let expected_transaction_size = len_size
1378            + (tx.signatures.len() * size_of::<Signature>())
1379            + num_required_sigs_size
1380            + num_readonly_accounts_size
1381            + len_size
1382            + (tx.message.account_keys.len() * size_of::<Pubkey>())
1383            + blockhash_size
1384            + len_size
1385            + expected_instruction_size;
1386        assert_eq!(expected_transaction_size, 215);
1387
1388        assert_eq!(
1389            serialized_size(&tx).unwrap() as usize,
1390            expected_transaction_size,
1391            "unexpected serialized transaction size"
1392        );
1393    }
1394
1395    /// Detect binary changes in the serialized transaction data, which could have a downstream
1396    /// affect on SDKs and applications
1397    #[test]
1398    fn test_sdk_serialize() {
1399        assert_eq!(
1400            serialize(&create_sample_transaction()).unwrap(),
1401            vec![
1402                1, 120, 138, 162, 185, 59, 209, 241, 157, 71, 157, 74, 131, 4, 87, 54, 28, 38, 180,
1403                222, 82, 64, 62, 61, 62, 22, 46, 17, 203, 187, 136, 62, 43, 11, 38, 235, 17, 239,
1404                82, 240, 139, 130, 217, 227, 214, 9, 242, 141, 223, 94, 29, 184, 110, 62, 32, 87,
1405                137, 63, 139, 100, 221, 20, 137, 4, 5, 1, 0, 1, 3, 36, 100, 158, 252, 33, 161, 97,
1406                185, 62, 89, 99, 195, 250, 249, 187, 189, 171, 118, 241, 90, 248, 14, 68, 219, 231,
1407                62, 157, 5, 142, 27, 210, 117, 1, 1, 1, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
1408                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,
1409                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,
1410                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,
1411                3, 1, 2, 3
1412            ]
1413        );
1414    }
1415
1416    #[test]
1417    #[should_panic]
1418    fn test_transaction_missing_key() {
1419        let keypair = Keypair::new();
1420        let message = Message::new(&[], None);
1421        Transaction::new_unsigned(message).sign(&[&keypair], Hash::default());
1422    }
1423
1424    #[test]
1425    #[should_panic]
1426    fn test_partial_sign_mismatched_key() {
1427        let keypair = Keypair::new();
1428        let fee_payer = solana_pubkey::new_rand();
1429        let ix = Instruction::new_with_bincode(
1430            Pubkey::default(),
1431            &0,
1432            vec![AccountMeta::new(fee_payer, true)],
1433        );
1434        let message = Message::new(&[ix], Some(&fee_payer));
1435        Transaction::new_unsigned(message).partial_sign(&[&keypair], Hash::default());
1436    }
1437
1438    #[test]
1439    fn test_partial_sign() {
1440        let keypair0 = Keypair::new();
1441        let keypair1 = Keypair::new();
1442        let keypair2 = Keypair::new();
1443        let ix = Instruction::new_with_bincode(
1444            Pubkey::default(),
1445            &0,
1446            vec![
1447                AccountMeta::new(keypair0.pubkey(), true),
1448                AccountMeta::new(keypair1.pubkey(), true),
1449                AccountMeta::new(keypair2.pubkey(), true),
1450            ],
1451        );
1452        let message = Message::new(&[ix], Some(&keypair0.pubkey()));
1453        let mut tx = Transaction::new_unsigned(message);
1454
1455        tx.partial_sign(&[&keypair0, &keypair2], Hash::default());
1456        assert!(!tx.is_signed());
1457        tx.partial_sign(&[&keypair1], Hash::default());
1458        assert!(tx.is_signed());
1459
1460        let hash = hash(&[1]);
1461        tx.partial_sign(&[&keypair1], hash);
1462        assert!(!tx.is_signed());
1463        tx.partial_sign(&[&keypair0, &keypair2], hash);
1464        assert!(tx.is_signed());
1465    }
1466
1467    #[test]
1468    #[should_panic]
1469    fn test_transaction_missing_keypair() {
1470        let program_id = Pubkey::default();
1471        let keypair0 = Keypair::new();
1472        let id0 = keypair0.pubkey();
1473        let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]);
1474        let message = Message::new(&[ix], Some(&id0));
1475        Transaction::new_unsigned(message).sign(&Vec::<&Keypair>::new(), Hash::default());
1476    }
1477
1478    #[test]
1479    #[should_panic]
1480    fn test_transaction_wrong_key() {
1481        let program_id = Pubkey::default();
1482        let keypair0 = Keypair::new();
1483        let wrong_id = Pubkey::default();
1484        let ix =
1485            Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(wrong_id, true)]);
1486        let message = Message::new(&[ix], Some(&wrong_id));
1487        Transaction::new_unsigned(message).sign(&[&keypair0], Hash::default());
1488    }
1489
1490    #[test]
1491    fn test_transaction_correct_key() {
1492        let program_id = Pubkey::default();
1493        let keypair0 = Keypair::new();
1494        let id0 = keypair0.pubkey();
1495        let ix = Instruction::new_with_bincode(program_id, &0, vec![AccountMeta::new(id0, true)]);
1496        let message = Message::new(&[ix], Some(&id0));
1497        let mut tx = Transaction::new_unsigned(message);
1498        tx.sign(&[&keypair0], Hash::default());
1499        assert_eq!(
1500            tx.message.instructions[0],
1501            CompiledInstruction::new(1, &0, vec![0])
1502        );
1503        assert!(tx.is_signed());
1504    }
1505
1506    #[test]
1507    fn test_transaction_instruction_with_duplicate_keys() {
1508        let program_id = Pubkey::default();
1509        let keypair0 = Keypair::new();
1510        let id0 = keypair0.pubkey();
1511        let id1 = solana_pubkey::new_rand();
1512        let ix = Instruction::new_with_bincode(
1513            program_id,
1514            &0,
1515            vec![
1516                AccountMeta::new(id0, true),
1517                AccountMeta::new(id1, false),
1518                AccountMeta::new(id0, false),
1519                AccountMeta::new(id1, false),
1520            ],
1521        );
1522        let message = Message::new(&[ix], Some(&id0));
1523        let mut tx = Transaction::new_unsigned(message);
1524        tx.sign(&[&keypair0], Hash::default());
1525        assert_eq!(
1526            tx.message.instructions[0],
1527            CompiledInstruction::new(2, &0, vec![0, 1, 0, 1])
1528        );
1529        assert!(tx.is_signed());
1530    }
1531
1532    #[test]
1533    fn test_try_sign_dyn_keypairs() {
1534        let program_id = Pubkey::default();
1535        let keypair = Keypair::new();
1536        let pubkey = keypair.pubkey();
1537        let presigner_keypair = Keypair::new();
1538        let presigner_pubkey = presigner_keypair.pubkey();
1539
1540        let ix = Instruction::new_with_bincode(
1541            program_id,
1542            &0,
1543            vec![
1544                AccountMeta::new(pubkey, true),
1545                AccountMeta::new(presigner_pubkey, true),
1546            ],
1547        );
1548        let message = Message::new(&[ix], Some(&pubkey));
1549        let mut tx = Transaction::new_unsigned(message);
1550
1551        let presigner_sig = presigner_keypair.sign_message(&tx.message_data());
1552        let presigner = Presigner::new(&presigner_pubkey, &presigner_sig);
1553
1554        let signers: Vec<&dyn Signer> = vec![&keypair, &presigner];
1555
1556        let res = tx.try_sign(&signers, Hash::default());
1557        assert_eq!(res, Ok(()));
1558        assert_eq!(tx.signatures[0], keypair.sign_message(&tx.message_data()));
1559        assert_eq!(tx.signatures[1], presigner_sig);
1560
1561        // Wrong key should error, not panic
1562        let another_pubkey = solana_pubkey::new_rand();
1563        let ix = Instruction::new_with_bincode(
1564            program_id,
1565            &0,
1566            vec![
1567                AccountMeta::new(another_pubkey, true),
1568                AccountMeta::new(presigner_pubkey, true),
1569            ],
1570        );
1571        let message = Message::new(&[ix], Some(&another_pubkey));
1572        let mut tx = Transaction::new_unsigned(message);
1573
1574        let res = tx.try_sign(&signers, Hash::default());
1575        assert!(res.is_err());
1576        assert_eq!(
1577            tx.signatures,
1578            vec![Signature::default(), Signature::default()]
1579        );
1580    }
1581
1582    fn nonced_transfer_tx() -> (Pubkey, Pubkey, Transaction) {
1583        let from_keypair = Keypair::new();
1584        let from_pubkey = from_keypair.pubkey();
1585        let nonce_keypair = Keypair::new();
1586        let nonce_pubkey = nonce_keypair.pubkey();
1587        let instructions = [
1588            system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
1589            system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42),
1590        ];
1591        let message = Message::new(&instructions, Some(&nonce_pubkey));
1592        let tx = Transaction::new(&[&from_keypair, &nonce_keypair], message, Hash::default());
1593        (from_pubkey, nonce_pubkey, tx)
1594    }
1595
1596    #[test]
1597    fn tx_uses_nonce_ok() {
1598        let (_, _, tx) = nonced_transfer_tx();
1599        assert!(uses_durable_nonce(&tx).is_some());
1600    }
1601
1602    #[test]
1603    fn tx_uses_nonce_empty_ix_fail() {
1604        assert!(uses_durable_nonce(&Transaction::default()).is_none());
1605    }
1606
1607    #[test]
1608    fn tx_uses_nonce_bad_prog_id_idx_fail() {
1609        let (_, _, mut tx) = nonced_transfer_tx();
1610        tx.message.instructions.get_mut(0).unwrap().program_id_index = 255u8;
1611        assert!(uses_durable_nonce(&tx).is_none());
1612    }
1613
1614    #[test]
1615    fn tx_uses_nonce_first_prog_id_not_nonce_fail() {
1616        let from_keypair = Keypair::new();
1617        let from_pubkey = from_keypair.pubkey();
1618        let nonce_keypair = Keypair::new();
1619        let nonce_pubkey = nonce_keypair.pubkey();
1620        let instructions = [
1621            system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42),
1622            system_instruction::advance_nonce_account(&nonce_pubkey, &nonce_pubkey),
1623        ];
1624        let message = Message::new(&instructions, Some(&from_pubkey));
1625        let tx = Transaction::new(&[&from_keypair, &nonce_keypair], message, Hash::default());
1626        assert!(uses_durable_nonce(&tx).is_none());
1627    }
1628
1629    #[test]
1630    fn tx_uses_nonce_wrong_first_nonce_ix_fail() {
1631        let from_keypair = Keypair::new();
1632        let from_pubkey = from_keypair.pubkey();
1633        let nonce_keypair = Keypair::new();
1634        let nonce_pubkey = nonce_keypair.pubkey();
1635        let instructions = [
1636            system_instruction::withdraw_nonce_account(
1637                &nonce_pubkey,
1638                &nonce_pubkey,
1639                &from_pubkey,
1640                42,
1641            ),
1642            system_instruction::transfer(&from_pubkey, &nonce_pubkey, 42),
1643        ];
1644        let message = Message::new(&instructions, Some(&nonce_pubkey));
1645        let tx = Transaction::new(&[&from_keypair, &nonce_keypair], message, Hash::default());
1646        assert!(uses_durable_nonce(&tx).is_none());
1647    }
1648
1649    #[test]
1650    fn tx_keypair_pubkey_mismatch() {
1651        let from_keypair = Keypair::new();
1652        let from_pubkey = from_keypair.pubkey();
1653        let to_pubkey = Pubkey::new_unique();
1654        let instructions = [system_instruction::transfer(&from_pubkey, &to_pubkey, 42)];
1655        let mut tx = Transaction::new_with_payer(&instructions, Some(&from_pubkey));
1656        let unused_keypair = Keypair::new();
1657        let err = tx
1658            .try_partial_sign(&[&from_keypair, &unused_keypair], Hash::default())
1659            .unwrap_err();
1660        assert_eq!(err, SignerError::KeypairPubkeyMismatch);
1661    }
1662
1663    #[test]
1664    fn test_unsized_signers() {
1665        fn instructions_to_tx(
1666            instructions: &[Instruction],
1667            signers: Box<dyn Signers>,
1668        ) -> Transaction {
1669            let pubkeys = signers.pubkeys();
1670            let first_signer = pubkeys.first().expect("should exist");
1671            let message = Message::new(instructions, Some(first_signer));
1672            Transaction::new(signers.as_ref(), message, Hash::default())
1673        }
1674
1675        let signer: Box<dyn Signer> = Box::new(Keypair::new());
1676        let tx = instructions_to_tx(&[], Box::new(vec![signer]));
1677
1678        assert!(tx.is_signed());
1679    }
1680
1681    #[test]
1682    fn test_replace_signatures() {
1683        let program_id = Pubkey::default();
1684        let keypair0 = Keypair::new();
1685        let keypair1 = Keypair::new();
1686        let pubkey0 = keypair0.pubkey();
1687        let pubkey1 = keypair1.pubkey();
1688        let ix = Instruction::new_with_bincode(
1689            program_id,
1690            &0,
1691            vec![
1692                AccountMeta::new(pubkey0, true),
1693                AccountMeta::new(pubkey1, true),
1694            ],
1695        );
1696        let message = Message::new(&[ix], Some(&pubkey0));
1697        let expected_account_keys = message.account_keys.clone();
1698        let mut tx = Transaction::new_unsigned(message);
1699        tx.sign(&[&keypair0, &keypair1], Hash::new_unique());
1700
1701        let signature0 = keypair0.sign_message(&tx.message_data());
1702        let signature1 = keypair1.sign_message(&tx.message_data());
1703
1704        // Replace signatures with order swapped
1705        tx.replace_signatures(&[(pubkey1, signature1), (pubkey0, signature0)])
1706            .unwrap();
1707        // Order of account_keys should not change
1708        assert_eq!(tx.message.account_keys, expected_account_keys);
1709        // Order of signatures should match original account_keys list
1710        assert_eq!(tx.signatures, &[signature0, signature1]);
1711    }
1712}