hopper-native 0.5.0

Low-level Solana backend for Hopper with zero-copy account access, syscalls, checked CPI infrastructure, PDA helpers, and entrypoint glue. no_std and no_alloc.
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
//! PDA (Program Derived Address) helpers.
//!
//! Direct syscall-based PDA creation and derivation. No external dependencies.

use crate::account_view::AccountView;
use crate::address::{Address, MAX_SEEDS, MAX_SEED_LEN};
use crate::error::ProgramError;

#[cfg(target_os = "solana")]
const CURVE25519_EDWARDS: u64 = 0;
#[cfg(target_os = "solana")]
const PDA_MARKER_BYTES: &[u8; 21] = crate::address::PDA_MARKER;

/// The PDA hash of `seeds` (every seed the caller passes, a bump included
/// if there is one), `program_id`, and the marker. Off chain and in
/// `const` evaluation; on chain the same bytes go through `sol_sha256`.
const fn pda_hash(seeds: &[&[u8]], bump: Option<u8>, program_id: &Address) -> [u8; 32] {
    let mut hasher = crate::sha256::ConstSha256::new();
    let mut i = 0;
    while i < seeds.len() {
        hasher = hasher.update(seeds[i]);
        i += 1;
    }
    if let Some(bump) = bump {
        hasher = hasher.update(&[bump]);
    }
    hasher
        .update(program_id.as_array())
        .update(crate::address::PDA_MARKER)
        .finalize()
}

/// The canonical program-derived address of `seeds` under `program_id`
/// and its bump, found at compile time.
///
/// This is `find_program_address` as a `const fn`: bumps 255 down to 0,
/// the first whose hash is not a point of the ed25519 curve. The seeds
/// may be any `const` expressions (a declared program id, another
/// constant address), not only literals. A program that knows its seeds
/// at build time pays nothing on chain for the search and stores no bump:
///
/// ```ignore
/// const CONFIG: (Address, u8) = find_program_address_const(&[b"config"], &crate::ID);
/// ```
///
/// Panics (a compile error in a `const`) on 16 or more seeds, a seed
/// longer than 32 bytes, or when no bump yields an address off the curve.
pub const fn find_program_address_const(seeds: &[&[u8]], program_id: &Address) -> (Address, u8) {
    assert!(
        seeds.len() < MAX_SEEDS,
        "a PDA takes at most 15 seeds plus its bump"
    );
    let mut i = 0;
    while i < seeds.len() {
        assert!(
            seeds[i].len() <= MAX_SEED_LEN,
            "a PDA seed is at most 32 bytes"
        );
        i += 1;
    }
    let mut bump = u8::MAX;
    loop {
        let hash = pda_hash(seeds, Some(bump), program_id);
        if !crate::curve25519::is_on_curve(&hash) {
            return (Address::new_from_array(hash), bump);
        }
        assert!(bump != 0, "no bump yields an address off the curve");
        bump -= 1;
    }
}

/// SHA-based paths must accept exactly the seed domain that the PDA signing
/// syscall accepts. A helper which appends a bump reserves one of the 16 slots.
#[inline(always)]
fn validate_seeds(seeds: &[&[u8]], max_count: usize) -> Result<(), ProgramError> {
    if seeds.len() > max_count || seeds.iter().any(|seed| seed.len() > MAX_SEED_LEN) {
        return Err(ProgramError::InvalidSeeds);
    }
    Ok(())
}

/// Create a program-derived address from seeds and a program ID.
///
/// Returns `Err(InvalidSeeds)` if the derived address falls on the
/// ed25519 curve (not a valid PDA), or if more than [`MAX_SEEDS`] seeds
/// are supplied (matching upstream `Pubkey::create_program_address`
/// semantics, never silently truncating the seed set).
#[inline(always)]
pub fn create_program_address(
    seeds: &[&[u8]],
    program_id: &Address,
) -> Result<Address, ProgramError> {
    validate_seeds(seeds, MAX_SEEDS)?;
    #[cfg(target_os = "solana")]
    {
        // The syscall reads `seeds.len()` (ptr, len) pairs of 8-byte words,
        // which is exactly the in-memory shape of a `&[&[u8]]` on the SBF
        // target (the same layout the Solana SDK and pinocchio hand over).
        // Passing the slice directly replaces the zero-filled 256-byte
        // staging buffer and repack loop the wrapper used to run before
        // every derivation; measured 2026-09-21 on the framework-comparison
        // counter at ~70 CU per call above the syscall's own charge.
        const _: () = assert!(core::mem::size_of::<&[u8]>() == 16);
        // Uninitialized: the syscall writes all 32 bytes on success, and
        // zero-filling first cost four stores it then overwrote.
        let mut result = core::mem::MaybeUninit::<Address>::uninit();
        // SAFETY: `seeds` is a live `&[&[u8]]` whose SBF layout is the
        // (pointer, length) array the syscall reads (the size is asserted
        // above); `program_id` is 32 readable bytes and `result` 32 writable
        // ones.
        let rc = unsafe {
            crate::syscalls::sol_create_program_address(
                seeds.as_ptr() as *const u8,
                seeds.len() as u64,
                program_id.as_array().as_ptr(),
                result.as_mut_ptr() as *mut u8,
            )
        };
        if rc == 0 {
            // SAFETY: a zero return means the syscall wrote the whole
            // address, and every byte pattern is a valid `Address`.
            Ok(unsafe { result.assume_init() })
        } else {
            Err(ProgramError::InvalidSeeds)
        }
    }
    #[cfg(not(target_os = "solana"))]
    {
        // Off chain: the same hash and the same curve rejection the
        // syscall applies.
        let hash = pda_hash(seeds, None, program_id);
        if crate::curve25519::is_on_curve(&hash) {
            Err(ProgramError::InvalidSeeds)
        } else {
            Ok(Address::new_from_array(hash))
        }
    }
}

/// Find a program-derived address and its bump seed.
///
/// Iterates bump seeds 255..=0 until a valid PDA is found.
///
/// # Panics
///
/// Panics if no viable bump exists, 16 or more base seeds are supplied,
/// or a seed exceeds 32 bytes. The bump occupies the final seed slot,
/// matching upstream `Pubkey::find_program_address` semantics.
/// Silently returning a placeholder here would hand callers the all-zero
/// address, the System Program, as if it were their PDA. Use
/// [`based_try_find_program_address`] for the fallible variant.
///
/// `#[inline(always)]` is deliberate: outlining the sibling
/// `verify_pda_sha256_loop` was measured on 2026-07-09 at only −88 bytes
/// of release `.text` for +44..+73 CU on every benched vault row, the
/// call boundary defeats LLVM's per-call-site specialization of the seed
/// staging and bump loop. The size answer to PDA duplication is
/// `bump = stored` (one hash, no search), not outlining the search.
#[inline(always)]
pub fn find_program_address(seeds: &[&[u8]], program_id: &Address) -> (Address, u8) {
    match based_try_find_program_address(seeds, program_id) {
        Ok(found) => found,
        Err(_) => panic!("hopper: unable to find a viable program address bump seed"),
    }
}

/// The program-derived address for `seeds` and `bump` under `program_id`,
/// computed with the const SHA-256 so it can be evaluated at compile time.
///
/// This is the hash half of `create_program_address` (seeds, bump, program
/// id, the `ProgramDerivedAddress` marker) without the curve rejection, so
/// callers must pass the canonical bump their client obtained from
/// `find_program_address`; a bump the runtime would skip because its hash
/// lands on the ed25519 curve is not detected here. Static seeds hashed
/// once at compile time turn a runtime PDA check into a 32-byte compare.
/// Panics on 16 or more base seeds or a seed longer than 32 bytes. The bump
/// occupies one of the runtime's 16 seed slots. In a const expression the
/// refusal is a compilation error.
pub const fn program_address_const(seeds: &[&[u8]], bump: u8, program_id: &Address) -> Address {
    assert!(
        seeds.len() < MAX_SEEDS,
        "a PDA takes at most 15 seeds plus its bump"
    );
    let mut hasher = crate::sha256::ConstSha256::new();
    let mut i = 0;
    while i < seeds.len() {
        assert!(
            seeds[i].len() <= crate::address::MAX_SEED_LEN,
            "a PDA seed is at most 32 bytes"
        );
        hasher = hasher.update(seeds[i]);
        i += 1;
    }
    let hash = hasher
        .update(&[bump])
        .update(program_id.as_array())
        .update(crate::address::PDA_MARKER)
        .finalize();
    Address::new_from_array(hash)
}

/// Verify that an expected address matches the PDA hash for the provided seeds.
///
/// The seeds slice must already include the bump byte.
/// This checks hash equality only. It does not establish curve membership,
/// canonicality, account ownership, or an account's initialization history.
#[inline(always)]
pub fn verify_program_address(
    seeds: &[&[u8]],
    program_id: &Address,
    expected: &Address,
) -> Result<(), ProgramError> {
    validate_seeds(seeds, MAX_SEEDS)?;

    #[cfg(target_os = "solana")]
    {
        let n = seeds.len();
        let mut slices = core::mem::MaybeUninit::<[&[u8]; MAX_SEEDS + 2]>::uninit();
        let slice_ptr = slices.as_mut_ptr() as *mut &[u8];

        let mut i = 0;
        while i < n {
            // SAFETY: `validate_seeds` bounded `n`, so every index written is
            // inside the `MAX_SEEDS + 2` descriptor array; `write`
            // initializes a slot without reading the uninitialized memory it
            // replaces.
            unsafe { slice_ptr.add(i).write(seeds[i]) };
            i += 1;
        }
        // SAFETY: `validate_seeds` bounded `n`, so every index written is
        // inside the `MAX_SEEDS + 2` descriptor array; `write` initializes a
        // slot without reading the uninitialized memory it replaces.
        unsafe {
            slice_ptr.add(n).write(program_id.as_ref());
            slice_ptr.add(n + 1).write(PDA_MARKER_BYTES.as_slice());
        }

        // SAFETY: The first `n + 2` descriptors were initialized above, and
        // only that prefix is exposed.
        let input = unsafe { core::slice::from_raw_parts(slice_ptr, n + 2) };
        let mut hash = core::mem::MaybeUninit::<[u8; 32]>::uninit();

        // SAFETY: `input` is `n + 2` initialized descriptors whose slices are
        // all live; `hash` has room for the 32 bytes the syscall writes.
        unsafe {
            crate::syscalls::sol_sha256(
                input as *const _ as *const u8,
                input.len() as u64,
                hash.as_mut_ptr() as *mut u8,
            );
        }

        // SAFETY: `sol_sha256` wrote all 32 bytes of `hash` (it aborts the
        // transaction otherwise), and `Address` is `#[repr(transparent)]`
        // over `[u8; 32]`.
        let derived = unsafe { &*(hash.as_ptr() as *const Address) };
        if derived == expected {
            Ok(())
        } else {
            Err(ProgramError::InvalidSeeds)
        }
    }
    #[cfg(not(target_os = "solana"))]
    {
        if pda_hash(seeds, None, program_id) == *expected.as_array() {
            Ok(())
        } else {
            Err(ProgramError::InvalidSeeds)
        }
    }
}

/// Find a valid PDA by hashing seeds directly and checking curve validity.
///
/// This avoids the `sol_try_find_program_address` syscall and substantially
/// reduces the per-attempt CU cost on SBF.
#[inline(always)]
pub fn based_try_find_program_address(
    seeds: &[&[u8]],
    program_id: &Address,
) -> Result<(Address, u8), ProgramError> {
    validate_seeds(seeds, MAX_SEEDS - 1)?;

    #[cfg(target_os = "solana")]
    {
        let n = seeds.len();
        let mut slices = core::mem::MaybeUninit::<[&[u8]; MAX_SEEDS + 2]>::uninit();
        let slice_ptr = slices.as_mut_ptr() as *mut &[u8];

        let mut i = 0;
        while i < n {
            // SAFETY: `validate_seeds` bounded `n`, so every index written is
            // inside the `MAX_SEEDS + 2` descriptor array; `write`
            // initializes a slot without reading the uninitialized memory it
            // replaces.
            unsafe { slice_ptr.add(i).write(seeds[i]) };
            i += 1;
        }
        // SAFETY: `validate_seeds` bounded `n`, so every index written is
        // inside the `MAX_SEEDS + 2` descriptor array; `write` initializes a
        // slot without reading the uninitialized memory it replaces.
        unsafe {
            slice_ptr.add(n + 1).write(program_id.as_ref());
            slice_ptr.add(n + 2).write(PDA_MARKER_BYTES.as_slice());
        }

        let mut hash = core::mem::MaybeUninit::<[u8; 32]>::uninit();
        let mut bump: u64 = u8::MAX as u64;

        loop {
            let bump_seed = [bump as u8];
            // SAFETY: n <= MAX_SEEDS - 1. Install this iteration's immutable
            // seed before constructing the initialized prefix. The syscall
            // consumes it synchronously; no shared seed reference is reused
            // after the next iteration rewrites the descriptor array.
            unsafe {
                slice_ptr
                    .add(n)
                    .write(core::slice::from_raw_parts(bump_seed.as_ptr(), 1))
            };
            let input = unsafe { core::slice::from_raw_parts(slice_ptr, n + 3) };

            // SAFETY: All n + 3 descriptors are initialized, every referenced
            // byte is live for the call, and hash has space for its 32-byte output.
            unsafe {
                crate::syscalls::sol_sha256(
                    input as *const _ as *const u8,
                    input.len() as u64,
                    hash.as_mut_ptr() as *mut u8,
                );
            }

            // SAFETY: `hash` was fully written by sol_sha256 above; the
            // syscall only reads 32 bytes from it.
            // Return code semantics: 0 = the point IS on the ed25519 curve
            // (not a valid PDA), nonzero = off-curve (valid PDA).
            let curve_rc = unsafe {
                crate::syscalls::sol_curve_validate_point(
                    CURVE25519_EDWARDS,
                    hash.as_ptr() as *const u8,
                    core::ptr::null_mut(),
                )
            };

            if curve_rc != 0 {
                return Ok((
                    // SAFETY: `sol_sha256` wrote all 32 bytes of `hash` in
                    // this iteration before the curve check read them.
                    Address::new_from_array(unsafe { hash.assume_init() }),
                    bump as u8,
                ));
            }

            if bump == 0 {
                break;
            }
            bump -= 1;
        }

        Err(ProgramError::InvalidSeeds)
    }
    #[cfg(not(target_os = "solana"))]
    {
        let mut bump = u8::MAX;
        loop {
            let hash = pda_hash(seeds, Some(bump), program_id);
            if !crate::curve25519::is_on_curve(&hash) {
                return Ok((Address::new_from_array(hash), bump));
            }
            if bump == 0 {
                return Err(ProgramError::InvalidSeeds);
            }
            bump -= 1;
        }
    }
}

/// Verify that an account's address matches a PDA derived from the given seeds.
///
/// Returns `Ok(())` if the account address matches the derived PDA,
/// or `Err(InvalidSeeds)` if it does not.
#[inline(always)]
pub fn verify_pda(
    account: &AccountView<'_>,
    seeds: &[&[u8]],
    program_id: &Address,
) -> Result<(), ProgramError> {
    let expected = create_program_address(seeds, program_id)?;
    if account.address() == &expected {
        Ok(())
    } else {
        Err(ProgramError::InvalidSeeds)
    }
}

/// Verify a PDA with an explicit bump seed appended to the seeds.
///
/// Appends `&[bump]` to the end of the seed list before verifying via
/// SHA-256 (~200 CU). This is substantially cheaper than the syscall-based
/// `create_program_address` approach (~1500 CU).
///
/// Returns `Err(InvalidSeeds)` for 16 or more base seeds or a seed longer
/// than 32 bytes. The bump counts toward the 16-seed runtime limit.
///
/// # Bump canonicalization
///
/// `bump` must be the **canonical** bump for these seeds, the one
/// `find_program_address` returns and the program stored at init. Passing
/// an attacker-supplied bump (e.g. straight from instruction data) lets
/// multiple addresses verify for the same logical seed set, the classic
/// bump-canonicalization vulnerability. Prefer
/// [`verify_pda_from_stored_bump`], which reads the bump the account
/// itself recorded.
#[inline]
pub fn verify_pda_with_bump(
    account: &AccountView<'_>,
    seeds: &[&[u8]],
    bump: u8,
    program_id: &Address,
) -> Result<(), ProgramError> {
    validate_seeds(seeds, MAX_SEEDS - 1)?;
    // Build a seed list with the bump appended.
    // Stack-allocated: at most 15 base seeds plus the bump.
    let mut full_seeds: [&[u8]; MAX_SEEDS] = [&[]; MAX_SEEDS];
    let num = seeds.len();
    let mut i = 0;
    while i < num {
        full_seeds[i] = seeds[i];
        i += 1;
    }
    let bump_bytes = [bump];
    full_seeds[num] = &bump_bytes;

    verify_program_address(&full_seeds[..num + 1], program_id, account.address())
}

/// Verify that an address matches a PDA derived from the given seeds.
///
/// Unlike `verify_pda` which takes an `AccountView`, this accepts a raw
/// `Address` reference directly. Useful when validating addresses outside
/// of the account parsing flow (e.g. instruction data, cross-program reads).
///
/// The seeds slice must already include the bump byte (like
/// `verify_program_address`). Uses SHA-256 verify-only path (~200 CU)
/// instead of the full `find_program_address` (~1500 CU).
///
/// The included bump must be the **canonical** one for the seed set (see
/// [`verify_pda_with_bump`]'s bump-canonicalization note): verifying with
/// an attacker-supplied bump lets multiple addresses pass for the same
/// logical seeds.
///
/// Returns `Ok(())` if the address matches the derived PDA,
/// or `Err(InvalidSeeds)` if it does not.
#[inline]
pub fn verify_pda_strict(
    expected: &Address,
    seeds: &[&[u8]],
    program_id: &Address,
) -> Result<(), ProgramError> {
    verify_program_address(seeds, program_id, expected)
}

/// Find the bump seed for a known PDA address, skipping curve validation.
///
/// This is a hash-match search, not canonical derivation or an off-curve
/// proof. Mere presence in a transaction or existence on chain does not
/// establish either property. The caller must establish the required PDA
/// provenance separately. Use [`based_try_find_program_address`] and compare
/// its result when a canonical address is required.
///
/// Returns the bump seed, or `Err(InvalidSeeds)` if no bump produces a match.
#[inline(always)]
pub fn find_bump_for_address(
    seeds: &[&[u8]],
    program_id: &Address,
    expected: &Address,
) -> Result<u8, ProgramError> {
    validate_seeds(seeds, MAX_SEEDS - 1)?;

    #[cfg(target_os = "solana")]
    {
        let n = seeds.len();
        let mut slices = core::mem::MaybeUninit::<[&[u8]; MAX_SEEDS + 2]>::uninit();
        let slice_ptr = slices.as_mut_ptr() as *mut &[u8];

        let mut i = 0;
        while i < n {
            // SAFETY: `validate_seeds` bounded `n`, so every index written is
            // inside the `MAX_SEEDS + 2` descriptor array; `write`
            // initializes a slot without reading the uninitialized memory it
            // replaces.
            unsafe { slice_ptr.add(i).write(seeds[i]) };
            i += 1;
        }
        // SAFETY: `validate_seeds` bounded `n`, so every index written is
        // inside the `MAX_SEEDS + 2` descriptor array; `write` initializes a
        // slot without reading the uninitialized memory it replaces.
        unsafe {
            slice_ptr.add(n + 1).write(program_id.as_ref());
            slice_ptr.add(n + 2).write(PDA_MARKER_BYTES.as_slice());
        }

        let mut hash = core::mem::MaybeUninit::<[u8; 32]>::uninit();
        let mut bump: u64 = u8::MAX as u64;

        loop {
            let bump_seed = [bump as u8];
            // SAFETY: n <= MAX_SEEDS - 1. Install this iteration's immutable
            // seed before constructing the initialized prefix. No shared
            // seed reference is reused after its backing byte changes.
            unsafe {
                slice_ptr
                    .add(n)
                    .write(core::slice::from_raw_parts(bump_seed.as_ptr(), 1))
            };
            let input = unsafe { core::slice::from_raw_parts(slice_ptr, n + 3) };

            // SAFETY: All descriptors and input bytes remain live through the
            // synchronous call, which fills the 32-byte hash output.
            unsafe {
                crate::syscalls::sol_sha256(
                    input as *const _ as *const u8,
                    input.len() as u64,
                    hash.as_mut_ptr() as *mut u8,
                );
            }

            // Address-match shortcut: skip curve check entirely.
            // Matching this address does not establish canonicality or
            // curve membership; those are separate caller obligations.
            // SAFETY: `sol_sha256` wrote all 32 bytes of `hash` in this
            // iteration, and `Address` is `#[repr(transparent)]` over `[u8;
            // 32]`.
            let derived = unsafe { &*(hash.as_ptr() as *const Address) };
            if derived == expected {
                return Ok(bump as u8);
            }

            if bump == 0 {
                break;
            }
            bump -= 1;
        }

        Err(ProgramError::InvalidSeeds)
    }
    #[cfg(not(target_os = "solana"))]
    {
        // The same hash-match search as on chain: no curve check.
        let mut bump = u8::MAX;
        loop {
            if pda_hash(seeds, Some(bump), program_id) == *expected.as_array() {
                return Ok(bump);
            }
            if bump == 0 {
                return Err(ProgramError::InvalidSeeds);
            }
            bump -= 1;
        }
    }
}

/// Read the bump byte directly from account data at a known offset.
///
/// Used with `BUMP_OFFSET` from `hopper_layout!` types to read the stored
/// bump without any derivation. Combined with `verify_program_address`,
/// the total PDA verification cost is ~200 CU vs ~1500 CU for
/// `find_program_address`.
///
/// Returns `Err(AccountDataTooSmall)` if the account data is shorter than
/// `bump_offset + 1`.
#[inline(always)]
pub fn read_bump_from_account(
    account: &AccountView<'_>,
    bump_offset: usize,
) -> Result<u8, ProgramError> {
    let data = account.try_borrow()?;
    if data.len() <= bump_offset {
        return Err(ProgramError::AccountDataTooSmall);
    }
    Ok(data[bump_offset])
}

/// Verify a PDA using the bump stored in account data (cheapest path).
///
/// Reads the bump at `bump_offset`, appends it to seeds, then uses
/// SHA-256 verify-only. Total cost: ~200 CU vs ~1500 CU.
///
/// This is the optimal PDA verification path and should be the default
/// for Hopper programs that store bumps in their account layout.
#[inline]
pub fn verify_pda_from_stored_bump(
    account: &AccountView<'_>,
    seeds: &[&[u8]],
    bump_offset: usize,
    program_id: &Address,
) -> Result<(), ProgramError> {
    validate_seeds(seeds, MAX_SEEDS - 1)?;
    let bump = read_bump_from_account(account, bump_offset)?;

    let mut full_seeds: [&[u8]; MAX_SEEDS] = [&[]; MAX_SEEDS];
    let num = seeds.len();
    let mut i = 0;
    while i < num {
        full_seeds[i] = seeds[i];
        i += 1;
    }
    let bump_bytes = [bump];
    full_seeds[num] = &bump_bytes;

    verify_program_address(&full_seeds[..num + 1], program_id, account.address())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn const_pda_accepts_fifteen_base_seeds() {
        let id = Address::new_from_array([91; 32]);
        let fifteen: [&[u8]; 15] = [&[]; 15];
        assert_eq!(
            program_address_const(&fifteen, 255, &id),
            program_address_const(&[], 255, &id)
        );
    }

    #[test]
    #[should_panic(expected = "at most 15 seeds plus its bump")]
    fn const_pda_reserves_the_bump_slot() {
        let seeds: [&[u8]; 16] = [&[]; 16];
        program_address_const(&seeds, 255, &Address::new_from_array([91; 32]));
    }

    #[test]
    #[should_panic(expected = "at most 32 bytes")]
    fn const_pda_rejects_oversized_seeds() {
        program_address_const(&[&[0; 33]], 255, &Address::new_from_array([91; 32]));
    }
}