@typesol/cli 0.42.0 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +350 -0
  2. package/NOTICE +71 -0
  3. package/README.md +35 -18
  4. package/SECURITY.md +32 -5
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.js +5 -5
  7. package/dist/cli.js +196 -72
  8. package/dist/compiler/analyze.js +447 -12
  9. package/dist/compiler/diagnostics.d.ts +1 -0
  10. package/dist/compiler/diagnostics.js +13 -0
  11. package/dist/compiler/emit/alias.d.ts +45 -1
  12. package/dist/compiler/emit/alias.js +143 -6
  13. package/dist/compiler/emit/base.d.ts +28 -1
  14. package/dist/compiler/emit/base.js +77 -9
  15. package/dist/compiler/emit/borsh.js +11 -5
  16. package/dist/compiler/emit/calls.d.ts +80 -0
  17. package/dist/compiler/emit/calls.js +612 -54
  18. package/dist/compiler/emit/cpi-core.d.ts +23 -4
  19. package/dist/compiler/emit/cpi-core.js +261 -12
  20. package/dist/compiler/emit/cpi.js +8 -2
  21. package/dist/compiler/emit/create.js +3 -0
  22. package/dist/compiler/emit/expressions.js +44 -8
  23. package/dist/compiler/emit/function.js +10 -0
  24. package/dist/compiler/emit/program.js +30 -1
  25. package/dist/compiler/emit/rbtree.d.ts +7 -0
  26. package/dist/compiler/emit/rbtree.js +142 -0
  27. package/dist/compiler/emit/shared.d.ts +25 -0
  28. package/dist/compiler/emit/shared.js +45 -4
  29. package/dist/compiler/emit/statements.d.ts +27 -1
  30. package/dist/compiler/emit/statements.js +305 -23
  31. package/dist/compiler/emit/storage.d.ts +25 -2
  32. package/dist/compiler/emit/storage.js +116 -64
  33. package/dist/compiler/emit/token.js +2 -2
  34. package/dist/compiler/emit/views.d.ts +60 -0
  35. package/dist/compiler/emit/views.js +523 -0
  36. package/dist/compiler/idl.js +2 -1
  37. package/dist/compiler/index.d.ts +15 -1
  38. package/dist/compiler/index.js +40 -3
  39. package/dist/compiler/model.d.ts +65 -4
  40. package/dist/compiler/model.js +14 -0
  41. package/dist/compiler/toolchain.d.ts +56 -1
  42. package/dist/compiler/toolchain.js +246 -12
  43. package/dist/testing-stake.d.ts +2 -1
  44. package/dist/testing-stake.js +2 -1
  45. package/dist/testing.js +6 -4
  46. package/dist/tools/clientgen.d.ts +15 -0
  47. package/dist/tools/clientgen.js +173 -7
  48. package/dist/tools/cpigen.d.ts +0 -15
  49. package/dist/tools/cpigen.js +19 -8
  50. package/dist/tools/doctor.d.ts +17 -2
  51. package/dist/tools/doctor.js +64 -4
  52. package/dist/tools/portgen.js +43 -18
  53. package/dist/workspace.d.ts +20 -0
  54. package/dist/workspace.js +173 -6
  55. package/docs/ai.md +10 -5
  56. package/docs/architecture.md +10 -3
  57. package/docs/audit.md +63 -17
  58. package/docs/case-study-escrow.md +1 -1
  59. package/docs/case-study-phoenix.md +226 -0
  60. package/docs/case-study-raydium-amm.md +3 -3
  61. package/docs/case-study-spl-stake-pool.md +5 -5
  62. package/docs/cli.md +17 -8
  63. package/docs/client.md +11 -3
  64. package/docs/errors.md +1 -1
  65. package/docs/language.md +148 -12
  66. package/docs/mainnet.md +21 -10
  67. package/docs/migrate-from-anchor.md +3 -1
  68. package/docs/runtime.md +12 -2
  69. package/docs/security-model.md +38 -6
  70. package/docs/stability.md +42 -4
  71. package/docs/testing.md +25 -0
  72. package/docs/troubleshooting.md +17 -2
  73. package/lib/typesol.d.ts +221 -4
  74. package/llms-full.txt +336 -65
  75. package/llms.txt +2 -2
  76. package/package.json +4 -2
  77. package/runtime/typesol_rt.h +429 -13
  78. package/test/programs/LICENSE-Apache-2.0.txt +201 -0
package/llms.txt CHANGED
@@ -23,8 +23,8 @@ The rules and the whole reference in one file: https://typesol.com/llms-full.txt
23
23
  ## Tools
24
24
 
25
25
  - `npx @typesol/cli init my-app`: a project with a program, a LiteSVM test, AGENTS.md / CLAUDE.md and the MCP server configured
26
- - `npx typesol check --json`: errors with hints; `npx typesol mcp`: check, IDL and docs as MCP tools
26
+ - `npx --no-install typesol check --json`: errors with hints; `npx --no-install typesol mcp`: check, IDL and docs as MCP tools
27
27
 
28
28
  ## Optional
29
29
 
30
- - [Case studies](https://typesol.com/docs/case-study-marginfi/): mainnet programs (Marginfi v2, SPL Stake Pool, Raydium AMM v4, CLMM, CP-Swap, Jito) ported and checked against their binaries
30
+ - [Case studies](https://typesol.com/docs/case-study-marginfi/): mainnet programs (Marginfi v2, Phoenix v1, SPL Stake Pool, Raydium AMM v4, CLMM, CP-Swap, Jito) ported and checked against their binaries
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typesol/cli",
3
- "version": "0.42.0",
3
+ "version": "0.44.0",
4
4
  "description": "Compile a TypeScript-syntax language directly to Solana SBF programs.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -52,6 +52,8 @@
52
52
  "assets",
53
53
  "!assets/readme",
54
54
  "LICENSE",
55
+ "NOTICE",
56
+ "test/programs/LICENSE-Apache-2.0.txt",
55
57
  "README.md",
56
58
  "CHANGELOG.md",
57
59
  "SECURITY.md",
@@ -65,7 +67,7 @@
65
67
  "test": "vitest run",
66
68
  "typesol": "node dist/cli.js",
67
69
  "smoke": "node scripts/smoke.ts",
68
- "fuzz": "FUZZ_RUNS=2000 FUZZ_STEPS=600 FUZZ_VERBOSE=1 vitest run test/verification/fuzz-arith.test.ts test/verification/fuzz-state.test.ts test/verification/fuzz-layout.test.ts test/verification/differential.test.ts showcase/test/fuzz-jito.test.ts showcase/test/fuzz-marginfi.test.ts --silent=false",
70
+ "fuzz": "FUZZ_RUNS=2000 FUZZ_STEPS=600 FUZZ_VERBOSE=1 vitest run test/verification/fuzz-arith.test.ts test/verification/fuzz-state.test.ts test/verification/fuzz-layout.test.ts test/verification/differential.test.ts showcase/test/fuzz-jito.test.ts showcase/test/fuzz-marginfi.test.ts showcase/test/phoenix-fuzz.test.ts --silent=false",
69
71
  "build:twins": "cd test/anchor-twins && cargo-build-sbf",
70
72
  "prepack": "npm run build",
71
73
  "fetch:programs": "bash scripts/fetch-programs.sh",
@@ -68,13 +68,21 @@
68
68
  #define TS_ERR_NO_RETURN 5114
69
69
  #define TS_ERR_ACCOUNT_MISSING 5115
70
70
 
71
+ #ifdef TS_PANIC_ABORT
72
+ extern __attribute__((noreturn)) void abort(void); /* declared again with the other syscalls below */
73
+ #endif
71
74
  /* Every failure logs through this one sol_log_ call: each syscall call site costs a 16-byte relocation in the binary. */
72
75
  static __attribute__((noinline)) uint64_t ts_fail(uint64_t code, const char *msg, uint64_t len) {
73
76
  sol_log_(msg, len);
74
77
  #ifdef TS_PANIC_ON_OVERFLOW
75
78
  /* PANIC_ON_OVERFLOW: arithmetic fails as a Rust `checked_*().unwrap()` does, with a panic (ProgramFailedToComplete). */
79
+ #ifdef TS_PANIC_ABORT
80
+ /* PANIC_STYLE "solana-1.14": a panic ends in the abort syscall ("SBF program panicked"), as that panic handler's. */
81
+ if (code == TS_ERR_OVERFLOW || code == TS_ERR_DIV_ZERO) abort();
82
+ #else
76
83
  if (code == TS_ERR_OVERFLOW || code == TS_ERR_DIV_ZERO) sol_panic_("", 0, 0, 0);
77
84
  #endif
85
+ #endif
78
86
  #ifdef TS_CUSTOM_ZERO
79
87
  /* An error with code 0 (a native program's first error) is returned as solana_program returns
80
88
  * ProgramError::Custom(0): the built-in CUSTOM_ZERO, since 0 itself means success. */
@@ -88,6 +96,24 @@ static __attribute__((noinline, unused)) uint64_t ts_fail_code(uint32_t code, co
88
96
  return ts_fail(code ? code : TS_ERR_OVERFLOW, msg, sol_strlen(msg));
89
97
  }
90
98
 
99
+ /* A failure that logs nothing (`const ERROR_LOG_PREFIX = null` / `PROGRAM_ERROR_LOG_PREFIX = null`): the code ts_fail
100
+ * would return, as a native program returns an error its own checks already explained (or never explain). */
101
+ static inline __attribute__((always_inline, unused)) uint64_t ts_fail_quiet(uint64_t code) {
102
+ #ifdef TS_PANIC_ON_OVERFLOW
103
+ #ifdef TS_PANIC_ABORT
104
+ if (code == TS_ERR_OVERFLOW || code == TS_ERR_DIV_ZERO) abort();
105
+ #else
106
+ if (code == TS_ERR_OVERFLOW || code == TS_ERR_DIV_ZERO) sol_panic_("", 0, 0, 0);
107
+ #endif
108
+ #endif
109
+ #ifdef TS_CUSTOM_ZERO
110
+ if (code == 0) return (uint64_t)1 << 32;
111
+ #endif
112
+ return code;
113
+ }
114
+ /* ts_fail_code's quiet form: a code computed at run time, 0 failing as an overflow. */
115
+ static inline __attribute__((always_inline, unused)) uint64_t ts_fail_code_quiet(uint32_t code) { return ts_fail_quiet(code ? code : TS_ERR_OVERFLOW); }
116
+
91
117
  #define TS_TRY(expr) \
92
118
  do { \
93
119
  uint64_t ts_r_ = (expr); \
@@ -557,7 +583,16 @@ typedef struct {
557
583
  #else
558
584
  uint64_t loaded_mut; /* bit i: ka[i] loaded with loadAccountMut (zeroed by the entrypoint of a program that uses it) */
559
585
  #endif
586
+ #ifdef TS_OWNER_CACHE
587
+ const TsAccount *owned; /* the account the last owner check found this program's (see ts_owned) */
588
+ #endif
560
589
  } TsParams;
590
+ /* Every CPI and every owner write of the program forgets the cached owner check (an owner may have changed). */
591
+ #ifdef TS_OWNER_CACHE
592
+ #define TS_OWNER_FORGET(p) ((p)->owned = NULL)
593
+ #else
594
+ #define TS_OWNER_FORGET(p) ((void)0)
595
+ #endif
561
596
 
562
597
  #ifdef TS_SCRATCH_ON_HEAP
563
598
  static uint64_t ts_infos_reserve(TsParams *params, uint64_t n);
@@ -599,6 +634,11 @@ static inline __attribute__((always_inline)) void ts_deserialize(const uint8_t *
599
634
  }
600
635
  TsAccount *a = (TsAccount *)input;
601
636
  params->ka[i] = a;
637
+ #ifdef TS_RECORD_ENTRY_LEN
638
+ /* resizeAccount on a remaining account: its size now, in the record's padding, as solana_program 1.14's
639
+ entrypoint keeps original_data_len there for AccountInfo::realloc (ts_entry_len). */
640
+ *(ts_u32_unaligned *)a->padding = (uint32_t)a->data_len;
641
+ #endif
602
642
  input = (const uint8_t *)(((uint64_t)(input + 88 + a->data_len + MAX_PERMITTED_DATA_INCREASE) + 7) & ~(uint64_t)7) + 8;
603
643
  }
604
644
  params->data_len = *(const uint64_t *)input;
@@ -634,6 +674,7 @@ static inline __attribute__((always_inline)) uint64_t ts_invoke(TsParams *params
634
674
  TS_INFOS_RESERVE(params, ix->account_len);
635
675
  SolAccountInfo *infos = params->infos;
636
676
  for (uint64_t i = 0; i < ix->account_len; i++) ts_info((const TsAccount *)((const uint8_t *)ix->accounts[i].pubkey - 8), &infos[i]);
677
+ TS_OWNER_FORGET(params);
637
678
  return sol_invoke_signed(ix, infos, ix->account_len, signers, nsigners);
638
679
  }
639
680
 
@@ -724,6 +765,19 @@ static inline void ts_copy(void *dst, const void *src, uint64_t n) {
724
765
  if (dst != src) ts_memcpy(dst, src, n);
725
766
  }
726
767
 
768
+ static inline __attribute__((always_inline)) bool ts_key_eq(const SolPubkey *a, const SolPubkey *b);
769
+ #ifdef TS_OWNER_CACHE
770
+ /* Is account `a` this program's? The views of native accounts (loadRaw, loadRawAt, rawArrayAt, rbTreeAt) check it each
771
+ time they are made, often of one account again and again (helpers that each make their own view, views in loops).
772
+ The last account found this program's is remembered until a CPI or an owner write (TS_OWNER_FORGET): until then
773
+ its owner cannot have changed, so the same record passes with one pointer compare instead of 32 bytes. */
774
+ static inline __attribute__((always_inline)) bool ts_owned(TsParams *params, const TsAccount *a) {
775
+ if (params->owned == a) return true;
776
+ if (!ts_key_eq(&a->owner, params->program_id)) return false;
777
+ params->owned = a;
778
+ return true;
779
+ }
780
+ #endif
727
781
  static inline __attribute__((always_inline)) bool ts_key_eq(const SolPubkey *a, const SolPubkey *b) {
728
782
  return ts_ld64(a->x) == ts_ld64(b->x) && ts_ld64(a->x + 8) == ts_ld64(b->x + 8) && ts_ld64(a->x + 16) == ts_ld64(b->x + 16) &&
729
783
  ts_ld64(a->x + 24) == ts_ld64(b->x + 24);
@@ -1370,6 +1424,11 @@ static inline uint64_t ts_resize(TsParams *params, TsAccount *payer, TsAccount *
1370
1424
  return SUCCESS;
1371
1425
  }
1372
1426
 
1427
+ #ifdef TS_RECORD_ENTRY_LEN
1428
+ /* A remaining account's data length when the instruction started (recorded by ts_deserialize). */
1429
+ static inline __attribute__((always_inline)) uint64_t ts_entry_len(const TsAccount *a) { return *(const ts_u32_unaligned *)a->padding; }
1430
+ #endif
1431
+
1373
1432
  /* resizeAccount(): the data length only (AccountInfo::resize), new bytes zeroed; no rent moves. */
1374
1433
  static inline uint64_t ts_resize_raw(TsAccount *acct, uint64_t new_len, uint64_t entry_len) {
1375
1434
  if (new_len > entry_len + MAX_PERMITTED_DATA_INCREASE)
@@ -1446,6 +1505,7 @@ static inline uint64_t ts_cpi_named(TsParams *params, const TsAccount *program,
1446
1505
  TS_INFOS_RESERVE(params, n);
1447
1506
  SolAccountInfo *infos = params->infos;
1448
1507
  for (uint64_t i = 0; i < n; i++) ts_info(accounts[i], &infos[i]);
1508
+ TS_OWNER_FORGET(params);
1449
1509
  return sol_invoke_signed(&ix, infos, n, &signer, nseeds > 0 ? 1 : 0);
1450
1510
  }
1451
1511
 
@@ -1775,6 +1835,8 @@ extern __attribute__((noreturn)) void abort(void);
1775
1835
 
1776
1836
  /*
1777
1837
  * ---- BigVec (SPL's big_vec) ------------------------------------------------
1838
+ * Follows SPL Stake Pool's big_vec.rs (solana-program/stake-pool, program/src/big_vec.rs), licensed under the Apache
1839
+ * License, Version 2.0; see NOTICE.
1778
1840
  * The memmove syscall, for BigVec::retain's block moves as the Rust does: it costs max(10, n / 250) CU, where the
1779
1841
  * word loop of ts_memmove costs about n / 2 (a 1.4 MB validator list moves in a few thousand CU, not hundreds of
1780
1842
  * thousands). Overlapping ranges are allowed. The "no SDK byte loops" rule is about the SDK's C loops, not this.
@@ -1790,6 +1852,22 @@ static inline __attribute__((always_inline)) void ts_memcpy_bulk(void *dst, cons
1790
1852
  if (n >= TS_MEMCPY_SYSCALL_MIN) sol_memcpy_(dst, src, n);
1791
1853
  else ts_memcpy(dst, src, n);
1792
1854
  }
1855
+ /* The memset syscall, for zeroing large regions (a local FixedVec's free slots, so bytes past its length read as zero
1856
+ * wherever its whole layout is copied: account data, events): max(10, n / 250) CU plus the call, against n / 8 stores
1857
+ * for ts_memzero's words (constant sizes unroll), so regions under 128 bytes keep the stores. */
1858
+ extern void sol_memset_(void *dst, uint8_t c, uint64_t n);
1859
+ #define TS_MEMSET_SYSCALL_MIN 128
1860
+ static inline __attribute__((always_inline, unused)) void ts_memzero_bulk(void *dst, uint64_t n) {
1861
+ if (n >= TS_MEMSET_SYSCALL_MIN) sol_memset_(dst, 0, n);
1862
+ else ts_memzero(dst, n);
1863
+ }
1864
+ /* A copy of a size known when compiling (a whole local FixedVec): the syscall from TS_MEMCPY_CONST_MIN bytes, where
1865
+ * the unrolled words (a load and a store per 8 bytes) cost more than the call. */
1866
+ #define TS_MEMCPY_CONST_MIN 128
1867
+ static inline __attribute__((always_inline, unused)) void ts_memcpy_const(void *dst, const void *src, uint64_t n) {
1868
+ if (n >= TS_MEMCPY_CONST_MIN) sol_memcpy_(dst, src, n);
1869
+ else ts_memcpy(dst, src, n);
1870
+ }
1793
1871
  /* A BigVec's room: a BigVec struct is only ever a loadRaw view, which sits at a TsAccount's data, right after its
1794
1872
  * data_len (see TsAccount); the elements that fit in the account past the struct (its fixed fields and the length). */
1795
1873
  static inline __attribute__((always_inline)) uint64_t ts_bigvec_cap(const uint8_t *data, uint64_t fixed, uint64_t elem) {
@@ -1804,6 +1882,339 @@ static inline __attribute__((always_inline)) uint8_t *ts_opaque_ptr(uint8_t *p)
1804
1882
  return p;
1805
1883
  }
1806
1884
 
1885
+ /*
1886
+ * ---- A Rust panic as solana-program up to 1.17 reports it ----------------------------------------------------
1887
+ * The program's panic handler logs the PanicInfo ("panicked at '<msg>', <file>:<line>:<col>", Rust before 1.73) and
1888
+ * the runtime's abort ends the program ("SBF program panicked", ProgramFailedToComplete). The built-in
1889
+ * RedBlackTree panics this way, where lib-sokoban 0.3 does, with sokoban's own messages and source locations.
1890
+ */
1891
+ static __attribute__((noinline, noreturn, unused)) void ts_rust_panic(const char *msg, uint64_t msg_len, const char *loc, uint64_t loc_len) {
1892
+ char line[160];
1893
+ uint64_t n = 0;
1894
+ const char *head = "panicked at '";
1895
+ for (uint64_t i = 0; head[i]; i++) line[n++] = head[i];
1896
+ for (uint64_t i = 0; i < msg_len && n < sizeof(line) - 4 - loc_len; i++) line[n++] = msg[i];
1897
+ line[n++] = '\'';
1898
+ line[n++] = ',';
1899
+ line[n++] = ' ';
1900
+ for (uint64_t i = 0; i < loc_len && n < sizeof(line); i++) line[n++] = loc[i];
1901
+ sol_log_(line, n);
1902
+ abort();
1903
+ }
1904
+ /* `msg` then the decimal digits of `v` (Rust's `panic!("Buffer is full, size {}", self.size)`). */
1905
+ static __attribute__((noinline, noreturn, unused)) void ts_rust_panic_u64(const char *msg, uint64_t msg_len, uint64_t v, const char *loc, uint64_t loc_len) {
1906
+ char text[112];
1907
+ uint64_t n = 0;
1908
+ for (; n < msg_len && n < 88; n++) text[n] = msg[n];
1909
+ char digits[20];
1910
+ uint64_t d = 0;
1911
+ do {
1912
+ digits[d++] = (char)('0' + v % 10);
1913
+ v /= 10;
1914
+ } while (v);
1915
+ while (d) text[n++] = digits[--d];
1916
+ ts_rust_panic(text, n, loc, loc_len);
1917
+ }
1918
+ #define TS_RUST_PANIC(msg, loc) ts_rust_panic((msg), sizeof(msg) - 1, (loc), sizeof(loc) - 1)
1919
+
1920
+ /*
1921
+ * ---- RedBlackTree (lib-sokoban 0.3's RedBlackTree<K, V, N>, byte for byte) ------------------------------------
1922
+ * Ported from lib-sokoban 0.3.0 (https://github.com/jarry-xiao/sokoban), Copyright (c) 2022 Jarry Xiao, used under
1923
+ * the MIT License (the crate is "MIT OR Apache-2.0"); the licence text is in NOTICE.
1924
+ * At `base`: root u32 (0 = SENTINEL), padding [u32; 3], then the NodeAllocator: size u64, bump_index u32,
1925
+ * free_list_head u32, then N nodes. Node i (1-based) is at base + 32 + (i - 1) * stride: registers [u32; 4] =
1926
+ * [left, right, parent, color (0 black, 1 red)], then the key, then the value. These functions are sokoban's own,
1927
+ * statement for statement (red_black_tree.rs, node_allocator.rs), so every register, size, bump index and free-list
1928
+ * write is the one sokoban makes: the free list is LIFO through register 0 and ends at the bump index (not at 0);
1929
+ * a node taken from the bump index has no register written, one taken from the free list only register 0; removing a
1930
+ * node clears its registers and leaves its key and value bytes. `stride` is a constant at every call (the per-tree
1931
+ * functions the compiler writes), so a node's address is one multiply or shift. Every node index read is checked
1932
+ * against the capacity (as Rust's `nodes[i - 1]` is): a damaged tree panics instead of reading outside the account.
1933
+ */
1934
+ typedef struct {
1935
+ uint8_t *base;
1936
+ uint64_t cap;
1937
+ } TsRbt;
1938
+ /* A node handed out by min / max / nodeAt / iteration: its index (0: none) and its first byte. */
1939
+ typedef struct {
1940
+ uint8_t *node;
1941
+ uint32_t index;
1942
+ } TsRbtEntry;
1943
+ #define TS_RBT_ROOT(b) (*(ts_u32_unaligned *)(b))
1944
+ #define TS_RBT_SIZE(b) (*(ts_u64_unaligned *)((b) + 16))
1945
+ #define TS_RBT_BUMP(b) (*(ts_u32_unaligned *)((b) + 24))
1946
+ #define TS_RBT_FREE(b) (*(ts_u32_unaligned *)((b) + 28))
1947
+ #define TS_RBT_LEFT 0
1948
+ #define TS_RBT_RIGHT 1
1949
+ #define TS_RBT_PARENT 2
1950
+ #define TS_RBT_COLOR 3
1951
+
1952
+ /* Rust's `&self.nodes[(i - 1) as usize]` out of range: index 0 underflows (overflow checks on), past N is out of bounds. */
1953
+ static __attribute__((noinline, noreturn, unused)) void ts_rbt_bad_index(uint64_t cap, uint32_t i) {
1954
+ if (i == 0) TS_RUST_PANIC("attempt to subtract with overflow", "src/node_allocator.rs:255:21");
1955
+ char text[96];
1956
+ uint64_t n = 0;
1957
+ const char *a = "index out of bounds: the len is ";
1958
+ for (uint64_t k = 0; a[k]; k++) text[n++] = a[k];
1959
+ char digits[20];
1960
+ uint64_t d = 0, v = cap;
1961
+ do {
1962
+ digits[d++] = (char)('0' + v % 10);
1963
+ v /= 10;
1964
+ } while (v);
1965
+ while (d) text[n++] = digits[--d];
1966
+ const char *b = " but the index is ";
1967
+ for (uint64_t k = 0; b[k]; k++) text[n++] = b[k];
1968
+ ts_rust_panic_u64(text, n, (uint64_t)i - 1, "src/node_allocator.rs:255:10", 28);
1969
+ }
1970
+ static inline __attribute__((always_inline)) uint8_t *ts_rbt_node(const TsRbt *t, uint64_t stride, uint32_t i) {
1971
+ if ((uint64_t)i - 1 >= t->cap) ts_rbt_bad_index(t->cap, i);
1972
+ return t->base + 32 + ((uint64_t)i - 1) * stride;
1973
+ }
1974
+ /* allocator.get_register / set_register / connect: SENTINEL reads 0 and ignores writes. */
1975
+ /* Node i's first byte, for an index already checked against the capacity (a walk checks each node once, when it
1976
+ steps onto it). */
1977
+ static inline __attribute__((always_inline)) uint8_t *ts_rbt_node_checked(const TsRbt *t, uint64_t stride, uint32_t i) {
1978
+ return t->base + 32 + ((uint64_t)i - 1) * stride;
1979
+ }
1980
+ static inline __attribute__((always_inline)) uint32_t ts_rbt_reg(const TsRbt *t, uint64_t stride, uint32_t i, uint32_t r) {
1981
+ return i ? ((ts_u32_unaligned *)ts_rbt_node(t, stride, i))[r] : 0;
1982
+ }
1983
+ static inline __attribute__((always_inline)) void ts_rbt_set(const TsRbt *t, uint64_t stride, uint32_t i, uint32_t r, uint32_t v) {
1984
+ if (i) ((ts_u32_unaligned *)ts_rbt_node(t, stride, i))[r] = v;
1985
+ }
1986
+ /* _connect(parent, child, dir): parent's register `dir` takes the child (0 too), the child's parent register the parent. */
1987
+ static inline __attribute__((always_inline)) void ts_rbt_connect(const TsRbt *t, uint64_t stride, uint32_t parent, uint32_t child, uint32_t dir) {
1988
+ ts_rbt_set(t, stride, parent, dir, child);
1989
+ ts_rbt_set(t, stride, child, TS_RBT_PARENT, parent);
1990
+ }
1991
+ static inline __attribute__((always_inline)) bool ts_rbt_is_red(const TsRbt *t, uint64_t stride, uint32_t i) {
1992
+ return ts_rbt_reg(t, stride, i, TS_RBT_COLOR) == 1;
1993
+ }
1994
+ static inline __attribute__((always_inline)) bool ts_rbt_is_black(const TsRbt *t, uint64_t stride, uint32_t i) {
1995
+ return ts_rbt_reg(t, stride, i, TS_RBT_COLOR) == 0;
1996
+ }
1997
+ static inline __attribute__((always_inline)) uint32_t ts_rbt_child_dir(const TsRbt *t, uint64_t stride, uint32_t parent, uint32_t child) {
1998
+ uint32_t left = ts_rbt_reg(t, stride, parent, TS_RBT_LEFT);
1999
+ uint32_t right = ts_rbt_reg(t, stride, parent, TS_RBT_RIGHT);
2000
+ if (child == left) return TS_RBT_LEFT;
2001
+ if (child == right) return TS_RBT_RIGHT;
2002
+ TS_RUST_PANIC("Nodes are not connected", "src/red_black_tree.rs:429:13");
2003
+ }
2004
+ static inline __attribute__((always_inline)) void ts_rbt_rotate(const TsRbt *t, uint64_t stride, uint32_t parent, uint32_t dir) {
2005
+ uint32_t grandparent = ts_rbt_reg(t, stride, parent, TS_RBT_PARENT);
2006
+ uint32_t sibling = ts_rbt_reg(t, stride, parent, 1 - dir);
2007
+ if (sibling == 0) return;
2008
+ uint32_t child = ts_rbt_reg(t, stride, sibling, dir);
2009
+ ts_rbt_connect(t, stride, sibling, parent, dir);
2010
+ ts_rbt_connect(t, stride, parent, child, 1 - dir);
2011
+ if (grandparent != 0) {
2012
+ ts_rbt_connect(t, stride, grandparent, sibling, ts_rbt_child_dir(t, stride, grandparent, parent));
2013
+ } else {
2014
+ ts_rbt_set(t, stride, sibling, TS_RBT_PARENT, 0);
2015
+ TS_RBT_ROOT(t->base) = sibling;
2016
+ }
2017
+ }
2018
+ /* NodeAllocator::initialize: size, bump index and free list all 0, else "Cannot reinitialize NodeAllocator". */
2019
+ static inline void ts_rbt_initialize(const TsRbt *t) {
2020
+ uint8_t *b = t->base;
2021
+ if (TS_RBT_SIZE(b) == 0 && TS_RBT_BUMP(b) == 0 && TS_RBT_FREE(b) == 0) {
2022
+ TS_RBT_BUMP(b) = 1;
2023
+ TS_RBT_FREE(b) = 1;
2024
+ } else {
2025
+ TS_RUST_PANIC("Cannot reinitialize NodeAllocator", "src/node_allocator.rs:249:13");
2026
+ }
2027
+ }
2028
+ /* NodeAllocator::add_node: the free list's head, or the bump index when the list is used up; then the key and value. */
2029
+ static inline __attribute__((always_inline)) uint32_t ts_rbt_add_node(const TsRbt *t, uint64_t stride, const void *key, uint64_t ksz,
2030
+ const void *value, uint64_t vsz) {
2031
+ uint8_t *b = t->base;
2032
+ uint32_t i = TS_RBT_FREE(b);
2033
+ if (i == TS_RBT_BUMP(b)) {
2034
+ if ((uint64_t)TS_RBT_BUMP(b) == t->cap + 1) ts_rust_panic_u64("Buffer is full, size ", 21, TS_RBT_SIZE(b), "src/node_allocator.rs:269:17", 28);
2035
+ TS_RBT_BUMP(b) += 1;
2036
+ TS_RBT_FREE(b) = TS_RBT_BUMP(b);
2037
+ } else {
2038
+ uint8_t *n = ts_rbt_node(t, stride, i);
2039
+ TS_RBT_FREE(b) = ((ts_u32_unaligned *)n)[0];
2040
+ ((ts_u32_unaligned *)n)[0] = 0;
2041
+ }
2042
+ uint8_t *n = ts_rbt_node(t, stride, i);
2043
+ ts_memcpy(n + 16, key, ksz);
2044
+ ts_memcpy(n + 16 + ksz, value, vsz);
2045
+ TS_RBT_SIZE(b) += 1;
2046
+ return i;
2047
+ }
2048
+ static inline __attribute__((always_inline)) void ts_rbt_fix_insert(const TsRbt *t, uint64_t stride, uint32_t node) {
2049
+ while (ts_rbt_is_red(t, stride, ts_rbt_reg(t, stride, node, TS_RBT_PARENT))) {
2050
+ uint32_t parent = ts_rbt_reg(t, stride, node, TS_RBT_PARENT);
2051
+ uint32_t grandparent = ts_rbt_reg(t, stride, parent, TS_RBT_PARENT);
2052
+ if (grandparent == 0) {
2053
+ if (TS_RBT_ROOT(t->base) != parent) TS_RUST_PANIC("assertion failed: self.is_root(parent)", "src/red_black_tree.rs:503:17");
2054
+ break;
2055
+ }
2056
+ uint32_t dir = ts_rbt_child_dir(t, stride, grandparent, parent);
2057
+ uint32_t uncle = ts_rbt_reg(t, stride, grandparent, 1 - dir);
2058
+ if (ts_rbt_is_red(t, stride, uncle)) {
2059
+ ts_rbt_set(t, stride, uncle, TS_RBT_COLOR, 0);
2060
+ ts_rbt_set(t, stride, parent, TS_RBT_COLOR, 0);
2061
+ ts_rbt_set(t, stride, grandparent, TS_RBT_COLOR, 1);
2062
+ node = grandparent;
2063
+ } else {
2064
+ if (ts_rbt_child_dir(t, stride, parent, node) == 1 - dir) {
2065
+ ts_rbt_rotate(t, stride, parent, dir);
2066
+ node = parent;
2067
+ }
2068
+ parent = ts_rbt_reg(t, stride, node, TS_RBT_PARENT);
2069
+ grandparent = ts_rbt_reg(t, stride, parent, TS_RBT_PARENT);
2070
+ ts_rbt_set(t, stride, parent, TS_RBT_COLOR, 0);
2071
+ ts_rbt_set(t, stride, grandparent, TS_RBT_COLOR, 1);
2072
+ ts_rbt_rotate(t, stride, grandparent, 1 - dir);
2073
+ }
2074
+ }
2075
+ ts_rbt_set(t, stride, TS_RBT_ROOT(t->base), TS_RBT_COLOR, 0);
2076
+ }
2077
+ /* _insert's new leaf under `parent` (on side `dir`): red, linked, then _fix_insert unless the parent is the root. */
2078
+ static inline __attribute__((always_inline)) void ts_rbt_link_leaf(const TsRbt *t, uint64_t stride, uint32_t parent, uint32_t node, uint32_t dir) {
2079
+ ts_rbt_set(t, stride, node, TS_RBT_COLOR, 1);
2080
+ ts_rbt_connect(t, stride, parent, node, dir);
2081
+ if (ts_rbt_reg(t, stride, parent, TS_RBT_PARENT) != 0) ts_rbt_fix_insert(t, stride, node);
2082
+ }
2083
+ static inline __attribute__((always_inline)) uint32_t ts_rbt_find_min(const TsRbt *t, uint64_t stride, uint32_t node) {
2084
+ while (ts_rbt_reg(t, stride, node, TS_RBT_LEFT) != 0) node = ts_rbt_reg(t, stride, node, TS_RBT_LEFT);
2085
+ return node;
2086
+ }
2087
+ static inline __attribute__((always_inline)) uint32_t ts_rbt_find_max(const TsRbt *t, uint64_t stride, uint32_t node) {
2088
+ while (ts_rbt_reg(t, stride, node, TS_RBT_RIGHT) != 0) node = ts_rbt_reg(t, stride, node, TS_RBT_RIGHT);
2089
+ return node;
2090
+ }
2091
+ static inline __attribute__((always_inline)) void ts_rbt_transplant(const TsRbt *t, uint64_t stride, uint32_t target, uint32_t source) {
2092
+ uint32_t parent = ts_rbt_reg(t, stride, target, TS_RBT_PARENT);
2093
+ if (parent == 0) {
2094
+ TS_RBT_ROOT(t->base) = source;
2095
+ ts_rbt_set(t, stride, source, TS_RBT_PARENT, 0);
2096
+ return;
2097
+ }
2098
+ ts_rbt_connect(t, stride, parent, source, ts_rbt_child_dir(t, stride, parent, target));
2099
+ }
2100
+ static inline __attribute__((always_inline)) void ts_rbt_fix_remove(const TsRbt *t, uint64_t stride, uint32_t node, bool has_pd, uint32_t parent, uint32_t dir) {
2101
+ /* `parent_and_dir.unwrap_or({ … })` evaluates its argument first: a pure read here (node is SENTINEL whenever
2102
+ parent_and_dir is Some), kept for the panic it could raise on a damaged tree. */
2103
+ uint32_t p0 = ts_rbt_reg(t, stride, node, TS_RBT_PARENT);
2104
+ uint32_t d0 = ts_rbt_child_dir(t, stride, p0, node);
2105
+ if (!has_pd) {
2106
+ parent = p0;
2107
+ dir = d0;
2108
+ }
2109
+ for (;;) {
2110
+ uint32_t sibling = ts_rbt_reg(t, stride, parent, 1 - dir);
2111
+ if (ts_rbt_is_red(t, stride, sibling)) {
2112
+ ts_rbt_set(t, stride, sibling, TS_RBT_COLOR, 0);
2113
+ ts_rbt_set(t, stride, parent, TS_RBT_COLOR, 1);
2114
+ ts_rbt_rotate(t, stride, parent, dir);
2115
+ sibling = ts_rbt_reg(t, stride, parent, 1 - dir);
2116
+ }
2117
+ if (ts_rbt_is_black(t, stride, ts_rbt_reg(t, stride, sibling, TS_RBT_LEFT)) &&
2118
+ ts_rbt_is_black(t, stride, ts_rbt_reg(t, stride, sibling, TS_RBT_RIGHT))) {
2119
+ ts_rbt_set(t, stride, sibling, TS_RBT_COLOR, 1);
2120
+ node = parent;
2121
+ } else {
2122
+ if (ts_rbt_is_black(t, stride, ts_rbt_reg(t, stride, sibling, 1 - dir))) {
2123
+ ts_rbt_set(t, stride, ts_rbt_reg(t, stride, sibling, dir), TS_RBT_COLOR, 0);
2124
+ ts_rbt_set(t, stride, sibling, TS_RBT_COLOR, 1);
2125
+ ts_rbt_rotate(t, stride, sibling, 1 - dir);
2126
+ sibling = ts_rbt_reg(t, stride, parent, 1 - dir);
2127
+ }
2128
+ ts_rbt_set(t, stride, sibling, TS_RBT_COLOR, ts_rbt_reg(t, stride, parent, TS_RBT_COLOR));
2129
+ ts_rbt_set(t, stride, parent, TS_RBT_COLOR, 0);
2130
+ ts_rbt_set(t, stride, ts_rbt_reg(t, stride, sibling, 1 - dir), TS_RBT_COLOR, 0);
2131
+ ts_rbt_rotate(t, stride, parent, dir);
2132
+ node = TS_RBT_ROOT(t->base);
2133
+ }
2134
+ if (TS_RBT_ROOT(t->base) == node || ts_rbt_is_red(t, stride, node)) break;
2135
+ parent = ts_rbt_reg(t, stride, node, TS_RBT_PARENT);
2136
+ dir = ts_rbt_child_dir(t, stride, parent, node);
2137
+ }
2138
+ ts_rbt_set(t, stride, node, TS_RBT_COLOR, 0);
2139
+ }
2140
+ /* _remove_tree_node: unlink node `n` (a leaf, one child transplanted, or replaced by its predecessor), free it, rebalance. */
2141
+ static inline __attribute__((always_inline)) void ts_rbt_remove_node(const TsRbt *t, uint64_t stride, uint32_t n) {
2142
+ uint8_t *b = t->base;
2143
+ bool black = ts_rbt_is_black(t, stride, n);
2144
+ uint32_t left = ts_rbt_reg(t, stride, n, TS_RBT_LEFT);
2145
+ uint32_t right = ts_rbt_reg(t, stride, n, TS_RBT_RIGHT);
2146
+ uint32_t pivot;
2147
+ bool has_pd = false;
2148
+ uint32_t pd_parent = 0, pd_dir = 0;
2149
+ if (ts_rbt_reg(t, stride, n, TS_RBT_LEFT) == 0 && ts_rbt_reg(t, stride, n, TS_RBT_RIGHT) == 0) {
2150
+ if (TS_RBT_ROOT(b) != n) {
2151
+ uint32_t parent = ts_rbt_reg(t, stride, n, TS_RBT_PARENT);
2152
+ uint32_t dir = ts_rbt_child_dir(t, stride, parent, n);
2153
+ ts_rbt_connect(t, stride, parent, 0, dir);
2154
+ pivot = 0;
2155
+ has_pd = true;
2156
+ pd_parent = parent;
2157
+ pd_dir = dir;
2158
+ } else {
2159
+ TS_RBT_ROOT(b) = 0;
2160
+ pivot = 0;
2161
+ }
2162
+ } else if (left == 0) {
2163
+ ts_rbt_transplant(t, stride, n, right);
2164
+ pivot = right;
2165
+ } else if (right == 0) {
2166
+ ts_rbt_transplant(t, stride, n, left);
2167
+ pivot = left;
2168
+ } else {
2169
+ uint32_t max_left = ts_rbt_find_max(t, stride, left);
2170
+ uint32_t max_left_parent = ts_rbt_reg(t, stride, max_left, TS_RBT_PARENT);
2171
+ uint32_t max_left_child = ts_rbt_reg(t, stride, max_left, TS_RBT_LEFT);
2172
+ black = ts_rbt_is_black(t, stride, max_left);
2173
+ if (ts_rbt_reg(t, stride, max_left, TS_RBT_PARENT) != n) {
2174
+ ts_rbt_transplant(t, stride, max_left, max_left_child);
2175
+ ts_rbt_connect(t, stride, max_left, ts_rbt_reg(t, stride, n, TS_RBT_LEFT), TS_RBT_LEFT);
2176
+ if (max_left_child == 0) {
2177
+ has_pd = true;
2178
+ pd_parent = max_left_parent;
2179
+ pd_dir = TS_RBT_RIGHT;
2180
+ }
2181
+ } else if (max_left_child == 0) {
2182
+ if (ts_rbt_reg(t, stride, max_left, TS_RBT_LEFT) != 0 || ts_rbt_reg(t, stride, max_left, TS_RBT_RIGHT) != 0)
2183
+ TS_RUST_PANIC("assertion failed: self.is_leaf(max_left)", "src/red_black_tree.rs:598:17");
2184
+ has_pd = true;
2185
+ pd_parent = max_left;
2186
+ pd_dir = TS_RBT_LEFT;
2187
+ }
2188
+ ts_rbt_transplant(t, stride, n, max_left);
2189
+ ts_rbt_connect(t, stride, max_left, ts_rbt_reg(t, stride, n, TS_RBT_RIGHT), TS_RBT_RIGHT);
2190
+ ts_rbt_set(t, stride, max_left, TS_RBT_COLOR, ts_rbt_reg(t, stride, n, TS_RBT_COLOR));
2191
+ pivot = max_left_child;
2192
+ }
2193
+ /* _remove_allocator_node: registers cleared, then onto the free list (key and value bytes stay). */
2194
+ ts_rbt_set(t, stride, n, TS_RBT_PARENT, 0);
2195
+ ts_rbt_set(t, stride, n, TS_RBT_COLOR, 0);
2196
+ ts_rbt_set(t, stride, n, TS_RBT_LEFT, 0);
2197
+ ts_rbt_set(t, stride, n, TS_RBT_RIGHT, 0);
2198
+ if (n != 0) {
2199
+ ts_rbt_set(t, stride, n, 0, TS_RBT_FREE(b));
2200
+ TS_RBT_FREE(b) = n;
2201
+ if (TS_RBT_SIZE(b) == 0) TS_RUST_PANIC("attempt to subtract with overflow", "src/node_allocator.rs:291:9");
2202
+ TS_RBT_SIZE(b) -= 1;
2203
+ }
2204
+ if (black) {
2205
+ if (TS_RBT_ROOT(b) == pivot)
2206
+ ts_rbt_set(t, stride, pivot, TS_RBT_COLOR, 0);
2207
+ else
2208
+ ts_rbt_fix_remove(t, stride, pivot, has_pd, pd_parent, pd_dir);
2209
+ }
2210
+ }
2211
+ /* For iteration: an in-order walk keeps at most the tree's height of nodes, under 64 for any red-black tree a u32
2212
+ index can address; a deeper (damaged) tree stops with a panic. */
2213
+ #define TS_RBT_STACK 64
2214
+ static __attribute__((noinline, noreturn, unused)) void ts_rbt_too_deep(void) {
2215
+ TS_RUST_PANIC("TypeSOL: RedBlackTree deeper than a red-black tree can be", "rbtree");
2216
+ }
2217
+
1807
2218
  /*
1808
2219
  * Did an Ed25519 precompile instruction in this transaction verify `message` signed by `signer`?
1809
2220
  * Reads the Instructions sysvar (data: u16 count, u16 offsets[count], then per instruction
@@ -1868,7 +2279,8 @@ static inline uint64_t ts_alloc(uint64_t n, uint8_t **out) {
1868
2279
  uint64_t *next = (uint64_t *)HEAP_START_ADDRESS;
1869
2280
  uint64_t at = *next == 0 ? 8 : *next;
1870
2281
  at = (at + 7) & ~(uint64_t)7;
1871
- if (at + n > TS_HEAP_LENGTH) TS_FAIL(TS_ERR_HEAP, "TypeSOL: out of heap");
2282
+ /* Not `at + n > …`: a size computed from untrusted lengths could wrap that sum. */
2283
+ if (at > TS_HEAP_LENGTH || n > TS_HEAP_LENGTH - at) TS_FAIL(TS_ERR_HEAP, "TypeSOL: out of heap");
1872
2284
  *next = at + n;
1873
2285
  *out = (uint8_t *)(HEAP_START_ADDRESS + at);
1874
2286
  return SUCCESS;
@@ -1989,7 +2401,7 @@ static uint64_t ts_str_append_parts(TS_Str *s, const TS_Str *parts, uint64_t n)
1989
2401
  uint64_t *next = (uint64_t *)HEAP_START_ADDRESS;
1990
2402
  uint64_t add = 0;
1991
2403
  for (uint64_t i = 0; i < n; i++) add += parts[i].len;
1992
- if (*next != 0 && s->len > 0 && (uint64_t)(s->ptr + s->len) == HEAP_START_ADDRESS + *next && *next + add <= TS_HEAP_LENGTH) {
2404
+ if (*next != 0 && s->len > 0 && (uint64_t)(s->ptr + s->len) == HEAP_START_ADDRESS + *next && add <= TS_HEAP_LENGTH - *next) {
1993
2405
  for (uint64_t i = 0; i < n; i++) {
1994
2406
  ts_memcpy((uint8_t *)s->ptr + s->len, parts[i].ptr, parts[i].len);
1995
2407
  s->len += parts[i].len;
@@ -2009,22 +2421,26 @@ static uint64_t ts_str_append_parts(TS_Str *s, const TS_Str *parts, uint64_t n)
2009
2421
  return SUCCESS;
2010
2422
  }
2011
2423
 
2012
- /* `s += b` (and `a + b`, with `s` a copy of `a`): the one-piece case of ts_str_append_parts. */
2013
- static uint64_t ts_str_append(TS_Str *s, TS_Str b) {
2424
+ /* `s += b` (and `a + b`, with `s` a copy of `a`): the one-piece case of ts_str_append_parts. The piece comes as its
2425
+ pointer and length: `s += s` passes `*s` itself, and the SBF target hands a C struct argument over as a pointer to
2426
+ the caller's object without copying it (see passedByPointer in the compiler), so a struct `b` would change with `*s`. */
2427
+ static uint64_t ts_str_append_n(TS_Str *s, const uint8_t *bp, uint64_t bl) {
2014
2428
  uint64_t *next = (uint64_t *)HEAP_START_ADDRESS;
2015
- if (*next != 0 && s->len > 0 && (uint64_t)(s->ptr + s->len) == HEAP_START_ADDRESS + *next && *next + b.len <= TS_HEAP_LENGTH) {
2016
- ts_memcpy((uint8_t *)s->ptr + s->len, b.ptr, b.len);
2017
- *next += b.len;
2018
- s->len += b.len;
2429
+ if (*next != 0 && s->len > 0 && (uint64_t)(s->ptr + s->len) == HEAP_START_ADDRESS + *next && bl <= TS_HEAP_LENGTH - *next) {
2430
+ ts_memcpy((uint8_t *)s->ptr + s->len, bp, bl);
2431
+ *next += bl;
2432
+ s->len += bl;
2019
2433
  return SUCCESS;
2020
2434
  }
2021
2435
  uint8_t *p;
2022
- TS_TRY(ts_alloc(s->len + b.len, &p));
2436
+ TS_TRY(ts_alloc(s->len + bl, &p));
2023
2437
  ts_memcpy(p, s->ptr, s->len);
2024
- ts_memcpy(p + s->len, b.ptr, b.len);
2025
- *s = ts_str(p, s->len + b.len);
2438
+ ts_memcpy(p + s->len, bp, bl);
2439
+ *s = ts_str(p, s->len + bl);
2026
2440
  return SUCCESS;
2027
2441
  }
2442
+ /* Always inlined, so `b` is read here, into scalars, before anything writes `*s`. */
2443
+ static inline __attribute__((always_inline)) uint64_t ts_str_append(TS_Str *s, TS_Str b) { return ts_str_append_n(s, b.ptr, b.len); }
2028
2444
 
2029
2445
  /* The pieces of a template literal, joined with one heap allocation and one copy each. */
2030
2446
  static uint64_t ts_str_join(const TS_Str *parts, uint64_t n, TS_Str *out) {
@@ -2318,8 +2734,8 @@ static const SolPubkey TS_STAKE_HISTORY_ID = {{6,167,213,23,25,53,132,208,254,23
2318
2734
  /* StakeHistory: u64 count, then (epoch, effective, activating, deactivating) u64 entries, newest first. The entry for
2319
2735
  `epoch` (field 1..3 of it), or 0 when it is not listed; `found` says which. */
2320
2736
  static inline uint64_t ts_stake_history(const TsAccount *a, uint64_t epoch, int field, bool *found) {
2321
- uint64_t n = ts_read_le(a->data, 8);
2322
- if (n > (a->data_len - 8) / 32) n = (a->data_len - 8) / 32;
2737
+ uint64_t n = a->data_len < 8 ? 0 : ts_read_le(a->data, 8);
2738
+ if (n > 0 && n > (a->data_len - 8) / 32) n = (a->data_len - 8) / 32;
2323
2739
  for (uint64_t i = 0; i < n; i++) {
2324
2740
  const uint8_t *e = a->data + 8 + 32 * i;
2325
2741
  if (ts_read_le(e, 8) == epoch) {