hopper-runtime 0.4.5

Canonical low-level runtime surface for Hopper programs: direct account memory, validation, borrow guards, CPI, and zero-copy state access.
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
//! Zero-copy Token-2022 extension TLV readers.
//!
//! Token-2022 stores extension data in a TLV region after a fixed
//! per-account prefix. Each TLV entry is
//! `[type: u16 LE][length: u16 LE][data: length bytes]`.
//!
//! This module reads Token-2022 TLV data directly from account bytes,
//! avoiding full-account decode while preserving the on-chain wire
//! rules.
//!
//! Every reader here validates only the bytes it reads. No heap
//! allocation, no full-account decode, no version coupling to
//! `spl-token-2022`. A program that needs to enforce
//! `transfer_hook::authority = X` on a mint calls [`require_transfer_hook_authority`]
//! and pays the cost of a TLV scan plus a 32-byte compare. That is the
//! cost floor for a correct check.
//!
//! ## On-chain layout (authoritative)
//!
//! An extended mint is padded to the same length as an extended token
//! account so that the Token-2022 program cannot confuse the two by
//! data length alone; the one-byte `AccountType` discriminator at
//! offset `ACCOUNT_TYPE_OFFSET` (= 165) disambiguates them.
//!
//! ```text
//! Extended mint         : [0..82] Mint base | [82..165] padding | [165] AccountType=1 | [166..] TLV
//! Extended token account: [0..165] Account base                 | [165] AccountType=2 | [166..] TLV
//! ```
//!
//! Both shapes place the AccountType byte at offset 165 and begin TLV
//! data at offset 166. `BASE_MINT_LEN` (82) is the length of a *plain*,
//! non-extended mint and is used by length checks; it is **not** the
//! offset at which mint extensions live. This layout matches
//! `spl-token-2022` (`validate_account_type` keys on
//! `bytes[BASE_ACCOUNT_LENGTH]` where `BASE_ACCOUNT_LENGTH = 165`).
//!
//! ## Extension type constants
//!
//! Values are the on-chain `u16` encoding from
//! `spl-token-2022::extension::ExtensionType`. They are stable wire
//! values and safe to hard-code. The full set is listed below so
//! tooling can surface the name for any TLV it encounters.
//!
//! ## Authority comparisons and `OptionalNonZeroPubkey`
//!
//! Token-2022 stores optional authorities as `OptionalNonZeroPubkey`:
//! an **all-zero pubkey means "not set"**. The `require_*_authority`
//! comparators below do a plain 32-byte compare, so passing an all-zero
//! `expected` would "match" an unset authority. Never pass
//! `Address::default()` as the expected authority; if the intent is
//! "authority must be unset", compare against zero explicitly and name
//! that intent in the calling code.

use crate::{account::AccountView, address::Address, error::ProgramError, result::ProgramResult};

// ---------------------------------------------------------------------

pub const EXT_UNINITIALIZED: u16 = 0;
pub const EXT_TRANSFER_FEE_CONFIG: u16 = 1;
pub const EXT_TRANSFER_FEE_AMOUNT: u16 = 2;
pub const EXT_MINT_CLOSE_AUTHORITY: u16 = 3;
pub const EXT_CONFIDENTIAL_TRANSFER_MINT: u16 = 4;
pub const EXT_CONFIDENTIAL_TRANSFER_ACCOUNT: u16 = 5;
pub const EXT_DEFAULT_ACCOUNT_STATE: u16 = 6;
pub const EXT_IMMUTABLE_OWNER: u16 = 7;
pub const EXT_MEMO_TRANSFER: u16 = 8;
pub const EXT_NON_TRANSFERABLE: u16 = 9;
pub const EXT_INTEREST_BEARING_CONFIG: u16 = 10;
pub const EXT_CPI_GUARD: u16 = 11;
pub const EXT_PERMANENT_DELEGATE: u16 = 12;
pub const EXT_NON_TRANSFERABLE_ACCOUNT: u16 = 13;
pub const EXT_TRANSFER_HOOK: u16 = 14;
pub const EXT_TRANSFER_HOOK_ACCOUNT: u16 = 15;
pub const EXT_CONFIDENTIAL_TRANSFER_FEE_CONFIG: u16 = 16;
pub const EXT_CONFIDENTIAL_TRANSFER_FEE_AMOUNT: u16 = 17;
pub const EXT_METADATA_POINTER: u16 = 18;
pub const EXT_TOKEN_METADATA: u16 = 19;
pub const EXT_GROUP_POINTER: u16 = 20;
pub const EXT_TOKEN_GROUP: u16 = 21;
pub const EXT_GROUP_MEMBER_POINTER: u16 = 22;
pub const EXT_TOKEN_GROUP_MEMBER: u16 = 23;
pub const EXT_CONFIDENTIAL_MINT_BURN: u16 = 24;
pub const EXT_SCALED_UI_AMOUNT_CONFIG: u16 = 25;
pub const EXT_PAUSABLE_CONFIG: u16 = 26;
pub const EXT_PAUSABLE_ACCOUNT: u16 = 27;
pub const EXT_PERMISSIONED_BURN: u16 = 28;

/// Highest Token-2022 extension discriminator understood by this release.
///
/// Allowlist policies deliberately reject larger values. A newly deployed
/// extension must be reviewed and added explicitly instead of silently
/// inheriting assumptions written for an older Token-2022 program.
pub const MAX_KNOWN_EXTENSION_TYPE: u16 = EXT_PERMISSIONED_BURN;

/// Account-type byte: Mint.
pub const ACCOUNT_TYPE_MINT: u8 = 0x01;
/// Account-type byte: Token Account.
pub const ACCOUNT_TYPE_TOKEN: u8 = 0x02;

/// Length of a plain (non-extended) mint's data region.
///
/// This is the stride of the `Mint` base struct; it is **not** the
/// offset at which mint extensions begin (see [`TLV_OFFSET`]). Used
/// for the length-only check that distinguishes a legacy SPL mint
/// (exactly 82 bytes) from an extended Token-2022 mint.
pub const BASE_MINT_LEN: usize = 82;
/// Length of a plain (non-extended) token-account's data region.
///
/// Also equal to [`ACCOUNT_TYPE_OFFSET`]: an extended mint is padded
/// up to this length so that the AccountType discriminator sits at
/// the same offset as on an extended token account.
pub const BASE_TOKEN_LEN: usize = 165;
/// Canonical SPL Token / Token-2022 multisig account length.
///
/// Token-2022's allocator deliberately pads extensible state away from this
/// exact size, so it is never a valid mint or token-account TLV envelope.
pub const TOKEN_MULTISIG_LEN: usize = 355;
/// Offset of the `AccountType` discriminator on any extended
/// Token-2022 account (mint or token account).
pub const ACCOUNT_TYPE_OFFSET: usize = BASE_TOKEN_LEN;
/// Offset at which the TLV extension region begins on any extended
/// Token-2022 account (mint or token account).
pub const TLV_OFFSET: usize = ACCOUNT_TYPE_OFFSET + 1;
/// Start of the mint's extension padding region (82..165). Bytes in
/// this range are zero-filled and exist purely to equalize the length
/// of extended mints and extended token accounts.
pub const MINT_EXTENSION_PADDING_START: usize = BASE_MINT_LEN;
/// End of the mint extension padding region (exclusive).
pub const MINT_EXTENSION_PADDING_END: usize = ACCOUNT_TYPE_OFFSET;

// ---------------------------------------------------------------------

/// Locate an extension in a Token-2022 account's TLV region.
///
/// Returns the slice of the extension's data bytes (not including the
/// 4-byte TLV header) or `None` if the extension is not present.
///
/// `tlv_bytes` must be the account data starting at the TLV region
/// (i.e. `&data[TLV_OFFSET..]` for both mints and token accounts).
/// Use [`mint_tlv_region`] or [`token_account_tlv_region`] to obtain
/// this slice safely. Malformed TLVs (length runs past the buffer)
/// return `None` rather than panic.
///
/// One pass, O(n) in the TLV count. No allocation. The caller is
/// expected to amortize calls by grouping checks.
#[inline]
pub fn find_extension(tlv_bytes: &[u8], ext_type: u16) -> Option<&[u8]> {
    let mut cursor = 0usize;
    while cursor + 4 <= tlv_bytes.len() {
        let t = u16::from_le_bytes([tlv_bytes[cursor], tlv_bytes[cursor + 1]]);
        let len = u16::from_le_bytes([tlv_bytes[cursor + 2], tlv_bytes[cursor + 3]]) as usize;
        let data_start = cursor + 4;
        let data_end = data_start + len;
        if data_end > tlv_bytes.len() {
            return None;
        }
        if t == ext_type {
            return Some(&tlv_bytes[data_start..data_end]);
        }
        if t == EXT_UNINITIALIZED {
            // Uninitialized marker with zero length is a valid
            // stopping condition. Anything else with type 0 is
            // malformed padding; we stop scanning to avoid running
            // off the end through stray bytes.
            return None;
        }
        cursor = data_end;
    }
    None
}

/// Validate a TLV stream without allocating or interpreting extension data.
///
/// Unlike [`find_extension`], this function distinguishes a missing extension
/// from malformed bytes. Unknown non-zero type values remain structurally
/// valid here so generic readers stay forward-compatible. Security policies
/// that must fail closed on new extension semantics should use
/// [`validate_extension_allowlist`].
pub fn validate_tlv_structure(tlv_bytes: &[u8]) -> ProgramResult {
    let mut cursor = 0usize;
    while cursor < tlv_bytes.len() {
        // Token-2022 permits one trailing allocation byte during realloc.
        if tlv_bytes.len() - cursor < 2 {
            return Ok(());
        }

        let ext_type = u16::from_le_bytes([tlv_bytes[cursor], tlv_bytes[cursor + 1]]);
        if ext_type == EXT_UNINITIALIZED {
            return Ok(());
        }
        if tlv_bytes.len() - cursor < 4 {
            return Err(ProgramError::InvalidAccountData);
        }

        let len = u16::from_le_bytes([tlv_bytes[cursor + 2], tlv_bytes[cursor + 3]]) as usize;
        cursor = cursor
            .checked_add(4)
            .and_then(|start| start.checked_add(len))
            .ok_or(ProgramError::InvalidAccountData)?;
        if cursor > tlv_bytes.len() {
            return Err(ProgramError::InvalidAccountData);
        }
    }
    Ok(())
}

/// Require every initialized TLV entry to be known, unique, and allowlisted.
///
/// This is the fail-closed counterpart to the presence readers. It is suited
/// to custody and settlement code where an unknown future extension must not
/// be treated as harmless merely because an older denylist did not name it.
pub fn validate_extension_allowlist(tlv_bytes: &[u8], allowed: &[u16]) -> ProgramResult {
    let mut cursor = 0usize;
    let mut seen = 0u32;
    while cursor < tlv_bytes.len() {
        if tlv_bytes.len() - cursor < 2 {
            return Ok(());
        }

        let ext_type = u16::from_le_bytes([tlv_bytes[cursor], tlv_bytes[cursor + 1]]);
        if ext_type == EXT_UNINITIALIZED {
            return Ok(());
        }
        if ext_type > MAX_KNOWN_EXTENSION_TYPE || !allowed.contains(&ext_type) {
            return Err(ProgramError::InvalidAccountData);
        }
        let bit = 1u32
            .checked_shl(ext_type as u32)
            .ok_or(ProgramError::InvalidAccountData)?;
        if seen & bit != 0 {
            return Err(ProgramError::InvalidAccountData);
        }
        seen |= bit;

        if tlv_bytes.len() - cursor < 4 {
            return Err(ProgramError::InvalidAccountData);
        }
        let len = u16::from_le_bytes([tlv_bytes[cursor + 2], tlv_bytes[cursor + 3]]) as usize;
        cursor = cursor
            .checked_add(4)
            .and_then(|start| start.checked_add(len))
            .ok_or(ProgramError::InvalidAccountData)?;
        if cursor > tlv_bytes.len() {
            return Err(ProgramError::InvalidAccountData);
        }
    }
    Ok(())
}

/// Slice the TLV region out of a mint account's data.
///
/// Returns `None` if the account is too short to be an *extended*
/// Token-2022 mint (length must be strictly greater than
/// [`TLV_OFFSET`]; a plain 82-byte legacy mint has no TLV region).
///
/// Performs four validations:
/// 1. Account length is large enough to contain at least the TLV
///    header offset (`> TLV_OFFSET`, i.e. >= 166).
/// 2. The length is not the canonical 355-byte multisig shape.
/// 3. The `AccountType` discriminator at [`ACCOUNT_TYPE_OFFSET`]
///    is either [`ACCOUNT_TYPE_MINT`] (0x01) or `0x00`. We accept
///    `0x00` for a just-reallocated mint before the Token-2022 program
///    stamps its account type; every subsequent extension initializer
///    writes the correct byte, and the TLV scanner tolerates an
///    all-zero region by hitting `EXT_UNINITIALIZED` on the first
///    header read. This matches `spl-token-2022`'s permissive init
///    sequencing.
/// 4. The mint equalization padding is zero, then the tail slice begins at
///    [`TLV_OFFSET`] (166).
///
/// The bytes in `[BASE_MINT_LEN..ACCOUNT_TYPE_OFFSET]` (82..165) are
/// Token-2022's equalization padding. They are not part of the TLV stream, but
/// canonical unpacking requires them to remain zero.
#[inline]
pub fn mint_tlv_region(data: &[u8]) -> Option<&[u8]> {
    if data.len() <= TLV_OFFSET || data.len() == TOKEN_MULTISIG_LEN {
        return None;
    }
    let kind = data[ACCOUNT_TYPE_OFFSET];
    if kind != ACCOUNT_TYPE_MINT && kind != 0 {
        return None;
    }
    if data[MINT_EXTENSION_PADDING_START..MINT_EXTENSION_PADDING_END]
        .iter()
        .any(|byte| *byte != 0)
    {
        return None;
    }
    Some(&data[TLV_OFFSET..])
}

/// Slice the TLV region out of a token-account's data.
///
/// Returns `None` if the account is too short to be an *extended*
/// Token-2022 token account. Same validation shape as
/// [`mint_tlv_region`] but requires the discriminator at
/// [`ACCOUNT_TYPE_OFFSET`] be [`ACCOUNT_TYPE_TOKEN`] (0x02) or
/// `0x00`. TLV data is read from [`TLV_OFFSET`] (166).
#[inline]
pub fn token_account_tlv_region(data: &[u8]) -> Option<&[u8]> {
    if data.len() <= TLV_OFFSET || data.len() == TOKEN_MULTISIG_LEN {
        return None;
    }
    let kind = data[ACCOUNT_TYPE_OFFSET];
    if kind != ACCOUNT_TYPE_TOKEN && kind != 0 {
        return None;
    }
    Some(&data[TLV_OFFSET..])
}

/// A no-alloc Token-2022 extension policy over a TLV region.
///
/// `required` entries must be present; `forbidden` entries must be absent.
/// This is the common core beneath declarative account constraints and tiny
/// on-chain probes that want to validate a Token-2022 shape without pulling in
/// `spl-token-2022` deserialization.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ExtensionPolicy<'a> {
    pub required: &'a [u16],
    pub forbidden: &'a [u16],
}

impl<'a> ExtensionPolicy<'a> {
    #[inline]
    pub const fn new(required: &'a [u16], forbidden: &'a [u16]) -> Self {
        Self {
            required,
            forbidden,
        }
    }
}

#[inline]
pub fn require_extension(tlv: &[u8], ext_type: u16) -> ProgramResult {
    validate_tlv_structure(tlv)?;
    if find_extension(tlv, ext_type).is_some() {
        Ok(())
    } else {
        Err(ProgramError::InvalidAccountData)
    }
}

#[inline]
pub fn forbid_extension(tlv: &[u8], ext_type: u16) -> ProgramResult {
    validate_tlv_structure(tlv)?;
    if find_extension(tlv, ext_type).is_none() {
        Ok(())
    } else {
        Err(ProgramError::InvalidAccountData)
    }
}

#[inline]
pub fn validate_extension_policy(tlv: &[u8], policy: &ExtensionPolicy<'_>) -> ProgramResult {
    validate_tlv_structure(tlv)?;
    for ext_type in policy.required {
        if find_extension(tlv, *ext_type).is_none() {
            return Err(ProgramError::InvalidAccountData);
        }
    }
    for ext_type in policy.forbidden {
        if find_extension(tlv, *ext_type).is_some() {
            return Err(ProgramError::InvalidAccountData);
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------

/// Require a mint to carry the `NonTransferable` extension.
///
/// Use when a program is designed to only ever mint soulbound tokens.
#[inline]
pub fn require_non_transferable(mint: &AccountView<'_>) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    if find_extension(tlv, EXT_NON_TRANSFERABLE).is_some() {
        Ok(())
    } else {
        Err(ProgramError::InvalidAccountData)
    }
}

/// Require a mint's `MintCloseAuthority` extension to equal `expected`.
#[inline]
pub fn require_mint_close_authority(mint: &AccountView<'_>, expected: &Address) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext =
        find_extension(tlv, EXT_MINT_CLOSE_AUTHORITY).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 32 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[..32], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

/// Require a mint's `PermanentDelegate` extension to equal `expected`.
#[inline]
pub fn require_permanent_delegate(mint: &AccountView<'_>, expected: &Address) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext =
        find_extension(tlv, EXT_PERMANENT_DELEGATE).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 32 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[..32], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

/// Require a mint's `TransferHook` program id to equal `expected`.
///
/// `TransferHook` layout: `[authority: 32][program_id: 32]`. This
/// validates the second field. Use [`require_transfer_hook_authority`]
/// for the first.
#[inline]
pub fn require_transfer_hook_program(mint: &AccountView<'_>, expected: &Address) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext = find_extension(tlv, EXT_TRANSFER_HOOK).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 64 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[32..64], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectProgramId)
    }
}

/// Require a mint's `TransferHook` authority to equal `expected`.
#[inline]
pub fn require_transfer_hook_authority(
    mint: &AccountView<'_>,
    expected: &Address,
) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext = find_extension(tlv, EXT_TRANSFER_HOOK).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 32 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[..32], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

/// Require a mint's `MetadataPointer` metadata-address to equal `expected`.
///
/// `MetadataPointer` layout: `[authority: 32][metadata_address: 32]`.
#[inline]
pub fn require_metadata_pointer_address(
    mint: &AccountView<'_>,
    expected: &Address,
) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext = find_extension(tlv, EXT_METADATA_POINTER).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 64 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[32..64], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::InvalidAccountData)
    }
}

/// Require a mint's `MetadataPointer` authority to equal `expected`.
#[inline]
pub fn require_metadata_pointer_authority(
    mint: &AccountView<'_>,
    expected: &Address,
) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext = find_extension(tlv, EXT_METADATA_POINTER).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 32 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[..32], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

/// Require a token account to carry the `ImmutableOwner` extension.
#[inline]
pub fn require_immutable_owner(token_account: &AccountView<'_>) -> ProgramResult {
    let data = token_account
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = token_account_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    require_extension(tlv, EXT_IMMUTABLE_OWNER)
}

/// Require a token account to carry the `CpiGuard` extension.
#[inline]
pub fn require_cpi_guard(token_account: &AccountView<'_>) -> ProgramResult {
    let data = token_account
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = token_account_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    require_extension(tlv, EXT_CPI_GUARD)
}

/// Require a mint to carry the `ConfidentialTransferMint` extension.
#[inline]
pub fn require_confidential_transfer_mint(mint: &AccountView<'_>) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    require_extension(tlv, EXT_CONFIDENTIAL_TRANSFER_MINT)
}

/// Require a token account to carry the `ConfidentialTransferAccount` extension.
#[inline]
pub fn require_confidential_transfer_account(token_account: &AccountView<'_>) -> ProgramResult {
    let data = token_account
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = token_account_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    require_extension(tlv, EXT_CONFIDENTIAL_TRANSFER_ACCOUNT)
}

/// Require a mint to carry the `ScaledUiAmountConfig` extension.
#[inline]
pub fn require_scaled_ui_amount_config(mint: &AccountView<'_>) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    require_extension(tlv, EXT_SCALED_UI_AMOUNT_CONFIG)
}

/// Require a mint's `DefaultAccountState` byte to equal `expected`.
///
/// Values: `0` Uninitialized, `1` Initialized, `2` Frozen.
#[inline]
pub fn require_default_account_state(mint: &AccountView<'_>, expected: u8) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext =
        find_extension(tlv, EXT_DEFAULT_ACCOUNT_STATE).ok_or(ProgramError::InvalidAccountData)?;
    if ext.is_empty() {
        return Err(ProgramError::InvalidAccountData);
    }
    if ext[0] == expected {
        Ok(())
    } else {
        Err(ProgramError::InvalidAccountData)
    }
}

/// Require a mint's `InterestBearingConfig` rate-authority to equal `expected`.
///
/// Layout: `[rate_authority: 32][initialization_timestamp: 8][pre_update_average_rate: 2][last_update_timestamp: 8][current_rate: 2]`.
#[inline]
pub fn require_interest_bearing_authority(
    mint: &AccountView<'_>,
    expected: &Address,
) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext =
        find_extension(tlv, EXT_INTEREST_BEARING_CONFIG).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 32 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[..32], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

/// Require a mint's `TransferFeeConfig` transfer-fee-config authority to equal `expected`.
///
/// Layout prefix: `[transfer_fee_config_authority: 32][withdraw_withheld_authority: 32]...`.
#[inline]
pub fn require_transfer_fee_config_authority(
    mint: &AccountView<'_>,
    expected: &Address,
) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext =
        find_extension(tlv, EXT_TRANSFER_FEE_CONFIG).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 32 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[..32], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

/// Require a mint's `TransferFeeConfig` withdraw-withheld-authority to equal `expected`.
#[inline]
pub fn require_transfer_fee_withdraw_authority(
    mint: &AccountView<'_>,
    expected: &Address,
) -> ProgramResult {
    let data = mint
        .try_borrow()
        .map_err(|_| ProgramError::AccountBorrowFailed)?;
    let tlv = mint_tlv_region(&data).ok_or(ProgramError::InvalidAccountData)?;
    let ext =
        find_extension(tlv, EXT_TRANSFER_FEE_CONFIG).ok_or(ProgramError::InvalidAccountData)?;
    if ext.len() < 64 {
        return Err(ProgramError::InvalidAccountData);
    }
    if crate::address::keys_eq_bytes(&ext[32..64], expected.as_array()) {
        Ok(())
    } else {
        Err(ProgramError::IncorrectAuthority)
    }
}

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

    /// Build a mint buffer in the **real** Token-2022 on-chain layout:
    /// 82 bytes of Mint base, 83 bytes of zero padding, one AccountType
    /// byte, then a single TLV entry.
    ///
    /// A previous iteration of this helper elided the padding region
    /// and pushed the AccountType byte directly after the 82-byte
    /// base. The parser was wrong in exactly the complementary way, so
    /// the two wrongnesses aligned and the tests passed while the
    /// production code silently mis-read every real mainnet mint. This
    /// helper now matches `spl-token-2022`'s `validate_account_type`
    /// (which keys on `bytes[BASE_ACCOUNT_LENGTH]` where
    /// `BASE_ACCOUNT_LENGTH = 165`).
    fn mint_with_exts(exts: &[(u16, &[u8])]) -> alloc::vec::Vec<u8> {
        // 82 base + 83 padding = 165 bytes, then AccountType, then TLV.
        let mut v = alloc::vec![0u8; ACCOUNT_TYPE_OFFSET];
        v.push(ACCOUNT_TYPE_MINT);
        for (ty, payload) in exts {
            v.extend_from_slice(&ty.to_le_bytes());
            v.extend_from_slice(&(payload.len() as u16).to_le_bytes());
            v.extend_from_slice(payload);
        }
        debug_assert!(v.len() > TLV_OFFSET);
        v
    }

    /// Single-extension convenience wrapper. Delegates to [`mint_with_exts`].
    fn one_ext_mint(ext_type: u16, payload: &[u8]) -> alloc::vec::Vec<u8> {
        mint_with_exts(&[(ext_type, payload)])
    }

    /// Build a token-account buffer in the real layout: 165 base bytes
    /// then AccountType then TLV.
    fn token_account_with_exts(exts: &[(u16, &[u8])]) -> alloc::vec::Vec<u8> {
        let mut v = alloc::vec![0u8; BASE_TOKEN_LEN];
        v.push(ACCOUNT_TYPE_TOKEN);
        for (ty, payload) in exts {
            v.extend_from_slice(&ty.to_le_bytes());
            v.extend_from_slice(&(payload.len() as u16).to_le_bytes());
            v.extend_from_slice(payload);
        }
        v
    }

    // ---------------------------------------------------------------------

    #[test]
    fn offset_constants_match_authoritative_spec() {
        // Values anchored to the spl-token-2022 wire layout.
        assert_eq!(BASE_MINT_LEN, 82);
        assert_eq!(BASE_TOKEN_LEN, 165);
        assert_eq!(ACCOUNT_TYPE_OFFSET, 165);
        assert_eq!(TLV_OFFSET, 166);
        assert_eq!(MINT_EXTENSION_PADDING_START, 82);
        assert_eq!(MINT_EXTENSION_PADDING_END, 165);
        assert_eq!(TOKEN_MULTISIG_LEN, 355);
        assert_eq!(ACCOUNT_TYPE_MINT, 0x01);
        assert_eq!(ACCOUNT_TYPE_TOKEN, 0x02);
        assert_eq!(EXT_CONFIDENTIAL_MINT_BURN, 24);
        assert_eq!(EXT_SCALED_UI_AMOUNT_CONFIG, 25);
        assert_eq!(EXT_PAUSABLE_CONFIG, 26);
        assert_eq!(EXT_PAUSABLE_ACCOUNT, 27);
        assert_eq!(EXT_PERMISSIONED_BURN, 28);
    }

    #[test]
    fn real_layout_mint_tlv_region_starts_at_166() {
        // Build a real-layout mint whose only extension is NonTransferable,
        // placed at offset 166.
        let data = one_ext_mint(EXT_NON_TRANSFERABLE, &[]);
        let tlv = mint_tlv_region(&data).expect("extended mint must yield TLV region");
        // TLV must begin at offset 166, not at offset 83.
        assert_eq!(tlv.as_ptr() as usize - data.as_ptr() as usize, TLV_OFFSET);
        // First four bytes are type=9, length=0.
        assert_eq!(u16::from_le_bytes([tlv[0], tlv[1]]), EXT_NON_TRANSFERABLE);
        assert_eq!(u16::from_le_bytes([tlv[2], tlv[3]]), 0);
    }

    #[test]
    fn real_layout_mint_padding_is_not_treated_as_tlv() {
        // This is the exact shape that the previous implementation
        // mis-parsed: 82 base + 83 zero padding + AccountType=1 +
        // genuine TLV entry for TransferHook at offset 166. The old
        // parser read zero padding at offset 83 as type=0/length=0 and
        // short-circuited to None. The corrected parser must find the
        // real entry.
        let data = one_ext_mint(EXT_TRANSFER_HOOK, &[0u8; 64]);
        let tlv = mint_tlv_region(&data).expect("tlv region");
        assert!(find_extension(tlv, EXT_TRANSFER_HOOK).is_some());
    }

    // ---------------------------------------------------------------------

    #[test]
    fn find_extension_returns_payload_slice() {
        let data = one_ext_mint(EXT_NON_TRANSFERABLE, &[]);
        let tlv = mint_tlv_region(&data).unwrap();
        assert!(find_extension(tlv, EXT_NON_TRANSFERABLE).is_some());
    }

    #[test]
    fn find_extension_returns_none_when_absent() {
        let data = one_ext_mint(EXT_NON_TRANSFERABLE, &[]);
        let tlv = mint_tlv_region(&data).unwrap();
        assert!(find_extension(tlv, EXT_TRANSFER_HOOK).is_none());
    }

    #[test]
    fn find_extension_bails_on_malformed_length() {
        // Real-layout mint: 82 + 83 padding + type byte, then a
        // corrupt TLV header claiming 999 bytes of data that are not
        // present. Scanner must return None, not panic.
        let mut data = alloc::vec![0u8; ACCOUNT_TYPE_OFFSET];
        data.push(ACCOUNT_TYPE_MINT);
        data.extend_from_slice(&EXT_TRANSFER_HOOK.to_le_bytes());
        data.extend_from_slice(&999u16.to_le_bytes());
        let tlv = mint_tlv_region(&data).unwrap();
        assert!(find_extension(tlv, EXT_TRANSFER_HOOK).is_none());
        assert_eq!(
            forbid_extension(tlv, EXT_TRANSFER_HOOK),
            Err(ProgramError::InvalidAccountData),
            "a malformed forbidden extension must not look absent",
        );
    }

    #[test]
    fn allowlist_rejects_unknown_duplicate_and_truncated_entries() {
        let allowed = [EXT_METADATA_POINTER];
        let known = mint_with_exts(&[(EXT_METADATA_POINTER, &[0u8; 64])]);
        validate_extension_allowlist(mint_tlv_region(&known).unwrap(), &allowed).unwrap();

        let unknown = mint_with_exts(&[(MAX_KNOWN_EXTENSION_TYPE + 1, &[])]);
        assert_eq!(
            validate_extension_allowlist(mint_tlv_region(&unknown).unwrap(), &allowed),
            Err(ProgramError::InvalidAccountData),
        );

        let duplicate = mint_with_exts(&[
            (EXT_METADATA_POINTER, &[0u8; 64]),
            (EXT_METADATA_POINTER, &[0u8; 64]),
        ]);
        assert_eq!(
            validate_extension_allowlist(mint_tlv_region(&duplicate).unwrap(), &allowed),
            Err(ProgramError::InvalidAccountData),
        );

        let truncated = [EXT_METADATA_POINTER as u8, 0, 4, 0, 1];
        assert_eq!(
            validate_extension_allowlist(&truncated, &allowed),
            Err(ProgramError::InvalidAccountData),
        );
    }

    #[test]
    fn find_extension_finds_second_entry() {
        let data = mint_with_exts(&[
            (EXT_METADATA_POINTER, &[1u8; 64]),
            (EXT_PERMANENT_DELEGATE, &[2u8; 32]),
        ]);
        let tlv = mint_tlv_region(&data).unwrap();
        let perm = find_extension(tlv, EXT_PERMANENT_DELEGATE).unwrap();
        assert_eq!(perm, &[2u8; 32]);
    }

    #[test]
    fn extension_policy_requires_and_forbids_extensions() {
        let data = mint_with_exts(&[
            (EXT_CONFIDENTIAL_TRANSFER_MINT, &[0u8; 1]),
            (EXT_SCALED_UI_AMOUNT_CONFIG, &[0u8; 1]),
        ]);
        let tlv = mint_tlv_region(&data).unwrap();
        let policy = ExtensionPolicy::new(
            &[EXT_CONFIDENTIAL_TRANSFER_MINT, EXT_SCALED_UI_AMOUNT_CONFIG],
            &[EXT_TRANSFER_HOOK],
        );

        validate_extension_policy(tlv, &policy).unwrap();

        let rejected = ExtensionPolicy::new(
            &[EXT_CONFIDENTIAL_TRANSFER_MINT],
            &[EXT_SCALED_UI_AMOUNT_CONFIG],
        );
        assert_eq!(
            validate_extension_policy(tlv, &rejected),
            Err(ProgramError::InvalidAccountData)
        );
    }

    #[test]
    fn token_account_policy_sees_cpi_guard_and_confidential_account() {
        let data = token_account_with_exts(&[
            (EXT_CPI_GUARD, &[]),
            (EXT_CONFIDENTIAL_TRANSFER_ACCOUNT, &[0u8; 1]),
        ]);
        let tlv = token_account_tlv_region(&data).unwrap();

        validate_extension_policy(
            tlv,
            &ExtensionPolicy::new(&[EXT_CPI_GUARD, EXT_CONFIDENTIAL_TRANSFER_ACCOUNT], &[]),
        )
        .unwrap();
    }

    // ---------------------------------------------------------------------

    #[test]
    fn mint_tlv_region_rejects_short_account() {
        // Anything <= TLV_OFFSET (166) has no extension region.
        let data = alloc::vec![0u8; 40];
        assert!(mint_tlv_region(&data).is_none());
        let data = alloc::vec![0u8; TLV_OFFSET];
        assert!(mint_tlv_region(&data).is_none());
    }

    #[test]
    fn mint_tlv_region_rejects_wrong_account_kind() {
        // A 166-byte buffer whose AccountType byte reads as Token
        // (0x02) must not decode as a mint.
        let mut data = alloc::vec![0u8; ACCOUNT_TYPE_OFFSET];
        data.push(ACCOUNT_TYPE_TOKEN);
        data.push(0); // make length > TLV_OFFSET
        assert!(mint_tlv_region(&data).is_none());
    }

    #[test]
    fn tlv_regions_reject_multisig_collision_and_dirty_mint_padding() {
        let mut multisig = alloc::vec![0u8; TOKEN_MULTISIG_LEN];
        multisig[ACCOUNT_TYPE_OFFSET] = ACCOUNT_TYPE_MINT;
        assert!(mint_tlv_region(&multisig).is_none());
        multisig[ACCOUNT_TYPE_OFFSET] = ACCOUNT_TYPE_TOKEN;
        assert!(token_account_tlv_region(&multisig).is_none());

        let mut dirty_mint = one_ext_mint(EXT_NON_TRANSFERABLE, &[]);
        dirty_mint[MINT_EXTENSION_PADDING_START] = 1;
        assert!(mint_tlv_region(&dirty_mint).is_none());
    }

    #[test]
    fn mint_tlv_region_accepts_zero_kind_byte() {
        // Permissive init sequencing: a freshly-reallocated mint may
        // have AccountType still zero. The scanner tolerates it.
        let mut data = alloc::vec![0u8; ACCOUNT_TYPE_OFFSET];
        data.push(0u8);
        data.push(0); // length > TLV_OFFSET
        assert!(mint_tlv_region(&data).is_some());
    }

    #[test]
    fn token_account_tlv_region_accepts_zero_kind_byte() {
        let mut data = alloc::vec![0u8; BASE_TOKEN_LEN];
        data.push(0u8);
        data.push(0); // length > TLV_OFFSET
        assert!(token_account_tlv_region(&data).is_some());
    }

    #[test]
    fn token_account_tlv_region_rejects_mint_kind() {
        let mut data = alloc::vec![0u8; BASE_TOKEN_LEN];
        data.push(ACCOUNT_TYPE_MINT);
        data.push(0);
        assert!(token_account_tlv_region(&data).is_none());
    }

    #[test]
    fn token_account_tlv_region_returns_real_tlv() {
        let data = token_account_with_exts(&[(EXT_IMMUTABLE_OWNER, &[])]);
        let tlv = token_account_tlv_region(&data).unwrap();
        assert_eq!(tlv.as_ptr() as usize - data.as_ptr() as usize, TLV_OFFSET);
        assert!(find_extension(tlv, EXT_IMMUTABLE_OWNER).is_some());
    }
}