Skip to content

Add OP_PUT stack opcode - #136

Open
msinkec wants to merge 1 commit into
masterfrom
feat/op-put
Open

Add OP_PUT stack opcode#136
msinkec wants to merge 1 commit into
masterfrom
feat/op-put

Conversation

@msinkec

@msinkec msinkec commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Summary

  • add OP_PUT at 0xbb (187), replacing the previously undefined opcode slot
  • replace a stack item at a runtime-selected depth without changing the surrounding stack shape
  • cover top, middle, bottom, empty-value, invalid-depth, disassembly, and fuzzed serialized execution paths

Semantics

OP_PUT pops depth, pops value, then replaces the item at depth measured in the remaining stack:

[..., x_n, ..., x_1, x_0, value, n] OP_PUT
→
[..., value, ..., x_1, x_0]

The successful stack effect is always -2. depth uses the same minimally encoded four-byte script-number rules as OP_PICK and OP_ROLL; negative and out-of-range depths fail with ErrInvalidStackOperation.

Arkade language impact

The compiler lives in a separate repository, so its lowering is a follow-up after this VM opcode lands. These examples were compiled with the current compiler to measure the opportunity.

Simple mutable variable

contract Counter() {
    function spend(int amount) {
        let total = amount;
        total = total + 1;
        require(total > amount);
    }
}

Today the replacement tail is:

OP_1 OP_ROLL OP_DROP

With OP_PUT it becomes:

OP_0 OP_PUT

The complete covenant drops from 18 to 17 assembly tokens. The small saving is the important base case: every scalar assignment becomes constant-size and no longer needs special stack restoration.

Deep assignment

contract DeepAssignment() {
    function spend(int amount) {
        int[16] balances = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        balances[15] = amount;
        require(balances[15] == amount);
    }
}

The current assignment emits 48 tokens: the value expression, OP_16 OP_ROLL OP_DROP, 15 OP_SWAPs, 14 OP_TOALTSTACKs, and 14 OP_FROMALTSTACKs. With OP_PUT, the same assignment is four tokens:

OP_16 OP_PICK OP_15 OP_PUT

That reduces the full covenant from 88 to 44 assembly tokens. The saving grows linearly with assignment depth while OP_PUT remains constant-size.

Runtime-indexed array assignment will additionally retain the compiler's 0 <= index < array.length checks so an index cannot overwrite an adjacent binding.

Validation

  • make test
  • golangci-lint run --new-from-rev=HEAD from pkg/arkade

Summary by CodeRabbit

  • New Features

    • Added the OP_PUT script operation.
    • Scripts can now replace a value at a specified stack position without changing the stack depth.
    • Supports indexed updates for both top-of-stack and deeper stack items.
  • Bug Fixes

    • Invalid indices, missing stack items, and insufficient stack depth now return appropriate script errors instead of performing an update.

@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 06108e80-479e-4a02-bbda-3d4cda958363

📥 Commits

Reviewing files that changed from the base of the PR and between 66fd93c and e7acb0c.

📒 Files selected for processing (5)
  • pkg/arkade/opcode.go
  • pkg/arkade/opcode_fuzz_test.go
  • pkg/arkade/opcode_test.go
  • pkg/arkade/stack.go
  • pkg/arkade/stack_test.go

Walkthrough

The change adds OP_PUT at opcode value 0xbb. The handler replaces an indexed stack item through the new stack.PutN method. Unit tests and fuzz cases cover valid replacement and stack errors.

Changes

OP_PUT stack replacement

Layer / File(s) Summary
Indexed stack replacement
pkg/arkade/stack.go, pkg/arkade/stack_test.go
PutN replaces an indexed stack item without changing stack depth. Tests cover top-level replacement, depth-two replacement, and insufficient stack depth.
OP_PUT execution and validation
pkg/arkade/opcode.go, pkg/arkade/opcode_test.go, pkg/arkade/opcode_fuzz_test.go
OP_PUT replaces OP_UNKNOWN187 at value 0xbb and invokes opcodePut. Tests cover valid indices, empty values, invalid indices, missing targets, underflow, and stack invariants. Fuzz generation supplies the required stack items.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Mergeability Score: ⚪ Minimal · up to e7acb

This PR adds the OP_PUT opcode with focused stack behavior and validation coverage; no actionable merge-blocking risk remains after normal checks and review.

Suggested reviewers: louisinger, chris-ricketts, kukks

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely identifies the main change: adding the OP_PUT stack opcode.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/op-put

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@msinkec
msinkec marked this pull request as ready for review August 13, 2026 21:56

@arkana-ai-bot arkana-ai-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arkana review — OP_PUT (0xbb)

Verdict: no blocking issues. One minor observation on fuzz coverage depth.


stack.go —

(new function, after line 364)

The bounds check delegates to , which enforces and returns for negatives and out-of-range depths. The subsequent write indexes the same slot, so after a successful peek the write is guaranteed in-bounds. No overflow risk: is , is at least 32 bits, and the peek gate ensures the subtraction cannot underderflow. Implementation is consistent with / (no unnecessary deep copy — assignment replaces the slot pointer, consistent with the rest of the codebase).

opcode.go —

(new function, after PickN ~line 1175)

Pop order is correct: (depth ) → (value) → . When is called the two sentinel items have already been removed, so depth is measured against the remaining stack exactly as specified. The doc comment examples (, ) verify against the test vectors.

Tests

Unit vectors cover:

  • depth 0 (, bottom of remaining stack is a 2-item stack)
  • depth 1 ()
  • depth 2 ()
  • empty value (, replacement)
  • negative index →
  • out-of-range (stack too shallow for requested depth) →
  • missing target (both n and value consumed, nothing left) →
  • complete underflow →

The invariant ( on success, on error) is correct: at most two items are consumed before any failure path is reached.

Fuzz coverage — minor observation

— hardcodes as the depth item (), so the corpus always exercises . The explicit unit vectors cover deeper and invalid depths adequately, but the fuzzer won't find crashes/panics at depth >0 from unexpected serialised data. Worth extending — e.g. derive the depth byte from the same way uses — but not a blocker given the explicit coverage.

Cross-repo impact

Grepped all SDK clones (ts-sdk, go-sdk, rust-sdk, dotnet-sdk, compiler) for / — no consumers found. The slot was previously , so assigning a live handler is a non-breaking change for any code that treated it as invalid. Compiler integration is correctly deferred.

Summary

Semantics, bounds checking, error propagation, and test coverage are all correct. The single observation above (fuzz depth) is low-priority. LGTM to merge once CI is green.

@arkana-ai-bot arkana-ai-bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arkana review — OP_PUT (0xbb)

Verdict: no blocking issues. One minor observation on fuzz coverage depth.


stack.go — PutN

pkg/arkade/stack.go (new function, after line 364)

The bounds check delegates to PeekByteArray(n), which enforces 0 <= n < sz and returns ErrInvalidStackOperation for negatives and out-of-range depths. The subsequent slot write (s.stk[len(s.stk)-int(n)-1] = so) addresses the same index, so after a successful peek the write is guaranteed in-bounds. No overflow risk: n is int32, int is at least 32 bits, and the peek gate ensures the subtraction cannot underflow. The function is consistent with PickN/RollN — no unnecessary deep copy, it replaces the slot pointer, which is the established pattern throughout the stack implementation.

opcode.go — opcodePut

pkg/arkade/opcode.go (new function, after opcodePickN ~line 1175)

Pop order is correct: PopInt (depth n) → PopByteArray (value) → PutN(n, value). By the time PutN is called the two sentinel items have already been removed, so depth n is measured against the remaining stack exactly as the specified semantics require. The doc comment examples (n=0, n=2) verify against the unit test vectors — all consistent.

Tests

Unit vectors in pkg/arkade/opcode_test.go cover:

  • depth 0 (put_0)
  • depth 1 (put_1)
  • depth 2 (put_2)
  • empty (nil) value replacement (put_empty)
  • negative index → ErrInvalidStackOperation
  • out-of-range (stack too shallow for requested depth) → ErrInvalidStackOperation
  • missing target (both n and value consumed, nothing left) → ErrInvalidStackOperation
  • complete underflow → ErrInvalidStackOperation

The checkProperties invariant (len(afterStack) == len(beforeStack)-2 on success; beforeStack-2 <= len(afterStack) <= beforeStack on error) is correct: at most two items are consumed before any failure path is reached.

Stack-level tests in pkg/arkade/stack_test.go cover Put0, Put2, and the too-little-stack case. Good.

Fuzz coverage — minor observation

pkg/arkade/opcode_fuzz_test.goputCaseBuilder hardcodes nil as the depth item (c.stackPushes = [][]byte{..., nil}), so the fuzz corpus always exercises n=0. Explicit unit vectors cover deeper and invalid depths adequately, but the fuzzer will not explore crashes or panics at depth > 0 from unexpected serialised data. Worth extending — for example, derive the depth byte from saltedBytes(data, 0x72) the way indexCaseBuilder uses fuzzIndexSource.IndexSeed — but not a blocker given the explicit unit coverage.

Cross-repo impact

Grepped all SDK clones (ts-sdk, go-sdk, rust-sdk, dotnet-sdk, compiler) for 0xbb and OP_UNKNOWN187 — no consumers found. The slot was previously opcodeInvalid, so promoting it to a live handler is non-breaking for any code that treated it as invalid. Compiler integration is correctly deferred as a follow-up.

Summary

Semantics, bounds checking, error propagation, and test coverage are all correct. The single observation above (fuzz depth) is low-priority. LGTM to merge once CI is green.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants