arch_program 0.6.4

A Rust library for building programs that run inside the Arch Virtual Machine. Provides core functionality for creating instructions, managing accounts, handling program errors, and interacting with the Arch runtime environment. Includes utilities for logging, transaction handling, and Bitcoin UTXO management.
Documentation
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use bitcoin::hashes::Hash;
use bitcoin::Transaction;
use bitcoin_slices::{bsl, Error, Visit, Visitor};
use borsh::{BorshDeserialize, BorshSerialize};

use crate::input_to_sign::InputToSign;
use crate::instruction::Instruction;
use crate::program_error::ProgramError;
use crate::rune::{RuneAmount, RuneInfo};
#[cfg(target_os = "solana")]
use crate::stable_layout::stable_ins::StableInstruction;
use crate::{msg, MAX_BTC_RUNE_OUTPUT_SIZE, MAX_BTC_TX_SIZE};

use crate::clock::Clock;
use crate::transaction_to_sign::TransactionToSign;
use crate::utxo::UtxoMeta;
use crate::{account::AccountInfo, entrypoint::ProgramResult, pubkey::Pubkey};

/// A generic wrapper for fixed-size data that avoids heap allocation.
///
/// This type holds raw bytes in a fixed-size array and tracks the actual size of the data.
/// The array size is determined by the const generic parameter `N`.
#[derive(Debug, Clone, BorshSerialize, BorshDeserialize)]
pub struct FixedSizeBuffer<const N: usize> {
    data: [u8; N],
    size: usize,
}

impl<const N: usize> FixedSizeBuffer<N> {
    /// Creates a new FixedSizeBuffer from a buffer and size.
    pub fn new(data: [u8; N], size: usize) -> Self {
        Self { data, size }
    }

    /// Returns the actual size of the data.
    pub fn size(&self) -> usize {
        self.size
    }

    /// Returns a slice of the actual data.
    pub fn as_slice(&self) -> &[u8] {
        &self.data[..self.size]
    }

    /// Returns a mutable raw pointer to the underlying buffer (for FFI/syscall writes).
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        self.data.as_mut_ptr()
    }

    /// Returns the total capacity of the buffer.
    pub fn capacity(&self) -> usize {
        N
    }

    /// Sets the length of the valid data written into the buffer.
    ///
    /// # Safety
    /// The caller must guarantee that `new_size` bytes starting from the
    /// pointer returned by `as_mut_ptr` have been initialised.
    pub fn set_size(&mut self, new_size: usize) {
        debug_assert!(
            new_size <= N,
            "new_size ({}) exceeds buffer capacity ({})",
            new_size,
            N
        );

        self.size = new_size;
    }
}

impl<const N: usize> AsRef<[u8]> for FixedSizeBuffer<N> {
    fn as_ref(&self) -> &[u8] {
        self.as_slice()
    }
}

impl<const N: usize> std::ops::Deref for FixedSizeBuffer<N> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.as_slice()
    }
}

impl<const N: usize> Default for FixedSizeBuffer<N> {
    fn default() -> Self {
        Self {
            data: [0u8; N],
            size: 0,
        }
    }
}

/// Type alias for Bitcoin transaction data with a fixed 3976-byte buffer.
pub type BitcoinTransaction = FixedSizeBuffer<MAX_BTC_TX_SIZE>;

/// Type alias for Bitcoin rune output data with a fixed 2048-byte buffer.
pub type BitcoinRuneOutput = FixedSizeBuffer<MAX_BTC_RUNE_OUTPUT_SIZE>;

/// Type alias for Returned Data with a fixed 1024-byte buffer.
pub type ReturnedData = FixedSizeBuffer<MAX_RETURN_DATA>;

/// Type alias for RuneInfo data with a tight 64-byte buffer.
/// Borsh-encoded `RuneInfo` is 53 bytes; 64 is a safe upper bound.
pub type RuneInfoBuf = FixedSizeBuffer<64>;

/// Invokes a program instruction through cross-program invocation.
///
/// This function processes the provided instruction by dispatching control to another program
/// using the account information provided.
///
/// # Arguments
/// * `instruction` - The instruction to process
/// * `account_infos` - The accounts required to process the instruction
///
/// # Returns
/// * `ProgramResult` - Ok(()) if successful, or an error if the operation fails
pub fn invoke(instruction: &Instruction, account_infos: &[AccountInfo]) -> ProgramResult {
    invoke_signed(instruction, account_infos, &[])
}

/// Invokes a program instruction without checking account permissions.
///
/// Similar to `invoke`, but skips the account permission checking step.
/// This is generally less safe than `invoke` and should be used carefully.
///
/// # Arguments
/// * `instruction` - The instruction to process
/// * `account_infos` - The accounts required to process the instruction
///
/// # Returns
/// * `ProgramResult` - Ok(()) if successful, or an error if the operation fails
pub fn invoke_unchecked(instruction: &Instruction, account_infos: &[AccountInfo]) -> ProgramResult {
    invoke_signed_unchecked(instruction, account_infos, &[])
}

/// Invokes a program instruction with additional signing authority.
///
/// This function processes the provided instruction by dispatching control to another program,
/// while also providing program-derived address signing authority.
/// It performs permission checks on the accounts before invoking.
///
/// # Arguments
/// * `instruction` - The instruction to process
/// * `account_infos` - The accounts required to process the instruction
/// * `signers_seeds` - Seeds used to sign the transaction as a program-derived address
///
/// # Returns
/// * `ProgramResult` - Ok(()) if successful, or an error if the operation fails
///
/// # Errors
/// Returns an error if any required account cannot be borrowed according to its stated permissions
pub fn invoke_signed(
    instruction: &Instruction,
    account_infos: &[AccountInfo],
    signers_seeds: &[&[&[u8]]],
) -> ProgramResult {
    // Check that the account RefCells are consistent with the request
    for account_meta in instruction.accounts.iter() {
        for account_info in account_infos.iter() {
            if account_meta.pubkey == *account_info.key {
                if account_meta.is_writable {
                    let _ = account_info.try_borrow_mut_data()?;
                } else {
                    let _ = account_info.try_borrow_data()?;
                }
                break;
            }
        }
    }

    invoke_signed_unchecked(instruction, account_infos, signers_seeds)
}

/// Invokes a program instruction with additional signing authority without checking account permissions.
///
/// Similar to `invoke_signed`, but skips the account permission checking step.
/// This is generally less safe than `invoke_signed` and should be used carefully.
///
/// # Arguments
/// * `instruction` - The instruction to process
/// * `account_infos` - The accounts required to process the instruction
/// * `signers_seeds` - Seeds used to sign the transaction as a program-derived address
///
/// # Returns
/// * `ProgramResult` - Ok(()) if successful, or an error if the operation fails
pub fn invoke_signed_unchecked(
    instruction: &Instruction,
    account_infos: &[AccountInfo],
    signers_seeds: &[&[&[u8]]],
) -> ProgramResult {
    #[cfg(target_os = "solana")]
    {
        let instruction = StableInstruction::from(instruction.clone());
        let result = unsafe {
            crate::syscalls::sol_invoke_signed_rust(
                &instruction as *const _ as *const u8,
                account_infos as *const _ as *const u8,
                account_infos.len() as u64,
                signers_seeds as *const _ as *const u8,
                signers_seeds.len() as u64,
            )
        };
        match result {
            crate::entrypoint::SUCCESS => Ok(()),
            _ => Err(result.into()),
        }
    }

    #[cfg(not(target_os = "solana"))]
    crate::program_stubs::sol_invoke_signed(instruction, account_infos, signers_seeds)
}

/// Gets the next account from an account iterator.
///
/// A utility function that advances the iterator and returns the next `AccountInfo`,
/// or returns a `NotEnoughAccountKeys` error if there are no more accounts.
///
/// # Arguments
/// * `iter` - Mutable reference to an iterator yielding references to `AccountInfo`
///
/// # Returns
/// * `Result<&AccountInfo, ProgramError>` - The next account info or an error if depleted
///
/// # Errors
/// Returns `ProgramError::NotEnoughAccountKeys` if the iterator has no more items
pub fn next_account_info<'a, 'b, I: Iterator<Item = &'a AccountInfo<'b>>>(
    iter: &mut I,
) -> Result<I::Item, ProgramError> {
    iter.next().ok_or(ProgramError::NotEnoughAccountKeys)
}

pub const MAX_TRANSACTION_TO_SIGN: usize = 4 * 1024;

/// Sets an Arch transaction to be signed by the program.
///
/// This function takes a transaction and its associated signing metadata and prepares it
/// for signing through the runtime. It also updates the UTXO metadata for relevant accounts.
///
/// # Arguments
/// * `accounts` - Slice of account information required for the transaction
/// * `tx` - The transaction
/// * `inputs_to_sign` - The inputs to sign
///
/// # Returns
/// * `ProgramResult` - Ok(()) if successful, or an error if the operation fails
pub fn set_transaction_to_sign<'info, T>(
    accounts: &[T],
    tx: &Transaction,
    inputs_to_sign: &[InputToSign],
) -> ProgramResult
where
    T: AsRef<AccountInfo<'info>>,
{
    msg!("setting tx to sign");
    // Use the new method that avoids double allocation

    let serialized_tx_bytes = bitcoin::consensus::serialize(tx);
    let serialized_inputs_to_sign = TransactionToSign::serialise_inputs_to_sign(inputs_to_sign);

    #[cfg(target_os = "solana")]
    let set_tx_result = unsafe {
        crate::syscalls::arch_set_transaction_to_sign(
            serialized_tx_bytes.as_ptr(),
            serialized_tx_bytes.len() as u64,
        )
    };
    #[cfg(not(target_os = "solana"))]
    let set_tx_result = crate::program_stubs::arch_set_transaction_to_sign(
        serialized_tx_bytes.as_ptr(),
        serialized_tx_bytes.len(),
    );

    #[cfg(target_os = "solana")]
    let set_inputs_to_sign_result = unsafe {
        crate::syscalls::arch_set_inputs_to_sign(
            serialized_inputs_to_sign.as_ptr(),
            serialized_inputs_to_sign.len() as u64,
        )
    };
    #[cfg(not(target_os = "solana"))]
    let set_inputs_to_sign_result = crate::program_stubs::arch_set_inputs_to_sign(
        serialized_inputs_to_sign.as_ptr(),
        serialized_inputs_to_sign.len(),
    );

    match set_tx_result {
        crate::entrypoint::SUCCESS => match set_inputs_to_sign_result {
            crate::entrypoint::SUCCESS => {
                let txid = tx.compute_txid();
                let mut txid_bytes: [u8; 32] = txid.as_raw_hash().to_byte_array();
                txid_bytes.reverse();

                for input in inputs_to_sign {
                    if let Some(account) = accounts
                        .iter()
                        .find(|account| *account.as_ref().key == input.signer)
                    {
                        account
                            .as_ref()
                            .set_utxo(&UtxoMeta::from(txid_bytes, input.index));
                    }
                }
                Ok(())
            }
            _ => Err(set_inputs_to_sign_result.into()),
        },
        _ => Err(set_tx_result.into()),
    }
}

pub fn set_input_to_sign(
    accounts: &[AccountInfo],
    txid: [u8; 32],
    inputs_to_sign: &[InputToSign],
) -> ProgramResult {
    msg!("setting inputs to sign");

    let serialized_inputs_to_sign = TransactionToSign::serialise_inputs_to_sign(inputs_to_sign);

    #[cfg(target_os = "solana")]
    let set_inputs_to_sign_result = unsafe {
        crate::syscalls::arch_set_inputs_to_sign(
            serialized_inputs_to_sign.as_ptr(),
            serialized_inputs_to_sign.len() as u64,
        )
    };
    #[cfg(not(target_os = "solana"))]
    let set_inputs_to_sign_result = crate::program_stubs::arch_set_inputs_to_sign(
        serialized_inputs_to_sign.as_ptr(),
        serialized_inputs_to_sign.len(),
    );

    match set_inputs_to_sign_result {
        crate::entrypoint::SUCCESS => {
            for input in inputs_to_sign {
                if let Some(account) = accounts.iter().find(|account| *account.key == input.signer)
                {
                    account
                        .as_ref()
                        .set_utxo(&UtxoMeta::from(txid, input.index));
                }
            }
            Ok(())
        }
        _ => Err(set_inputs_to_sign_result.into()),
    }
}

/// Maximum size that can be set using [`set_return_data`].
pub const MAX_RETURN_DATA: usize = 1024;

/// Set the running program's return data.
///
/// Return data is a dedicated per-transaction buffer for data passed
/// from cross-program invoked programs back to their caller.
///
/// The maximum size of return data is [`MAX_RETURN_DATA`]. Return data is
/// retrieved by the caller with [`get_return_data`].
pub fn set_return_data(data: &[u8]) {
    unsafe { crate::syscalls::sol_set_return_data(data.as_ptr(), data.len() as u64) };
}

/// Get the return data from an invoked program.
///
/// For every transaction there is a single buffer with maximum length
/// [`MAX_RETURN_DATA`], paired with a [`Pubkey`] representing the program ID of
/// the program that most recently set the return data. Thus the return data is
/// a global resource and care must be taken to ensure that it represents what
/// is expected: called programs are free to set or not set the return data; and
/// the return data may represent values set by programs multiple calls down the
/// call stack, depending on the circumstances of transaction execution.
///
/// Return data is set by the callee with [`set_return_data`].
///
/// Return data is cleared before every CPI invocation &mdash; a program that
/// has invoked no other programs can expect the return data to be `None`; if no
/// return data was set by the previous CPI invocation, then this function
/// returns `None`.
///
/// Return data is not cleared after returning from CPI invocations &mdash; a
/// program that has called another program may retrieve return data that was
/// not set by the called program, but instead set by a program further down the
/// call stack; or, if a program calls itself recursively, it is possible that
/// the return data was not set by the immediate call to that program, but by a
/// subsequent recursive call to that program. Likewise, an external RPC caller
/// may see return data that was not set by the program it is directly calling,
/// but by a program that program called.
///
/// For more about return data see the [documentation for the return data proposal][rdp].
///
/// [rdp]: https://docs.solanalabs.com/proposals/return-data
#[inline(never)]
pub fn get_return_data() -> Option<(Pubkey, ReturnedData)> {
    use std::cmp::min;

    let mut buf = [0u8; MAX_RETURN_DATA];
    let mut program_id = Pubkey::default();

    let size = unsafe {
        crate::syscalls::sol_get_return_data(buf.as_mut_ptr(), buf.len() as u64, &mut program_id)
    };

    if size == 0 {
        None
    } else {
        let size = min(size as usize, MAX_RETURN_DATA);
        Some((program_id, ReturnedData::new(buf, size)))
    }
}

/// Retrieves a Bitcoin transaction by its transaction ID.
///
/// # Arguments
/// * `txid` - 32-byte array containing the Bitcoin transaction ID
///
/// # Returns
/// * `Option<BitcoinTransaction>` - The transaction if found, None if not found
#[inline(never)]
pub fn get_bitcoin_tx(txid: [u8; 32]) -> Option<BitcoinTransaction> {
    let mut buf: BitcoinTransaction = Default::default();

    #[cfg(target_os = "solana")]
    let size = unsafe {
        crate::syscalls::arch_get_bitcoin_tx(buf.as_mut_ptr(), buf.capacity() as u64, &txid)
    };
    #[cfg(not(target_os = "solana"))]
    let size = crate::program_stubs::arch_get_bitcoin_tx(buf.as_mut_ptr(), buf.capacity(), &txid);

    if size == 0 {
        return None;
    }

    buf.set_size(core::cmp::min(size as usize, MAX_BTC_TX_SIZE));

    Some(buf)
}

/// Extracts the value of a specific output from a serialized Bitcoin transaction.
///
/// This function is used to extract the value of a specific output from a serialized Bitcoin transaction.
///
/// # Arguments
/// * `tx` - The transaction bytes
/// * `output_index` - The output index to retrieve
///
/// # Returns
/// * `Option<u64>` - The output value if found, None if not found
#[inline(never)]
pub fn get_bitcoin_tx_output_value(txid: [u8; 32], vout: u32) -> Option<u64> {
    let mut buf: BitcoinTransaction = Default::default();

    #[cfg(target_os = "solana")]
    let size = unsafe {
        crate::syscalls::arch_get_bitcoin_tx(buf.as_mut_ptr(), buf.capacity() as u64, &txid)
    };
    #[cfg(not(target_os = "solana"))]
    let size = crate::program_stubs::arch_get_bitcoin_tx(buf.as_mut_ptr(), buf.capacity(), &txid);

    if size == 0 {
        return None;
    }

    buf.set_size(core::cmp::min(size as usize, MAX_BTC_TX_SIZE));

    extract_output_value(buf.as_slice(), vout as usize)
}

#[inline(never)]
fn extract_output_value(tx: &[u8], output_index: usize) -> Option<u64> {
    struct OutputExtractor {
        target_index: usize,
        value: Option<u64>,
    }

    impl Visitor for OutputExtractor {
        fn visit_tx_out(&mut self, vout: usize, tx_out: &bsl::TxOut) -> core::ops::ControlFlow<()> {
            if vout == self.target_index {
                // Calculate the position within the original transaction bytes
                let value = tx_out.value();
                self.value = Some(value);
                return core::ops::ControlFlow::Break(());
            }
            core::ops::ControlFlow::Continue(())
        }
    }

    let mut extractor = OutputExtractor {
        target_index: output_index,
        value: None,
    };

    // Parse transaction and visit outputs
    match bsl::Transaction::visit(tx, &mut extractor) {
        Ok(_) | Err(Error::VisitBreak) => extractor.value,
        Err(_) => None,
    }
}

/// Retrieves the runes from a Bitcoin output by its transaction ID and output index.
///
/// # Arguments
/// * `txid` - 32-byte array containing the Bitcoin transaction ID
/// * `output_index` - The output index to retrieve
///
/// # Returns
/// * `Option<Vec<RuneAmount>>` - The runes if found, None if not found
#[inline(never)]
pub fn get_runes_from_output(txid: [u8; 32], output_index: u32) -> Option<Vec<RuneAmount>> {
    use std::cmp::min;
    if txid == [0u8; 32] {
        return None;
    }

    let mut result: BitcoinRuneOutput = Default::default();

    #[cfg(target_os = "solana")]
    let size = unsafe {
        crate::syscalls::arch_get_runes_from_output(
            result.as_mut_ptr(),
            result.capacity() as u64,
            &txid,
            output_index,
        )
    };

    #[cfg(not(target_os = "solana"))]
    let size = crate::program_stubs::arch_get_runes_from_output(
        result.as_mut_ptr(),
        result.capacity(),
        &txid,
        output_index,
    );

    if size == 0 {
        None
    } else {
        result.set_size(min(size as usize, MAX_BTC_RUNE_OUTPUT_SIZE));
        borsh::from_slice::<Vec<RuneAmount>>(result.as_slice()).ok()
    }
}

/// Retrieves the runes from a Bitcoin output by its transaction ID and output index.
///
/// # Arguments
/// * `txid` - 32-byte array containing the Bitcoin transaction ID
/// * `output_index` - The output index to retrieve
///
/// # Returns
/// * `Option<RuneInfo>` - The runes if found, None if not found
#[inline(never)]
pub fn get_rune_info(block: u64, tx: u64) -> Option<RuneInfo> {
    use std::cmp::min;

    let mut result: RuneInfoBuf = Default::default();

    #[cfg(target_os = "solana")]
    let size = unsafe {
        crate::syscalls::arch_get_rune_info(
            result.as_mut_ptr(),
            result.capacity() as u64,
            block,
            tx,
        )
    };

    #[cfg(not(target_os = "solana"))]
    let size =
        crate::program_stubs::arch_get_rune_info(result.as_mut_ptr(), result.capacity(), block, tx);

    if size == 0 {
        None
    } else {
        result.set_size(min(size as usize, result.capacity()));
        borsh::from_slice::<RuneInfo>(result.as_slice()).ok()
    }
}

pub fn get_remaining_compute_units() -> u64 {
    #[cfg(target_os = "solana")]
    unsafe {
        crate::syscalls::get_remaining_compute_units()
    }

    #[cfg(not(target_os = "solana"))]
    crate::program_stubs::get_remaining_compute_units()
}
/// Retrieves the network's X-only public key.
///
/// This function fetches the X-only public key associated with the current network configuration.
///
/// # Returns
/// * `[u8; 32]` - The 32-byte X-only public key
pub fn get_network_xonly_pubkey() -> [u8; 32] {
    let mut buf = [0u8; 32];

    #[cfg(target_os = "solana")]
    let _ = unsafe { crate::syscalls::arch_get_network_xonly_pubkey(buf.as_mut_ptr()) };

    #[cfg(not(target_os = "solana"))]
    crate::program_stubs::arch_get_network_xonly_pubkey(buf.as_mut_ptr());
    buf
}

/// Validates if a UTXO is owned by the specified public key.
///
/// # Arguments
/// * `utxo` - The UTXO metadata to validate
/// * `owner` - The public key to check ownership against
///
/// # Returns
/// * `bool` - true if the UTXO is owned by the specified public key, false otherwise
pub fn validate_utxo_ownership(utxo: &UtxoMeta, owner: &Pubkey) -> bool {
    #[cfg(target_os = "solana")]
    unsafe {
        crate::syscalls::arch_validate_utxo_ownership(utxo, owner) != 0
    }

    #[cfg(not(target_os = "solana"))]
    {
        crate::program_stubs::arch_validate_utxo_ownership(utxo, owner) != 0
    }
}

/// Gets the script public key for a given account.
///
/// # Arguments
/// * `pubkey` - The public key of the account
///
/// # Returns
/// * `[u8; 34]` - The 34-byte script public key
pub fn get_account_script_pubkey(pubkey: &Pubkey) -> [u8; 34] {
    let mut buf = [0u8; 34];

    #[cfg(target_os = "solana")]
    let _ = unsafe { crate::syscalls::arch_get_account_script_pubkey(buf.as_mut_ptr(), pubkey) };

    #[cfg(not(target_os = "solana"))]
    crate::program_stubs::arch_get_account_script_pubkey(&mut buf, pubkey);
    buf
}

/// Retrieves the current Bitcoin block height from the runtime.
///
/// # Returns
/// * `u64` - The current Bitcoin block height
pub fn get_bitcoin_block_height() -> u64 {
    #[cfg(target_os = "solana")]
    unsafe {
        crate::syscalls::arch_get_bitcoin_block_height()
    }

    #[cfg(not(target_os = "solana"))]
    crate::program_stubs::arch_get_bitcoin_block_height()
}

/// Gets the current clock information from the runtime.
///
/// # Returns
/// * `Clock` - The current clock state containing timing information
pub fn get_clock() -> Clock {
    let mut clock = Clock::default();
    #[cfg(target_os = "solana")]
    unsafe {
        crate::syscalls::arch_get_clock(&mut clock)
    };

    #[cfg(not(target_os = "solana"))]
    let _ = crate::program_stubs::arch_get_clock(&mut clock);

    clock
}

/// Gets the current stack height from the runtime.
///
/// # Returns
/// * `u64` - The current stack height
pub fn get_stack_height() -> u64 {
    #[cfg(target_os = "solana")]
    unsafe {
        crate::syscalls::arch_get_stack_height()
    }

    #[cfg(not(target_os = "solana"))]
    crate::program_stubs::arch_get_stack_height()
}

/// Retrieves the confirmation status of a Bitcoin transaction by its transaction ID.
///
/// # Arguments
/// * `txid` - 32-byte array containing the Bitcoin transaction ID
///
/// # Returns
/// * `bool` - The confirmation status of the transaction, false if not found
pub fn get_bitcoin_tx_confirmation(txid: [u8; 32]) -> bool {
    let mut buf = [0u8; 1];

    #[cfg(target_os = "solana")]
    let _ = unsafe { crate::syscalls::arch_get_bitcoin_tx_confirmation(&txid, buf.as_mut_ptr()) };

    #[cfg(not(target_os = "solana"))]
    let _ = crate::program_stubs::arch_get_bitcoin_tx_confirmation(&txid, buf.as_mut_ptr());

    buf[0] == 1
}

pub fn get_transaction_to_sign() -> [u8; 1024] {
    // setting it to 2048 as large allocation can cause stack allocation errors as we have limited
    // stack space, we expect it to be useful only when debugging code
    // in case you need more space, use the syscall directly

    let mut buf = [0u8; 1024];

    #[cfg(target_os = "solana")]
    unsafe {
        crate::syscalls::arch_get_transaction_to_sign(buf.as_mut_ptr(), buf.len() as u64)
    };

    #[cfg(not(target_os = "solana"))]
    let _ = crate::program_stubs::arch_get_transaction_to_sign(buf.as_mut_ptr(), buf.len());

    buf
}