1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! A client for the ledger state, from the perspective of an arbitrary validator.
//!
//! Use start_tcp_client() to create a client and then import BanksClientExt to
//! access its methods. Additional "*_with_context" methods are also available,
//! but they are undocumented, may change over time, and are generally more
//! cumbersome to use.

pub use crate::error::BanksClientError;
pub use solana_banks_interface::{BanksClient as TarpcClient, TransactionStatus};
use {
    borsh::BorshDeserialize,
    futures::{future::join_all, Future, FutureExt, TryFutureExt},
    solana_banks_interface::{BanksRequest, BanksResponse, BanksTransactionResultWithSimulation},
    solana_program::{
        clock::Slot, fee_calculator::FeeCalculator, hash::Hash, program_pack::Pack, pubkey::Pubkey,
        rent::Rent, sysvar::Sysvar,
    },
    solana_sdk::{
        account::{from_account, Account},
        commitment_config::CommitmentLevel,
        message::Message,
        signature::Signature,
        transaction::{self, Transaction},
        transport,
    },
    std::io,
    tarpc::{
        client::{self, NewClient, RequestDispatch},
        context::{self, Context},
        serde_transport::tcp,
        ClientMessage, Response, Transport,
    },
    tokio::{net::ToSocketAddrs, time::Duration},
    tokio_serde::formats::Bincode,
};

mod error;

// This exists only for backward compatibility
pub trait BanksClientExt {}

#[derive(Clone)]
pub struct BanksClient {
    inner: TarpcClient,
}

impl BanksClient {
    #[allow(clippy::new_ret_no_self)]
    pub fn new<C>(
        config: client::Config,
        transport: C,
    ) -> NewClient<TarpcClient, RequestDispatch<BanksRequest, BanksResponse, C>>
    where
        C: Transport<ClientMessage<BanksRequest>, Response<BanksResponse>>,
    {
        TarpcClient::new(config, transport)
    }

    pub fn send_transaction_with_context(
        &mut self,
        ctx: Context,
        transaction: Transaction,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner
            .send_transaction_with_context(ctx, transaction)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    #[deprecated(
        since = "1.9.0",
        note = "Please use `get_fee_for_message` or `is_blockhash_valid` instead"
    )]
    pub fn get_fees_with_commitment_and_context(
        &mut self,
        ctx: Context,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<(FeeCalculator, Hash, u64)>> + '_ {
        #[allow(deprecated)]
        self.inner
            .get_fees_with_commitment_and_context(ctx, commitment)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    pub fn get_transaction_status_with_context(
        &mut self,
        ctx: Context,
        signature: Signature,
    ) -> impl Future<Output = io::Result<Option<TransactionStatus>>> + '_ {
        self.inner
            .get_transaction_status_with_context(ctx, signature)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    pub fn get_slot_with_context(
        &mut self,
        ctx: Context,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Slot>> + '_ {
        self.inner
            .get_slot_with_context(ctx, commitment)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    pub fn get_block_height_with_context(
        &mut self,
        ctx: Context,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Slot>> + '_ {
        self.inner
            .get_block_height_with_context(ctx, commitment)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    pub fn process_transaction_with_commitment_and_context(
        &mut self,
        ctx: Context,
        transaction: Transaction,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Option<transaction::Result<()>>>> + '_ {
        self.inner
            .process_transaction_with_commitment_and_context(ctx, transaction, commitment)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    pub fn process_transaction_with_preflight_and_commitment_and_context(
        &mut self,
        ctx: Context,
        transaction: Transaction,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = Result<BanksTransactionResultWithSimulation, BanksClientError>> + '_
    {
        self.inner
            .process_transaction_with_preflight_and_commitment_and_context(
                ctx,
                transaction,
                commitment,
            )
            .map_err(Into::into)
    }

    pub fn get_account_with_commitment_and_context(
        &mut self,
        ctx: Context,
        address: Pubkey,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Option<Account>>> + '_ {
        self.inner
            .get_account_with_commitment_and_context(ctx, address, commitment)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    /// Send a transaction and return immediately. The server will resend the
    /// transaction until either it is accepted by the cluster or the transaction's
    /// blockhash expires.
    pub fn send_transaction(
        &mut self,
        transaction: Transaction,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.send_transaction_with_context(context::current(), transaction)
    }

    /// Return the fee parameters associated with a recent, rooted blockhash. The cluster
    /// will use the transaction's blockhash to look up these same fee parameters and
    /// use them to calculate the transaction fee.
    #[deprecated(
        since = "1.9.0",
        note = "Please use `get_fee_for_message` or `is_blockhash_valid` instead"
    )]
    pub fn get_fees(
        &mut self,
    ) -> impl Future<Output = io::Result<(FeeCalculator, Hash, u64)>> + '_ {
        #[allow(deprecated)]
        self.get_fees_with_commitment_and_context(context::current(), CommitmentLevel::default())
    }

    /// Return the cluster Sysvar
    pub fn get_sysvar<T: Sysvar>(&mut self) -> impl Future<Output = io::Result<T>> + '_ {
        self.get_account(T::id()).map(|result| {
            let sysvar = result?
                .ok_or(BanksClientError::ClientError("Sysvar not present"))
                .map_err(io::Error::from)?; // Remove this map when return Err type updated to BanksClientError
            from_account::<T, _>(&sysvar)
                .ok_or(BanksClientError::ClientError(
                    "Failed to deserialize sysvar",
                ))
                .map_err(Into::into) // Remove this when return Err type updated to BanksClientError
        })
    }

    /// Return the cluster rent
    pub fn get_rent(&mut self) -> impl Future<Output = io::Result<Rent>> + '_ {
        self.get_sysvar::<Rent>()
    }

    /// Return a recent, rooted blockhash from the server. The cluster will only accept
    /// transactions with a blockhash that has not yet expired. Use the `get_fees`
    /// method to get both a blockhash and the blockhash's last valid slot.
    #[deprecated(since = "1.9.0", note = "Please use `get_latest_blockhash` instead")]
    pub fn get_recent_blockhash(&mut self) -> impl Future<Output = io::Result<Hash>> + '_ {
        #[allow(deprecated)]
        self.get_fees().map(|result| Ok(result?.1))
    }

    /// Send a transaction and return after the transaction has been rejected or
    /// reached the given level of commitment.
    pub fn process_transaction_with_commitment(
        &mut self,
        transaction: Transaction,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = transport::Result<()>> + '_ {
        let mut ctx = context::current();
        ctx.deadline += Duration::from_secs(50);
        self.process_transaction_with_commitment_and_context(ctx, transaction, commitment)
            .map(|result| match result? {
                None => Err(BanksClientError::ClientError(
                    "invalid blockhash or fee-payer",
                )),
                Some(transaction_result) => Ok(transaction_result?),
            })
            .map_err(Into::into) // Remove this when return Err type updated to BanksClientError
    }

    /// Send a transaction and return any preflight (sanitization or simulation) errors, or return
    /// after the transaction has been rejected or reached the given level of commitment.
    pub fn process_transaction_with_preflight_and_commitment(
        &mut self,
        transaction: Transaction,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = Result<(), BanksClientError>> + '_ {
        let mut ctx = context::current();
        ctx.deadline += Duration::from_secs(50);
        self.process_transaction_with_preflight_and_commitment_and_context(
            ctx,
            transaction,
            commitment,
        )
        .map(|result| match result? {
            BanksTransactionResultWithSimulation {
                result: None,
                simulation_details: _,
            } => Err(BanksClientError::ClientError(
                "invalid blockhash or fee-payer",
            )),
            BanksTransactionResultWithSimulation {
                result: Some(Err(err)),
                simulation_details: Some(simulation_details),
            } => Err(BanksClientError::SimulationError {
                err,
                logs: simulation_details.logs,
                units_consumed: simulation_details.units_consumed,
            }),
            BanksTransactionResultWithSimulation {
                result: Some(result),
                simulation_details: _,
            } => result.map_err(Into::into),
        })
    }

    /// Send a transaction and return any preflight (sanitization or simulation) errors, or return
    /// after the transaction has been finalized or rejected.
    pub fn process_transaction_with_preflight(
        &mut self,
        transaction: Transaction,
    ) -> impl Future<Output = Result<(), BanksClientError>> + '_ {
        self.process_transaction_with_preflight_and_commitment(
            transaction,
            CommitmentLevel::default(),
        )
    }

    /// Send a transaction and return until the transaction has been finalized or rejected.
    pub fn process_transaction(
        &mut self,
        transaction: Transaction,
    ) -> impl Future<Output = transport::Result<()>> + '_ {
        self.process_transaction_with_commitment(transaction, CommitmentLevel::default())
    }

    pub async fn process_transactions_with_commitment(
        &mut self,
        transactions: Vec<Transaction>,
        commitment: CommitmentLevel,
    ) -> transport::Result<()> {
        let mut clients: Vec<_> = transactions.iter().map(|_| self.clone()).collect();
        let futures = clients
            .iter_mut()
            .zip(transactions)
            .map(|(client, transaction)| {
                client.process_transaction_with_commitment(transaction, commitment)
            });
        let statuses = join_all(futures).await;
        statuses.into_iter().collect() // Convert Vec<Result<_, _>> to Result<Vec<_>>
    }

    /// Send transactions and return until the transaction has been finalized or rejected.
    pub fn process_transactions(
        &mut self,
        transactions: Vec<Transaction>,
    ) -> impl Future<Output = transport::Result<()>> + '_ {
        self.process_transactions_with_commitment(transactions, CommitmentLevel::default())
    }

    /// Return the most recent rooted slot. All transactions at or below this slot
    /// are said to be finalized. The cluster will not fork to a higher slot.
    pub fn get_root_slot(&mut self) -> impl Future<Output = io::Result<Slot>> + '_ {
        self.get_slot_with_context(context::current(), CommitmentLevel::default())
    }

    /// Return the most recent rooted block height. All transactions at or below this height
    /// are said to be finalized. The cluster will not fork to a higher block height.
    pub fn get_root_block_height(&mut self) -> impl Future<Output = io::Result<Slot>> + '_ {
        self.get_block_height_with_context(context::current(), CommitmentLevel::default())
    }

    /// Return the account at the given address at the slot corresponding to the given
    /// commitment level. If the account is not found, None is returned.
    pub fn get_account_with_commitment(
        &mut self,
        address: Pubkey,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Option<Account>>> + '_ {
        self.get_account_with_commitment_and_context(context::current(), address, commitment)
    }

    /// Return the account at the given address at the time of the most recent root slot.
    /// If the account is not found, None is returned.
    pub fn get_account(
        &mut self,
        address: Pubkey,
    ) -> impl Future<Output = io::Result<Option<Account>>> + '_ {
        self.get_account_with_commitment(address, CommitmentLevel::default())
    }

    /// Return the unpacked account data at the given address
    /// If the account is not found, an error is returned
    pub fn get_packed_account_data<T: Pack>(
        &mut self,
        address: Pubkey,
    ) -> impl Future<Output = io::Result<T>> + '_ {
        self.get_account(address).map(|result| {
            let account = result?
                .ok_or(BanksClientError::ClientError("Account not found"))
                .map_err(io::Error::from)?; // Remove this map when return Err type updated to BanksClientError
            T::unpack_from_slice(&account.data)
                .map_err(|_| BanksClientError::ClientError("Failed to deserialize account"))
                .map_err(Into::into) // Remove this when return Err type updated to BanksClientError
        })
    }

    /// Return the unpacked account data at the given address
    /// If the account is not found, an error is returned
    pub fn get_account_data_with_borsh<T: BorshDeserialize>(
        &mut self,
        address: Pubkey,
    ) -> impl Future<Output = io::Result<T>> + '_ {
        self.get_account(address).map(|result| {
            let account = result?.ok_or(BanksClientError::ClientError("Account not found"))?;
            T::try_from_slice(&account.data).map_err(Into::into)
        })
    }

    /// Return the balance in lamports of an account at the given address at the slot
    /// corresponding to the given commitment level.
    pub fn get_balance_with_commitment(
        &mut self,
        address: Pubkey,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<u64>> + '_ {
        self.get_account_with_commitment_and_context(context::current(), address, commitment)
            .map(|result| Ok(result?.map(|x| x.lamports).unwrap_or(0)))
    }

    /// Return the balance in lamports of an account at the given address at the time
    /// of the most recent root slot.
    pub fn get_balance(&mut self, address: Pubkey) -> impl Future<Output = io::Result<u64>> + '_ {
        self.get_balance_with_commitment(address, CommitmentLevel::default())
    }

    /// Return the status of a transaction with a signature matching the transaction's first
    /// signature. Return None if the transaction is not found, which may be because the
    /// blockhash was expired or the fee-paying account had insufficient funds to pay the
    /// transaction fee. Note that servers rarely store the full transaction history. This
    /// method may return None if the transaction status has been discarded.
    pub fn get_transaction_status(
        &mut self,
        signature: Signature,
    ) -> impl Future<Output = io::Result<Option<TransactionStatus>>> + '_ {
        self.get_transaction_status_with_context(context::current(), signature)
    }

    /// Same as get_transaction_status, but for multiple transactions.
    pub async fn get_transaction_statuses(
        &mut self,
        signatures: Vec<Signature>,
    ) -> io::Result<Vec<Option<TransactionStatus>>> {
        // tarpc futures oddly hold a mutable reference back to the client so clone the client upfront
        let mut clients_and_signatures: Vec<_> = signatures
            .into_iter()
            .map(|signature| (self.clone(), signature))
            .collect();

        let futs = clients_and_signatures
            .iter_mut()
            .map(|(client, signature)| client.get_transaction_status(*signature));

        let statuses = join_all(futs).await;

        // Convert Vec<Result<_, _>> to Result<Vec<_>>
        statuses.into_iter().collect()
    }

    pub fn get_latest_blockhash(&mut self) -> impl Future<Output = io::Result<Hash>> + '_ {
        self.get_latest_blockhash_with_commitment(CommitmentLevel::default())
            .map(|result| {
                result?
                    .map(|x| x.0)
                    .ok_or(BanksClientError::ClientError("valid blockhash not found"))
                    .map_err(Into::into)
            })
    }

    pub fn get_latest_blockhash_with_commitment(
        &mut self,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Option<(Hash, u64)>>> + '_ {
        self.get_latest_blockhash_with_commitment_and_context(context::current(), commitment)
    }

    pub fn get_latest_blockhash_with_commitment_and_context(
        &mut self,
        ctx: Context,
        commitment: CommitmentLevel,
    ) -> impl Future<Output = io::Result<Option<(Hash, u64)>>> + '_ {
        self.inner
            .get_latest_blockhash_with_commitment_and_context(ctx, commitment)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }

    pub fn get_fee_for_message_with_commitment_and_context(
        &mut self,
        ctx: Context,
        commitment: CommitmentLevel,
        message: Message,
    ) -> impl Future<Output = io::Result<Option<u64>>> + '_ {
        self.inner
            .get_fee_for_message_with_commitment_and_context(ctx, commitment, message)
            .map_err(BanksClientError::from) // Remove this when return Err type updated to BanksClientError
            .map_err(Into::into)
    }
}

pub async fn start_client<C>(transport: C) -> io::Result<BanksClient>
where
    C: Transport<ClientMessage<BanksRequest>, Response<BanksResponse>> + Send + 'static,
{
    Ok(BanksClient {
        inner: TarpcClient::new(client::Config::default(), transport).spawn(),
    })
}

pub async fn start_tcp_client<T: ToSocketAddrs>(addr: T) -> io::Result<BanksClient> {
    let transport = tcp::connect(addr, Bincode::default).await?;
    Ok(BanksClient {
        inner: TarpcClient::new(client::Config::default(), transport).spawn(),
    })
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        solana_banks_server::banks_server::start_local_server,
        solana_runtime::{
            bank::Bank, bank_forks::BankForks, commitment::BlockCommitmentCache,
            genesis_utils::create_genesis_config,
        },
        solana_sdk::{message::Message, signature::Signer, system_instruction},
        std::sync::{Arc, RwLock},
        tarpc::transport,
        tokio::{runtime::Runtime, time::sleep},
    };

    #[test]
    fn test_banks_client_new() {
        let (client_transport, _server_transport) = transport::channel::unbounded();
        BanksClient::new(client::Config::default(), client_transport);
    }

    #[test]
    fn test_banks_server_transfer_via_server() -> Result<(), BanksClientError> {
        // This test shows the preferred way to interact with BanksServer.
        // It creates a runtime explicitly (no globals via tokio macros) and calls
        // `runtime.block_on()` just once, to run all the async code.

        let genesis = create_genesis_config(10);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let slot = bank.slot();
        let block_commitment_cache = Arc::new(RwLock::new(
            BlockCommitmentCache::new_for_tests_with_slots(slot, slot),
        ));
        let bank_forks = Arc::new(RwLock::new(BankForks::new(bank)));

        let bob_pubkey = solana_sdk::pubkey::new_rand();
        let mint_pubkey = genesis.mint_keypair.pubkey();
        let instruction = system_instruction::transfer(&mint_pubkey, &bob_pubkey, 1);
        let message = Message::new(&[instruction], Some(&mint_pubkey));

        Runtime::new()?.block_on(async {
            let client_transport =
                start_local_server(bank_forks, block_commitment_cache, Duration::from_millis(1))
                    .await;
            let mut banks_client = start_client(client_transport).await?;

            let recent_blockhash = banks_client.get_latest_blockhash().await?;
            let transaction = Transaction::new(&[&genesis.mint_keypair], message, recent_blockhash);
            banks_client.process_transaction(transaction).await.unwrap();
            assert_eq!(banks_client.get_balance(bob_pubkey).await?, 1);
            Ok(())
        })
    }

    #[test]
    fn test_banks_server_transfer_via_client() -> Result<(), BanksClientError> {
        // The caller may not want to hold the connection open until the transaction
        // is processed (or blockhash expires). In this test, we verify the
        // server-side functionality is available to the client.

        let genesis = create_genesis_config(10);
        let bank = Bank::new_for_tests(&genesis.genesis_config);
        let slot = bank.slot();
        let block_commitment_cache = Arc::new(RwLock::new(
            BlockCommitmentCache::new_for_tests_with_slots(slot, slot),
        ));
        let bank_forks = Arc::new(RwLock::new(BankForks::new(bank)));

        let mint_pubkey = &genesis.mint_keypair.pubkey();
        let bob_pubkey = solana_sdk::pubkey::new_rand();
        let instruction = system_instruction::transfer(mint_pubkey, &bob_pubkey, 1);
        let message = Message::new(&[instruction], Some(mint_pubkey));

        Runtime::new()?.block_on(async {
            let client_transport =
                start_local_server(bank_forks, block_commitment_cache, Duration::from_millis(1))
                    .await;
            let mut banks_client = start_client(client_transport).await?;
            let (recent_blockhash, last_valid_block_height) = banks_client
                .get_latest_blockhash_with_commitment(CommitmentLevel::default())
                .await?
                .unwrap();
            let transaction = Transaction::new(&[&genesis.mint_keypair], message, recent_blockhash);
            let signature = transaction.signatures[0];
            banks_client.send_transaction(transaction).await?;

            let mut status = banks_client.get_transaction_status(signature).await?;

            while status.is_none() {
                let root_block_height = banks_client.get_root_block_height().await?;
                if root_block_height > last_valid_block_height {
                    break;
                }
                sleep(Duration::from_millis(100)).await;
                status = banks_client.get_transaction_status(signature).await?;
            }
            assert!(status.unwrap().err.is_none());
            assert_eq!(banks_client.get_balance(bob_pubkey).await?, 1);
            Ok(())
        })
    }
}