solana_cli_output/
display.rs

1use {
2    crate::cli_output::CliSignatureVerificationStatus,
3    base64::{prelude::BASE64_STANDARD, Engine},
4    chrono::{DateTime, Local, SecondsFormat, TimeZone, Utc},
5    console::style,
6    indicatif::{ProgressBar, ProgressStyle},
7    solana_bincode::limited_deserialize,
8    solana_cli_config::SettingType,
9    solana_clock::UnixTimestamp,
10    solana_hash::Hash,
11    solana_message::{compiled_instruction::CompiledInstruction, v0::MessageAddressTableLookup},
12    solana_native_token::lamports_to_sol,
13    solana_program::stake,
14    solana_pubkey::Pubkey,
15    solana_reserved_account_keys::ReservedAccountKeys,
16    solana_signature::Signature,
17    solana_transaction::versioned::{TransactionVersion, VersionedTransaction},
18    solana_transaction_error::TransactionError,
19    solana_transaction_status::{
20        Rewards, UiReturnDataEncoding, UiTransactionReturnData, UiTransactionStatusMeta,
21    },
22    spl_memo::{id as spl_memo_id, v1::id as spl_memo_v1_id},
23    std::{collections::HashMap, fmt, io, time::Duration},
24};
25
26#[derive(Clone, Debug)]
27pub struct BuildBalanceMessageConfig {
28    pub use_lamports_unit: bool,
29    pub show_unit: bool,
30    pub trim_trailing_zeros: bool,
31}
32
33impl Default for BuildBalanceMessageConfig {
34    fn default() -> Self {
35        Self {
36            use_lamports_unit: false,
37            show_unit: true,
38            trim_trailing_zeros: true,
39        }
40    }
41}
42
43fn is_memo_program(k: &Pubkey) -> bool {
44    let k_str = k.to_string();
45    (k_str == spl_memo_v1_id().to_string()) || (k_str == spl_memo_id().to_string())
46}
47
48pub fn build_balance_message_with_config(
49    lamports: u64,
50    config: &BuildBalanceMessageConfig,
51) -> String {
52    let value = if config.use_lamports_unit {
53        lamports.to_string()
54    } else {
55        let sol = lamports_to_sol(lamports);
56        let sol_str = format!("{sol:.9}");
57        if config.trim_trailing_zeros {
58            sol_str
59                .trim_end_matches('0')
60                .trim_end_matches('.')
61                .to_string()
62        } else {
63            sol_str
64        }
65    };
66    let unit = if config.show_unit {
67        if config.use_lamports_unit {
68            let ess = if lamports == 1 { "" } else { "s" };
69            format!(" lamport{ess}")
70        } else {
71            " SOL".to_string()
72        }
73    } else {
74        "".to_string()
75    };
76    format!("{value}{unit}")
77}
78
79pub fn build_balance_message(lamports: u64, use_lamports_unit: bool, show_unit: bool) -> String {
80    build_balance_message_with_config(
81        lamports,
82        &BuildBalanceMessageConfig {
83            use_lamports_unit,
84            show_unit,
85            ..BuildBalanceMessageConfig::default()
86        },
87    )
88}
89
90// Pretty print a "name value"
91pub fn println_name_value(name: &str, value: &str) {
92    let styled_value = if value.is_empty() {
93        style("(not set)").italic()
94    } else {
95        style(value)
96    };
97    println!("{} {}", style(name).bold(), styled_value);
98}
99
100pub fn writeln_name_value(f: &mut dyn fmt::Write, name: &str, value: &str) -> fmt::Result {
101    let styled_value = if value.is_empty() {
102        style("(not set)").italic()
103    } else {
104        style(value)
105    };
106    writeln!(f, "{} {}", style(name).bold(), styled_value)
107}
108
109pub fn println_name_value_or(name: &str, value: &str, setting_type: SettingType) {
110    let description = match setting_type {
111        SettingType::Explicit => "",
112        SettingType::Computed => "(computed)",
113        SettingType::SystemDefault => "(default)",
114    };
115
116    println!(
117        "{} {} {}",
118        style(name).bold(),
119        style(value),
120        style(description).italic(),
121    );
122}
123
124pub fn format_labeled_address(pubkey: &str, address_labels: &HashMap<String, String>) -> String {
125    let label = address_labels.get(pubkey);
126    match label {
127        Some(label) => format!(
128            "{:.31} ({:.4}..{})",
129            label,
130            pubkey,
131            pubkey.split_at(pubkey.len() - 4).1
132        ),
133        None => pubkey.to_string(),
134    }
135}
136
137pub fn println_signers(
138    blockhash: &Hash,
139    signers: &[String],
140    absent: &[String],
141    bad_sig: &[String],
142) {
143    println!();
144    println!("Blockhash: {blockhash}");
145    if !signers.is_empty() {
146        println!("Signers (Pubkey=Signature):");
147        signers.iter().for_each(|signer| println!("  {signer}"))
148    }
149    if !absent.is_empty() {
150        println!("Absent Signers (Pubkey):");
151        absent.iter().for_each(|pubkey| println!("  {pubkey}"))
152    }
153    if !bad_sig.is_empty() {
154        println!("Bad Signatures (Pubkey):");
155        bad_sig.iter().for_each(|pubkey| println!("  {pubkey}"))
156    }
157    println!();
158}
159
160struct CliAccountMeta {
161    is_signer: bool,
162    is_writable: bool,
163    is_invoked: bool,
164}
165
166fn format_account_mode(meta: CliAccountMeta) -> String {
167    format!(
168        "{}r{}{}", // accounts are always readable...
169        if meta.is_signer {
170            "s" // stands for signer
171        } else {
172            "-"
173        },
174        if meta.is_writable {
175            "w" // comment for consistent rust fmt (no joking; lol)
176        } else {
177            "-"
178        },
179        // account may be executable on-chain while not being
180        // designated as a program-id in the message
181        if meta.is_invoked {
182            "x"
183        } else {
184            // programs to be executed via CPI cannot be identified as
185            // executable from the message
186            "-"
187        },
188    )
189}
190
191fn write_transaction<W: io::Write>(
192    w: &mut W,
193    transaction: &VersionedTransaction,
194    transaction_status: Option<&UiTransactionStatusMeta>,
195    prefix: &str,
196    sigverify_status: Option<&[CliSignatureVerificationStatus]>,
197    block_time: Option<UnixTimestamp>,
198    timezone: CliTimezone,
199) -> io::Result<()> {
200    write_block_time(w, block_time, timezone, prefix)?;
201
202    let message = &transaction.message;
203    let account_keys: Vec<AccountKeyType> = {
204        let static_keys_iter = message
205            .static_account_keys()
206            .iter()
207            .map(AccountKeyType::Known);
208        let dynamic_keys: Vec<AccountKeyType> = message
209            .address_table_lookups()
210            .map(transform_lookups_to_unknown_keys)
211            .unwrap_or_default();
212        static_keys_iter.chain(dynamic_keys).collect()
213    };
214
215    write_version(w, transaction.version(), prefix)?;
216    write_recent_blockhash(w, message.recent_blockhash(), prefix)?;
217    write_signatures(w, &transaction.signatures, sigverify_status, prefix)?;
218
219    let reserved_account_keys = ReservedAccountKeys::new_all_activated().active;
220    for (account_index, account) in account_keys.iter().enumerate() {
221        let account_meta = CliAccountMeta {
222            is_signer: message.is_signer(account_index),
223            is_writable: message.is_maybe_writable(account_index, Some(&reserved_account_keys)),
224            is_invoked: message.is_invoked(account_index),
225        };
226
227        let is_fee_payer = account_index == 0;
228        write_account(
229            w,
230            account_index,
231            *account,
232            format_account_mode(account_meta),
233            is_fee_payer,
234            prefix,
235        )?;
236    }
237
238    for (instruction_index, instruction) in message.instructions().iter().enumerate() {
239        let program_pubkey = account_keys[instruction.program_id_index as usize];
240        let instruction_accounts = instruction
241            .accounts
242            .iter()
243            .map(|account_index| (account_keys[*account_index as usize], *account_index));
244
245        write_instruction(
246            w,
247            instruction_index,
248            program_pubkey,
249            instruction,
250            instruction_accounts,
251            prefix,
252        )?;
253    }
254
255    if let Some(address_table_lookups) = message.address_table_lookups() {
256        write_address_table_lookups(w, address_table_lookups, prefix)?;
257    }
258
259    if let Some(transaction_status) = transaction_status {
260        write_status(w, &transaction_status.status, prefix)?;
261        write_fees(w, transaction_status.fee, prefix)?;
262        write_balances(w, transaction_status, prefix)?;
263        write_compute_units_consumed(
264            w,
265            transaction_status.compute_units_consumed.clone().into(),
266            prefix,
267        )?;
268        write_log_messages(w, transaction_status.log_messages.as_ref().into(), prefix)?;
269        write_return_data(w, transaction_status.return_data.as_ref().into(), prefix)?;
270        write_rewards(w, transaction_status.rewards.as_ref().into(), prefix)?;
271    } else {
272        writeln!(w, "{prefix}Status: Unavailable")?;
273    }
274
275    Ok(())
276}
277
278fn transform_lookups_to_unknown_keys(lookups: &[MessageAddressTableLookup]) -> Vec<AccountKeyType> {
279    let unknown_writable_keys = lookups
280        .iter()
281        .enumerate()
282        .flat_map(|(lookup_index, lookup)| {
283            lookup
284                .writable_indexes
285                .iter()
286                .map(move |table_index| AccountKeyType::Unknown {
287                    lookup_index,
288                    table_index: *table_index,
289                })
290        });
291
292    let unknown_readonly_keys = lookups
293        .iter()
294        .enumerate()
295        .flat_map(|(lookup_index, lookup)| {
296            lookup
297                .readonly_indexes
298                .iter()
299                .map(move |table_index| AccountKeyType::Unknown {
300                    lookup_index,
301                    table_index: *table_index,
302                })
303        });
304
305    unknown_writable_keys.chain(unknown_readonly_keys).collect()
306}
307
308enum CliTimezone {
309    Local,
310    #[allow(dead_code)]
311    Utc,
312}
313
314fn write_block_time<W: io::Write>(
315    w: &mut W,
316    block_time: Option<UnixTimestamp>,
317    timezone: CliTimezone,
318    prefix: &str,
319) -> io::Result<()> {
320    if let Some(block_time) = block_time {
321        let block_time_output = match timezone {
322            CliTimezone::Local => format!("{:?}", Local.timestamp_opt(block_time, 0).unwrap()),
323            CliTimezone::Utc => format!("{:?}", Utc.timestamp_opt(block_time, 0).unwrap()),
324        };
325        writeln!(w, "{prefix}Block Time: {block_time_output}",)?;
326    }
327    Ok(())
328}
329
330fn write_version<W: io::Write>(
331    w: &mut W,
332    version: TransactionVersion,
333    prefix: &str,
334) -> io::Result<()> {
335    let version = match version {
336        TransactionVersion::Legacy(_) => "legacy".to_string(),
337        TransactionVersion::Number(number) => number.to_string(),
338    };
339    writeln!(w, "{prefix}Version: {version}")
340}
341
342fn write_recent_blockhash<W: io::Write>(
343    w: &mut W,
344    recent_blockhash: &Hash,
345    prefix: &str,
346) -> io::Result<()> {
347    writeln!(w, "{prefix}Recent Blockhash: {recent_blockhash:?}")
348}
349
350fn write_signatures<W: io::Write>(
351    w: &mut W,
352    signatures: &[Signature],
353    sigverify_status: Option<&[CliSignatureVerificationStatus]>,
354    prefix: &str,
355) -> io::Result<()> {
356    let sigverify_statuses = if let Some(sigverify_status) = sigverify_status {
357        sigverify_status.iter().map(|s| format!(" ({s})")).collect()
358    } else {
359        vec!["".to_string(); signatures.len()]
360    };
361    for (signature_index, (signature, sigverify_status)) in
362        signatures.iter().zip(&sigverify_statuses).enumerate()
363    {
364        writeln!(
365            w,
366            "{prefix}Signature {signature_index}: {signature:?}{sigverify_status}",
367        )?;
368    }
369    Ok(())
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq)]
373enum AccountKeyType<'a> {
374    Known(&'a Pubkey),
375    Unknown {
376        lookup_index: usize,
377        table_index: u8,
378    },
379}
380
381impl fmt::Display for AccountKeyType<'_> {
382    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
383        match self {
384            Self::Known(address) => write!(f, "{address}"),
385            Self::Unknown {
386                lookup_index,
387                table_index,
388            } => {
389                write!(
390                    f,
391                    "Unknown Address (uses lookup {lookup_index} and index {table_index})"
392                )
393            }
394        }
395    }
396}
397
398fn write_account<W: io::Write>(
399    w: &mut W,
400    account_index: usize,
401    account_address: AccountKeyType,
402    account_mode: String,
403    is_fee_payer: bool,
404    prefix: &str,
405) -> io::Result<()> {
406    writeln!(
407        w,
408        "{}Account {}: {} {}{}",
409        prefix,
410        account_index,
411        account_mode,
412        account_address,
413        if is_fee_payer { " (fee payer)" } else { "" },
414    )
415}
416
417fn write_instruction<'a, W: io::Write>(
418    w: &mut W,
419    instruction_index: usize,
420    program_pubkey: AccountKeyType,
421    instruction: &CompiledInstruction,
422    instruction_accounts: impl Iterator<Item = (AccountKeyType<'a>, u8)>,
423    prefix: &str,
424) -> io::Result<()> {
425    writeln!(w, "{prefix}Instruction {instruction_index}")?;
426    writeln!(
427        w,
428        "{}  Program:   {} ({})",
429        prefix, program_pubkey, instruction.program_id_index
430    )?;
431    for (index, (account_address, account_index)) in instruction_accounts.enumerate() {
432        writeln!(
433            w,
434            "{prefix}  Account {index}: {account_address} ({account_index})"
435        )?;
436    }
437
438    let mut raw = true;
439    if let AccountKeyType::Known(program_pubkey) = program_pubkey {
440        if program_pubkey == &solana_vote_program::id() {
441            if let Ok(vote_instruction) =
442                limited_deserialize::<solana_vote_program::vote_instruction::VoteInstruction>(
443                    &instruction.data,
444                    solana_packet::PACKET_DATA_SIZE as u64,
445                )
446            {
447                writeln!(w, "{prefix}  {vote_instruction:?}")?;
448                raw = false;
449            }
450        } else if program_pubkey == &stake::program::id() {
451            if let Ok(stake_instruction) = limited_deserialize::<stake::instruction::StakeInstruction>(
452                &instruction.data,
453                solana_packet::PACKET_DATA_SIZE as u64,
454            ) {
455                writeln!(w, "{prefix}  {stake_instruction:?}")?;
456                raw = false;
457            }
458        } else if program_pubkey == &solana_sdk_ids::system_program::id() {
459            if let Ok(system_instruction) =
460                limited_deserialize::<solana_system_interface::instruction::SystemInstruction>(
461                    &instruction.data,
462                    solana_packet::PACKET_DATA_SIZE as u64,
463                )
464            {
465                writeln!(w, "{prefix}  {system_instruction:?}")?;
466                raw = false;
467            }
468        } else if is_memo_program(program_pubkey) {
469            if let Ok(s) = std::str::from_utf8(&instruction.data) {
470                writeln!(w, "{prefix}  Data: \"{s}\"")?;
471                raw = false;
472            }
473        }
474    }
475
476    if raw {
477        writeln!(w, "{}  Data: {:?}", prefix, instruction.data)?;
478    }
479
480    Ok(())
481}
482
483fn write_address_table_lookups<W: io::Write>(
484    w: &mut W,
485    address_table_lookups: &[MessageAddressTableLookup],
486    prefix: &str,
487) -> io::Result<()> {
488    for (lookup_index, lookup) in address_table_lookups.iter().enumerate() {
489        writeln!(w, "{prefix}Address Table Lookup {lookup_index}",)?;
490        writeln!(w, "{}  Table Account: {}", prefix, lookup.account_key,)?;
491        writeln!(
492            w,
493            "{}  Writable Indexes: {:?}",
494            prefix,
495            &lookup.writable_indexes[..],
496        )?;
497        writeln!(
498            w,
499            "{}  Readonly Indexes: {:?}",
500            prefix,
501            &lookup.readonly_indexes[..],
502        )?;
503    }
504    Ok(())
505}
506
507fn write_rewards<W: io::Write>(
508    w: &mut W,
509    rewards: Option<&Rewards>,
510    prefix: &str,
511) -> io::Result<()> {
512    if let Some(rewards) = rewards {
513        if !rewards.is_empty() {
514            writeln!(w, "{prefix}Rewards:",)?;
515            writeln!(
516                w,
517                "{}  {:<44}  {:^15}  {:<16}  {:<20}",
518                prefix, "Address", "Type", "Amount", "New Balance"
519            )?;
520            for reward in rewards {
521                let sign = if reward.lamports < 0 { "-" } else { "" };
522                writeln!(
523                    w,
524                    "{}  {:<44}  {:^15}  {}◎{:<14.9}  ◎{:<18.9}",
525                    prefix,
526                    reward.pubkey,
527                    if let Some(reward_type) = reward.reward_type {
528                        format!("{reward_type}")
529                    } else {
530                        "-".to_string()
531                    },
532                    sign,
533                    lamports_to_sol(reward.lamports.unsigned_abs()),
534                    lamports_to_sol(reward.post_balance)
535                )?;
536            }
537        }
538    }
539    Ok(())
540}
541
542fn write_status<W: io::Write>(
543    w: &mut W,
544    transaction_status: &Result<(), TransactionError>,
545    prefix: &str,
546) -> io::Result<()> {
547    writeln!(
548        w,
549        "{}Status: {}",
550        prefix,
551        match transaction_status {
552            Ok(_) => "Ok".into(),
553            Err(err) => err.to_string(),
554        }
555    )
556}
557
558fn write_fees<W: io::Write>(w: &mut W, transaction_fee: u64, prefix: &str) -> io::Result<()> {
559    writeln!(w, "{}  Fee: ◎{}", prefix, lamports_to_sol(transaction_fee))
560}
561
562fn write_balances<W: io::Write>(
563    w: &mut W,
564    transaction_status: &UiTransactionStatusMeta,
565    prefix: &str,
566) -> io::Result<()> {
567    assert_eq!(
568        transaction_status.pre_balances.len(),
569        transaction_status.post_balances.len()
570    );
571    for (i, (pre, post)) in transaction_status
572        .pre_balances
573        .iter()
574        .zip(transaction_status.post_balances.iter())
575        .enumerate()
576    {
577        if pre == post {
578            writeln!(
579                w,
580                "{}  Account {} balance: ◎{}",
581                prefix,
582                i,
583                lamports_to_sol(*pre)
584            )?;
585        } else {
586            writeln!(
587                w,
588                "{}  Account {} balance: ◎{} -> ◎{}",
589                prefix,
590                i,
591                lamports_to_sol(*pre),
592                lamports_to_sol(*post)
593            )?;
594        }
595    }
596    Ok(())
597}
598
599fn write_return_data<W: io::Write>(
600    w: &mut W,
601    return_data: Option<&UiTransactionReturnData>,
602    prefix: &str,
603) -> io::Result<()> {
604    if let Some(return_data) = return_data {
605        let (data, encoding) = &return_data.data;
606        let raw_return_data = match encoding {
607            UiReturnDataEncoding::Base64 => BASE64_STANDARD.decode(data).map_err(|err| {
608                io::Error::new(
609                    io::ErrorKind::Other,
610                    format!("could not parse data as {encoding:?}: {err:?}"),
611                )
612            })?,
613        };
614        if !raw_return_data.is_empty() {
615            use pretty_hex::*;
616            writeln!(
617                w,
618                "{}Return Data from Program {}:",
619                prefix, return_data.program_id
620            )?;
621            writeln!(w, "{}  {:?}", prefix, raw_return_data.hex_dump())?;
622        }
623    }
624    Ok(())
625}
626
627fn write_compute_units_consumed<W: io::Write>(
628    w: &mut W,
629    compute_units_consumed: Option<u64>,
630    prefix: &str,
631) -> io::Result<()> {
632    if let Some(cus) = compute_units_consumed {
633        writeln!(w, "{prefix}Compute Units Consumed: {cus}")?;
634    }
635    Ok(())
636}
637
638fn write_log_messages<W: io::Write>(
639    w: &mut W,
640    log_messages: Option<&Vec<String>>,
641    prefix: &str,
642) -> io::Result<()> {
643    if let Some(log_messages) = log_messages {
644        if !log_messages.is_empty() {
645            writeln!(w, "{prefix}Log Messages:",)?;
646            for log_message in log_messages {
647                writeln!(w, "{prefix}  {log_message}")?;
648            }
649        }
650    }
651    Ok(())
652}
653
654pub fn println_transaction(
655    transaction: &VersionedTransaction,
656    transaction_status: Option<&UiTransactionStatusMeta>,
657    prefix: &str,
658    sigverify_status: Option<&[CliSignatureVerificationStatus]>,
659    block_time: Option<UnixTimestamp>,
660) {
661    let mut w = Vec::new();
662    if write_transaction(
663        &mut w,
664        transaction,
665        transaction_status,
666        prefix,
667        sigverify_status,
668        block_time,
669        CliTimezone::Local,
670    )
671    .is_ok()
672    {
673        if let Ok(s) = String::from_utf8(w) {
674            print!("{s}");
675        }
676    }
677}
678
679pub fn writeln_transaction(
680    f: &mut dyn fmt::Write,
681    transaction: &VersionedTransaction,
682    transaction_status: Option<&UiTransactionStatusMeta>,
683    prefix: &str,
684    sigverify_status: Option<&[CliSignatureVerificationStatus]>,
685    block_time: Option<UnixTimestamp>,
686) -> fmt::Result {
687    let mut w = Vec::new();
688    let write_result = write_transaction(
689        &mut w,
690        transaction,
691        transaction_status,
692        prefix,
693        sigverify_status,
694        block_time,
695        CliTimezone::Local,
696    );
697
698    if write_result.is_ok() {
699        if let Ok(s) = String::from_utf8(w) {
700            write!(f, "{s}")?;
701        }
702    }
703    Ok(())
704}
705
706/// Creates a new process bar for processing that will take an unknown amount of time
707pub fn new_spinner_progress_bar() -> ProgressBar {
708    let progress_bar = ProgressBar::new(42);
709    progress_bar.set_style(
710        ProgressStyle::default_spinner()
711            .template("{spinner:.green} {wide_msg}")
712            .expect("ProgressStyle::template direct input to be correct"),
713    );
714    progress_bar.enable_steady_tick(Duration::from_millis(100));
715    progress_bar
716}
717
718pub fn unix_timestamp_to_string(unix_timestamp: UnixTimestamp) -> String {
719    match DateTime::from_timestamp(unix_timestamp, 0) {
720        Some(ndt) => ndt.to_rfc3339_opts(SecondsFormat::Secs, true),
721        None => format!("UnixTimestamp {unix_timestamp}"),
722    }
723}
724
725#[cfg(test)]
726mod test {
727    use {
728        super::*,
729        solana_keypair::Keypair,
730        solana_message::{
731            v0::{self, LoadedAddresses},
732            Message as LegacyMessage, MessageHeader, VersionedMessage,
733        },
734        solana_pubkey::Pubkey,
735        solana_signer::Signer,
736        solana_transaction::Transaction,
737        solana_transaction_context::TransactionReturnData,
738        solana_transaction_status::{Reward, RewardType, TransactionStatusMeta},
739        std::io::BufWriter,
740    };
741
742    fn new_test_keypair() -> Keypair {
743        let secret = ed25519_dalek::SecretKey::from_bytes(&[0u8; 32]).unwrap();
744        let public = ed25519_dalek::PublicKey::from(&secret);
745        let keypair = ed25519_dalek::Keypair { secret, public };
746        Keypair::from_bytes(&keypair.to_bytes()).unwrap()
747    }
748
749    fn new_test_v0_transaction() -> VersionedTransaction {
750        let keypair = new_test_keypair();
751        let account_key = Pubkey::new_from_array([1u8; 32]);
752        let address_table_key = Pubkey::new_from_array([2u8; 32]);
753        VersionedTransaction::try_new(
754            VersionedMessage::V0(v0::Message {
755                header: MessageHeader {
756                    num_required_signatures: 1,
757                    num_readonly_signed_accounts: 0,
758                    num_readonly_unsigned_accounts: 1,
759                },
760                recent_blockhash: Hash::default(),
761                account_keys: vec![keypair.pubkey(), account_key],
762                address_table_lookups: vec![MessageAddressTableLookup {
763                    account_key: address_table_key,
764                    writable_indexes: vec![0],
765                    readonly_indexes: vec![1],
766                }],
767                instructions: vec![CompiledInstruction::new_from_raw_parts(
768                    3,
769                    vec![],
770                    vec![1, 2],
771                )],
772            }),
773            &[&keypair],
774        )
775        .unwrap()
776    }
777
778    #[test]
779    fn test_write_legacy_transaction() {
780        let keypair = new_test_keypair();
781        let account_key = Pubkey::new_from_array([1u8; 32]);
782        let transaction = VersionedTransaction::from(Transaction::new(
783            &[&keypair],
784            LegacyMessage {
785                header: MessageHeader {
786                    num_required_signatures: 1,
787                    num_readonly_signed_accounts: 0,
788                    num_readonly_unsigned_accounts: 1,
789                },
790                recent_blockhash: Hash::default(),
791                account_keys: vec![keypair.pubkey(), account_key],
792                instructions: vec![CompiledInstruction::new_from_raw_parts(1, vec![], vec![0])],
793            },
794            Hash::default(),
795        ));
796
797        let sigverify_status = CliSignatureVerificationStatus::verify_transaction(&transaction);
798        let meta = TransactionStatusMeta {
799            status: Ok(()),
800            fee: 5000,
801            pre_balances: vec![5000, 10_000],
802            post_balances: vec![0, 9_900],
803            inner_instructions: None,
804            log_messages: Some(vec!["Test message".to_string()]),
805            pre_token_balances: None,
806            post_token_balances: None,
807            rewards: Some(vec![Reward {
808                pubkey: account_key.to_string(),
809                lamports: -100,
810                post_balance: 9_900,
811                reward_type: Some(RewardType::Rent),
812                commission: None,
813            }]),
814            loaded_addresses: LoadedAddresses::default(),
815            return_data: Some(TransactionReturnData {
816                program_id: Pubkey::new_from_array([2u8; 32]),
817                data: vec![1, 2, 3],
818            }),
819            compute_units_consumed: Some(1234u64),
820        };
821
822        let output = {
823            let mut write_buffer = BufWriter::new(Vec::new());
824            write_transaction(
825                &mut write_buffer,
826                &transaction,
827                Some(&meta.into()),
828                "",
829                Some(&sigverify_status),
830                Some(1628633791),
831                CliTimezone::Utc,
832            )
833            .unwrap();
834            let bytes = write_buffer.into_inner().unwrap();
835            String::from_utf8(bytes).unwrap()
836        };
837
838        assert_eq!(
839            output,
840            r"Block Time: 2021-08-10T22:16:31Z
841Version: legacy
842Recent Blockhash: 11111111111111111111111111111111
843Signature 0: 5pkjrE4VBa3Bu9CMKXgh1U345cT1gGo8QBVRTzHAo6gHeiPae5BTbShP15g6NgqRMNqu8Qrhph1ATmrfC1Ley3rx (pass)
844Account 0: srw- 4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS (fee payer)
845Account 1: -r-x 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi
846Instruction 0
847  Program:   4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi (1)
848  Account 0: 4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS (0)
849  Data: []
850Status: Ok
851  Fee: ◎0.000005
852  Account 0 balance: ◎0.000005 -> ◎0
853  Account 1 balance: ◎0.00001 -> ◎0.0000099
854Compute Units Consumed: 1234
855Log Messages:
856  Test message
857Return Data from Program 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR:
858  Length: 3 (0x3) bytes
8590000:   01 02 03                                             ...
860Rewards:
861  Address                                            Type        Amount            New Balance         \0
862  4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi        rent        -◎0.000000100     ◎0.000009900       \0
863".replace("\\0", "") // replace marker used to subvert trailing whitespace linter on CI
864        );
865    }
866
867    #[test]
868    fn test_write_v0_transaction() {
869        let versioned_tx = new_test_v0_transaction();
870        let sigverify_status = CliSignatureVerificationStatus::verify_transaction(&versioned_tx);
871        let address_table_entry1 = Pubkey::new_from_array([3u8; 32]);
872        let address_table_entry2 = Pubkey::new_from_array([4u8; 32]);
873        let loaded_addresses = LoadedAddresses {
874            writable: vec![address_table_entry1],
875            readonly: vec![address_table_entry2],
876        };
877        let meta = TransactionStatusMeta {
878            status: Ok(()),
879            fee: 5000,
880            pre_balances: vec![5000, 10_000, 15_000, 20_000],
881            post_balances: vec![0, 10_000, 14_900, 20_000],
882            inner_instructions: None,
883            log_messages: Some(vec!["Test message".to_string()]),
884            pre_token_balances: None,
885            post_token_balances: None,
886            rewards: Some(vec![Reward {
887                pubkey: address_table_entry1.to_string(),
888                lamports: -100,
889                post_balance: 14_900,
890                reward_type: Some(RewardType::Rent),
891                commission: None,
892            }]),
893            loaded_addresses,
894            return_data: Some(TransactionReturnData {
895                program_id: Pubkey::new_from_array([2u8; 32]),
896                data: vec![1, 2, 3],
897            }),
898            compute_units_consumed: Some(2345u64),
899        };
900
901        let output = {
902            let mut write_buffer = BufWriter::new(Vec::new());
903            write_transaction(
904                &mut write_buffer,
905                &versioned_tx,
906                Some(&meta.into()),
907                "",
908                Some(&sigverify_status),
909                Some(1628633791),
910                CliTimezone::Utc,
911            )
912            .unwrap();
913            let bytes = write_buffer.into_inner().unwrap();
914            String::from_utf8(bytes).unwrap()
915        };
916
917        assert_eq!(
918            output,
919            r"Block Time: 2021-08-10T22:16:31Z
920Version: 0
921Recent Blockhash: 11111111111111111111111111111111
922Signature 0: 5iEy3TT3ZhTA1NkuCY8GrQGNVY8d5m1bpjdh5FT3Ca4Py81fMipAZjafDuKJKrkw5q5UAAd8oPcgZ4nyXpHt4Fp7 (pass)
923Account 0: srw- 4zvwRjXUKGfvwnParsHAS3HuSVzV5cA4McphgmoCtajS (fee payer)
924Account 1: -r-- 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi
925Account 2: -rw- Unknown Address (uses lookup 0 and index 0)
926Account 3: -r-x Unknown Address (uses lookup 0 and index 1)
927Instruction 0
928  Program:   Unknown Address (uses lookup 0 and index 1) (3)
929  Account 0: 4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLKi (1)
930  Account 1: Unknown Address (uses lookup 0 and index 0) (2)
931  Data: []
932Address Table Lookup 0
933  Table Account: 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR
934  Writable Indexes: [0]
935  Readonly Indexes: [1]
936Status: Ok
937  Fee: ◎0.000005
938  Account 0 balance: ◎0.000005 -> ◎0
939  Account 1 balance: ◎0.00001
940  Account 2 balance: ◎0.000015 -> ◎0.0000149
941  Account 3 balance: ◎0.00002
942Compute Units Consumed: 2345
943Log Messages:
944  Test message
945Return Data from Program 8qbHbw2BbbTHBW1sbeqakYXVKRQM8Ne7pLK7m6CVfeR:
946  Length: 3 (0x3) bytes
9470000:   01 02 03                                             ...
948Rewards:
949  Address                                            Type        Amount            New Balance         \0
950  CktRuQ2mttgRGkXJtyksdKHjUdc2C4TgDzyB98oEzy8        rent        -◎0.000000100     ◎0.000014900       \0
951".replace("\\0", "") // replace marker used to subvert trailing whitespace linter on CI
952        );
953    }
954
955    #[test]
956    fn test_format_labeled_address() {
957        let pubkey = Pubkey::default().to_string();
958        let mut address_labels = HashMap::new();
959
960        assert_eq!(format_labeled_address(&pubkey, &address_labels), pubkey);
961
962        address_labels.insert(pubkey.to_string(), "Default Address".to_string());
963        assert_eq!(
964            &format_labeled_address(&pubkey, &address_labels),
965            "Default Address (1111..1111)"
966        );
967
968        address_labels.insert(
969            pubkey.to_string(),
970            "abcdefghijklmnopqrstuvwxyz1234567890".to_string(),
971        );
972        assert_eq!(
973            &format_labeled_address(&pubkey, &address_labels),
974            "abcdefghijklmnopqrstuvwxyz12345 (1111..1111)"
975        );
976    }
977
978    #[test]
979    fn test_unix_timestamp_to_string() {
980        assert_eq!(unix_timestamp_to_string(1628633791), "2021-08-10T22:16:31Z");
981    }
982}