diff --git a/README.md b/README.md index bf6de03..092d6cf 100644 --- a/README.md +++ b/README.md @@ -14,4 +14,5 @@ Kaspa Improvement Proposals (KIPs) describe standard proposals for the Kaspa net | [10](kip-0010.md) | Consensus, Script Engine | New Transaction Opcodes for Enhanced Script Functionality | Maxim Biryukov, Ori Newman | Active | | [13](kip-0013.md) | Consensus | Transient Storage Handling | Michael Sutton, coderofstuff | Active | | [14](kip-0014.md) | Consensus | The Crescendo Hardfork | Michael Sutton | Active | -| [15](kip-0015.md) | Consensus | Canonical Transaction Ordering and Sequencing Commitments | Mike Zak, Ro Ma | Active | \ No newline at end of file +| [15](kip-0015.md) | Consensus | Canonical Transaction Ordering and Sequencing Commitments | Mike Zak, Ro Ma | Active | +| [18](kip-0018.md) | Consensus, Script Engine | Integration of OP_SIMPLICITY Opcode for Simplicity Processing | Anton Yemelyanov | Draft | diff --git a/kip-0018.md b/kip-0018.md new file mode 100644 index 0000000..405fd0a --- /dev/null +++ b/kip-0018.md @@ -0,0 +1,130 @@ +``` + KIP: 18 + Layer: Consensus, Script Engine + Title: Integration of OP_SIMPLICITY Opcode for Simplicity Processing + Authors: Anton Yemelyanov + Status: Draft +``` + +## Abstract + +This proposal introduces OP_SIMPLICITY, a new opcode to the Kaspa scripting language, enabling the execution of Simplicity programs as an alternative or complement to traditional stack-based scripts. Simplicity is a low-level, functional, combinator-based programming language developed by Blockstream, designed for blockchain smart contracts with a focus on formal verification, safety, and expressiveness. This KIP builds on the covenant capabilities introduced in KIP-10 and KIP-17 by allowing more complex and verifiable logic without indefinitely expanding the opcode set. It also includes a section on integrating the rust-simplicity crate into the Rusty Kaspa script engine for a reference implementation. + +## Specification + +### 1. New Opcode: OP_SIMPLICITY + +- **Opcode Value**: 0xd0 (tentative, to be confirmed to avoid conflicts with existing opcodes). +- **Behavior**: + - Pops two items from the stack: + - Top stack item: a 32-byte Simplicity program commitment (e.g., CMR/commitment hash) committed to by the output script. + - Next stack item: a byte string representing the serialized Simplicity program in redemption form, including any witness data required for execution. + - The redemption program is decoded. Its commitment root/hash is computed and must match the committed 32-byte program commitment. If the commitment check fails, execution fails. + - The program is then executed using the Simplicity virtual machine (Bit Machine). + - Input to the Simplicity program is derived from the transaction context, including: + - Current transaction fields (version, locktime, inputs, outputs, etc., accessible via jets or built-in combinators). + - Stack items remaining after popping the commitment and redemption program (e.g., for custom inputs like signatures or hashes). + - The program must output a unit value (success) or fail, determining the script's validity. + - Execution fails if: + - The program is malformed or exceeds resource limits (e.g., computation bounds to prevent denial-of-service). + - Type checking fails (Simplicity enforces strong typing). + - Runtime errors occur (e.g., division by zero in jets). + - Resource limits: Execution is bounded by a maximum number of Bit Machine operations (e.g., 10^6 bits processed) to ensure halting and prevent infinite computation, aligning with Simplicity's design, which avoids loops and recursion. +- **Serialization**: + - The output (locking) script commits to the program by including its 32-byte commitment value (e.g., CMR/commitment hash). + - The spending transaction provides the redemption-form program bytes (including witness data) as stack data. + - The redemption-form program is provided as a byte string following the canonical encoding specified in the Simplicity specification. + +### 2. Integration with Existing Script + +- OP_SIMPLICITY can be used within standard Kaspa scripts, allowing hybrid scripts where traditional opcodes prepare inputs (e.g., via introspection from KIP-17) before invoking Simplicity. +- For pure Simplicity scripts, the scriptPubKey could be simplified to ` OP_SIMPLICITY`, where `` is the 32-byte commitment (e.g., CMR/commitment hash) of the Simplicity program. The spending transaction provides the redemption program bytes (and witness data) on the stack. + +### 3. Activation + +The features introduced in this KIP are activated based on DAA score: + +1. Prior to activation: + - OP_SIMPLICITY is treated as invalid. +2. After activation: + - OP_SIMPLICITY becomes active, enabling Simplicity execution. + +## Motivation + +Kaspa's scripting language, inspired by Bitcoin Script, provides basic stack-based operations for transaction validation but is limited in expressiveness and difficult to formally verify. As Kaspa evolves with features like covenants (KIP-10, KIP-17), the need for more advanced smart contract capabilities grows. Adding new opcodes for each desired feature risks opcode bloat, increased attack surface, and consensus bugs. + +Simplicity addresses these issues as a verifiable alternative: + +### Advantages of Simplicity over Bitcoin-based Script Engine + +- **Formal Verification**: Simplicity programs can be formally proven correct using tools like Coq, reducing bugs in smart contracts. Bitcoin Script lacks this, leading to vulnerabilities like those in historical opcodes (e.g., OP_LSHIFT exploits). +- **Expressiveness without Turing Completeness**: Using combinators and jets (optimized primitives like hashes, signatures), Simplicity enables complex logic (e.g., covenants, state machines) without loops or recursion, avoiding the halting problem and gas metering complexities in languages like Solidity. +- **Strong Typing and Static Analysis**: Enforces types at commitment time, preventing runtime errors common in stack-based scripts. +- **Modularity and Reusability**: Programs are built from combinators, allowing higher-level languages (e.g., SimplicityHL and Simfony) to compile to Simplicity, unlike the ad-hoc nature of Bitcoin Script. +- **Security**: Merkleized programs (via commitment roots) hide unused branches, enhancing privacy and reducing on-chain data. Jets provide efficient implementations of common operations, outperforming interpreted opcodes. +- **Deployment Experience**: Proven on Blockstream's Liquid network (Elements sidechain), where it enables advanced features like covenants and delegated signing without expanding opcodes. + +In contrast, Bitcoin/Kaspa Script is stack-based, untyped, and limited to simple predicates, making complex contracts cumbersome and error-prone. + +### Benefits of Simplicity vs. Adding New Opcodes to the Existing Script Engine + +- **Avoids Opcode Bloat**: Instead of introducing dozens of new opcodes (e.g., for advanced math, string ops as in KIP-17), Simplicity encapsulates arbitrary logic in a single opcode, keeping the core engine simple. +- **Reduced Consensus Risk**: Simplicity's core is minimal (combinators + Bit Machine), with jets verifiable against specs. Adding opcodes increases the surface for bugs or exploits. +- **Ecosystem Growth**: Enables (currently limited) compilation from high-level languages, attracting developers without requiring them to learn low-level opcodes. + +Overall, integrating Simplicity positions Kaspa as a scalable, secure platform for DeFi, NFTs, and layer-2 bridges, while maintaining its high-throughput blockDAG advantages. + +## Use Cases + +- **Advanced Covenants**: Beyond KIP-17, Simplicity enables recursive covenants, vaults with timelocks, or stateful tokens with verifiable transitions. +- **DeFi Primitives**: Oracles, lending protocols, or AMMs with formal proofs of solvency. +- **NFTs and Tokens**: Verifiable ownership transfers with custom rules (e.g., royalties enforced on-chain). +- **Cross-Chain Bridges**: Trust-minimized bridges using Simplicity's verification for zero-knowledge proofs or state proofs. +- **Privacy Enhancements**: Merkleized scripts for confidential transactions. +- **vProg vaults**: Using Simplicity can provide vProgs with a more flexible way to control KAS locking mechanisms. + +## Additional Research + +Kaspa can offer a mechanism for registration of persistent or UTXO reference-based Simplicity programs. Such a registry is outside of the scope of this KIP. The creation of such a registry would allow Kaspa scripts to invoke a previously registered program via a reference, reducing the UTXO state size and bandwidth consumption due to program reuse. For example, the [Stwo ZK proof verifier example](https://github.com/starkware-bitcoin/stark-symphony) and similar ZK verifiers (for different ZK VMs) can be introduced into Kaspa dynamically, without a hard forks. + +## Backward Compatibility + +This proposal requires a hard fork, as it introduces new opcodes to the scripting language. Older software will require an update to support these new features. Existing scripts and addresses remain valid, but cannot use the new functionality without being updated. + +## Reference Implementation + +There is currently no reference implementation available. It will be considered after the initial feedback from the Kaspa research team. Simplicity is available as a Rust crate maintained by the Blockstream Research team and the basic integration steps are described below. + +### Integrating rust-simplicity into Rusty Kaspa Script Engine + +The rust-simplicity crate (https://github.com/BlockstreamResearch/rust-simplicity) provides a Rust implementation of Simplicity, including program construction, type inference, encoding, and execution via the Bit Machine. It vendors libsimplicity (C library) for consensus-critical operations. + +To integrate: + +1. **Add Dependency**: In `Cargo.toml`, add `simplicity-lang = "0.7"` (library crate name: `simplicity`). See the upstream API docs for available modules/types. ([`simplicity` crate docs](https://docs.rs/simplicity-lang/0.7.0/simplicity/)) +2. **Opcode Handler (Redeem / Execute)**: In the script engine (e.g., `consensus/core/src/script`), add a handler for OP_SIMPLICITY: + - Pop the program bytes from the stack. + - **Decode** the canonical on-chain encoding into a `simplicity::RedeemNode` using the `simplicity::decode` module. + - **Validate shape**: `RedeemNode` is the “on-chain” node type; unused branches must already be pruned and any remaining witness/disconnect nodes must be present on-chain (i.e. in the bytes you decoded). + - **Execute** via the Simplicity Bit Machine (`simplicity::BitMachine`) and treat success/failure of evaluation as the opcode result (Simplicity programs used for validation should effectively return unit-or-fail). +3. **Program Lifecycle (Commit vs Redeem)**: + - **Commit-time**: when constructing programs off-chain (e.g. wallets / tooling), build with `simplicity::ConstructNode` inside a `simplicity::types::Context` and finish inference with `finalize_types()`. This produces a committed program (`simplicity::CommitNode`) suitable for computing commitment identifiers (e.g. CMR) and for address construction. + - **Redeem-time**: on-chain, the engine should only accept the canonical redeem form (`simplicity::RedeemNode`) and execute that. +4. **Resource Bounding**: Use Simplicity’s built-in static bounds to enforce consensus limits before running: + - `simplicity::Cost` for CPU cost accounting. + - `simplicity::NodeBounds` for Bit Machine resource bounds (memory/cells, etc.). +5. **Encoding / Decoding (Interop & Tests)**: + - Use `simplicity::write_to_vec` together with the encoding APIs (e.g. `encode_without_witness` for committed programs) to produce deterministic byte encodings for fixtures and cross-implementation tests. + - Round-trip test vectors through `simplicity::decode` and `simplicity::encode`, and validate expected failure modes using `simplicity::DecodeError` / `simplicity::Error`. + +This integration leverages Rusty Kaspa's Rust codebase for seamless addition, enabling Simplicity execution in validation routines. + +## References + +1. KIP-17: [kip-0017.md](https://github.com/someone235/kips/blob/kip17/kip-0017.md) +2. rust-simplicity Repository: [https://github.com/BlockstreamResearch/rust-simplicity](https://github.com/BlockstreamResearch/rust-simplicity) +3. Simplicity Home Page: [https://simplicity-lang.org/](https://simplicity-lang.org/) +4. Advantages of Simplicity: [What Is Simplicity?](https://thebitcoinmanual.com/articles/simplicity/), [Simplicity: Going Beyond Miniscript](https://btctranscripts.com/advancing-bitcoin/2023/simplicity-going-beyond-miniscript) +5. Liquid Network Integration: [What can Simplicity Bring to the Liquid Network?](https://blog.bitfinex.com/education/what-can-simplicity-bring-to-the-liquid-network/) +6. [Video discussing Simplicity, state management tradeoffs, comparing UTXO and account state systems such as Ethereum](https://x.com/tftc21/status/1953101198610911725?s=46&t=VNTo-WpiS4pr9Xc1PPpy0Q) +7. ZK integration: [Stwo (STARK StarkNet) verifier written in SimplicityHL](https://github.com/starkware-bitcoin/stark-symphony)