Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

kip-10 #18

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 198 additions & 0 deletions kip-0010.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
```
  KIP: 10
  Layer: Consensus, Script Engine
  Title: New Transaction Opcodes for Enhanced Script Functionality
  Authors: Maxim Biryukov (@biryukovmaxim),
Ori Newman <[email protected]>
  Status: proposed, implemented in the rust codebase and activated in testnet 11
```

## Abstract

This KIP introduces transaction introspection opcodes and enhanced arithmetic capabilities to the Kaspa scripting language. The primary additions include opcodes for querying transaction metadata, input/output properties, and support for 8-byte integer arithmetic operations. These enhancements enable more sophisticated script conditions and use cases, particularly in support of mutual transactions as discussed in KIP-9.
## Motivation

Following the introduction of the extended mass formula in KIP-9 to mitigate state bloat, this proposal addresses the need for more flexible and powerful scripting capabilities. The new opcodes allow scripts to access transaction data directly and perform calculations with larger numbers, enabling the implementation of various advanced transaction types.
The introduction of these features will:

1. Enable more sophisticated smart contracts and conditional spending scenarios.
2. Support the implementation of mutual transactions as discussed in KIP-9.
3. Allow for more efficient handling of micropayments and recurring transactions.
4. Enhance the overall flexibility and expressiveness of Kaspa's scripting language.
5. Enable precise calculations with larger numeric values through 8-byte integer support.

## Specification

### 1. New Opcodes

The following new opcodes are introduced to enhance script functionality:
#### Transaction Level Opcodes:

1. `OpTxInputCount` (0xb3): Returns the total number of inputs in the transaction
2. `OpTxOutputCount` (0xb4): Returns the total number of outputs in the transaction
3. `OpTxInputIndex` (0xb9): Returns the index of the current input being validated

#### Input/Output Query Opcodes:
1. `OpTxInputAmount` (0xbe): Returns the amount of the specified input
2. `OpTxInputSpk` (0xbf): Returns the script public key of the specified input
3. `OpTxOutputAmount` (0xc2): Returns the amount of the specified output
4. `OpTxOutputSpk` (0xc3): Returns the script public key of the specified output

### 2. Enhanced Integer Support
The proposal extends arithmetic operations to support 8-byte integers (previously limited to 4 bytes). This enhancement applies to:
1. Basic arithmetic operations
2. Numeric comparisons
3. Stack operations involving numbers
4. All opcodes that produce or consume numeric values

### 3. Opcode Behavior

#### 3.1 Input/Output Query Opcodes

- These opcodes expect an index parameter on the stack
- The index must be within valid bounds (0 to n-1, where n is the number of inputs/outputs)
- For amount opcodes, values are returned in sompis
- Script public key values include both version and script bytes

#### 3.2 Transaction Metadata Opcodes

- Return values directly without requiring parameters
- Values are pushed as minimal-encoded numbers
- Always succeed if executed (assuming KIP-10 is active)

### 4. Consensus Changes

- The implementation of these opcodes requires a hard fork, as they introduce new functionality to the scripting language.
- All nodes must upgrade to support these new opcodes for the network to remain in consensus.
- The activation of these opcodes should be scheduled for a specific daa score, allowing sufficient time for the network to upgrade.

### 5. Activation
The features introduced in this KIP are activated based on DAA score:
1. Prior to activation:
- New opcodes are treated as invalid
- Arithmetic operations remain limited to 4 bytes
2. After activation:
- All new opcodes become available
- 8-byte arithmetic support is enabled
- Existing scripts continue to function as before

### 6. Reserved Opcodes
The following opcodes are reserved for future expansion:
- OpTxVersion (0xb2)
- OpTxLockTime (0xb5)
- OpTxSubnetId (0xb6)
- OpTxGas (0xb7)
- OpTxPayload (0xb8)
- OpOutpointTxId (0xba)
- OpOutpointIndex (0xbb)
- OpTxInputScriptSig (0xbc)
- OpTxInputSeq (0xbd)
- OpTxInputBlockDaaScore (0xc0)
- OpTxInputIsCoinbase (0xc1)

## Rationale

The enhanced opcodes and arithmetic capabilities address several key requirements:

1. Transaction Introspection: Scripts can now examine and validate transaction properties directly, enabling complex conditional logic
2. Larger Number Support: 8-byte integers allow for precise calculations with large values, essential for financial operations
3. Future Extensibility: Reserved opcodes provide a clear path for future enhancements
4. Backward Compatibility: The activation mechanism ensures a smooth network upgrade

These opcodes are designed to work within the existing P2SH framework, maintaining compatibility with current address types while significantly expanding the possibilities for script design.

## Backwards 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

A reference implementation of the new opcodes and example usage can be found in the following pull request to the rusty-kaspa repository:

[https://github.com/kaspanet/rusty-kaspa/pull/487](https://github.com/kaspanet/rusty-kaspa/pull/487)

Additional examples demonstrating the use of these opcodes can be found in:

[https://github.com/biryukovmaxim/rusty-kaspa/blob/kip-10-mutual-tx/crypto/txscript/examples/kip-10.rs](https://github.com/biryukovmaxim/rusty-kaspa/blob/kip-10-mutual-tx/crypto/txscript/examples/kip-10.rs)

## Example Usage

To illustrate the practical application of the new opcodes, we present three scenarios: a threshold scenario, a shared secret scenario, and a mining pool payment scenario.

### 1. Threshold Scenario

This scenario demonstrates a script that allows for two types of spending conditions:

1. Owner spending: The owner can spend the UTXO by providing a valid signature.
2. Borrower spending: Anyone can spend the UTXO if they create an output with a value greater than the input by a specified threshold amount, sent to the same script.

### 2. Shared Secret Scenario

This scenario demonstrates a more complex script that allows for:

1. Owner spending: The owner can spend the UTXO by providing a valid signature.
2. Borrower spending with shared secret: A borrower can spend if they know a shared secret and create an output with a value greater than or equal to the input, sent to the same script.

### 3. Mining Pool Payment Scenario

This scenario demonstrates how the new opcodes can be used to optimize mining pool payouts, allowing for efficient M:N transactions where multiple inputs can be used to pay multiple participants.

Concept:
1. Pool Operation: The pool manages a KIP-10 compatible P2SH address for each participant, ensuring each address always has at least one UTXO.
2. Payout Process: When a block is mined, the pool can efficiently distribute rewards using a single transaction with multiple inputs and outputs.

The script for this scenario would allow two types of spending:
1. Borrowing (used by the pool for payouts): Allows spending the UTXO if an output of greater value is created with the same script.
2. Owner spending: Allows the participant to spend their funds normally with their signature.

Advantages:
1. Efficient M:N transactions: The pool can use M inputs (including the coinbase and participant UTXOs) to create N outputs (payouts to participants) in a single transaction.
2. Reduced transaction costs: By combining multiple payouts into a single transaction, the overall transaction costs are significantly reduced.
3. Improved payout frequency: The ability to efficiently batch payouts allows pools to distribute rewards more frequently without incurring excessive fees.
4. Simplified pool operations: Pools can manage payouts more efficiently, streamlining their operational processes.
5. Participant flexibility: Participants maintain full control over their funds while allowing the pool to optimize payouts.
6. Enhanced scalability: As the number of pool participants grows, the efficiency gains from this approach become more pronounced.

These examples demonstrate how the new opcodes enable complex spending conditions that were not possible before, allowing for innovative use cases such as threshold-based spending, shared control over UTXOs, and efficient mining pool operations.

## Security Considerations

1. Increased complexity in transaction validation, requiring careful implementation and testing.
2. Potential for resource consumption attacks if scripts using these opcodes are not properly limited.
3. Implications for transaction caching and optimizations, as scripts may now depend on broader transaction context.
4. Potential privacy implications of allowing scripts to access more transaction data.

Implementers should be aware of these considerations and implement appropriate safeguards, such as script size and complexity limits, to mitigate potential risks.

## Related Work: Additive Addresses

While this KIP focuses on transaction introspection opcodes, it's worth noting a related but separate feature being discussed for Kaspa: additive addresses. Additive addresses would allow for auto-compounding behavior where UTXOs can be spent by adding to their value, subject to certain constraints.

The key distinction is that additive addresses can be implemented without consensus changes, using only the existing P2SH mechanism:

1. A public key and threshold value can be combined into a standard script that enforces additive-only spending rules
2. This script can be hashed to create a P2SH script public key
3. The reverse operation (extracting the public key and threshold from the P2SH hash) is impossible by design, as P2SH only stores the hash of the script

While additive addresses complement the functionality provided by KIP-10's introspection opcodes, they serve different purposes and will be proposed separately. The introspection opcodes in this KIP provide general-purpose transaction inspection capabilities, while additive addresses offer a specific optimization for auto-compounding use cases.


## References

1. KIP-9: Extended mass formula for mitigating state bloat
[https://github.com/kaspanet/kips/blob/master/kip-0009.md](https://github.com/kaspanet/kips/blob/master/kip-0009.md)

2. Auto-Compounding Additive Addresses Discussion
[https://research.kas.pa/t/auto-compounding-additive-addresses-kip10-draft/168](https://research.kas.pa/t/auto-compounding-additive-addresses-kip10-draft/168)

3. Micropayments Discussion (KIP-9 Follow-up)
[https://research.kas.pa/t/micropayments/20](https://research.kas.pa/t/micropayments/20)

4. Bitcoin Cash CHIP-2021-02: Native Introspection Opcodes
[https://gitlab.com/GeneralProtocols/research/chips/-/blob/master/CHIP-2021-02-Add-Native-Introspection-Opcodes.md](https://gitlab.com/GeneralProtocols/research/chips/-/blob/master/CHIP-2021-02-Add-Native-Introspection-Opcodes.md)

This proposal draws significant inspiration from BCH's implementation of transaction introspection opcodes. The BCH implementation demonstrated the viability and benefits of native introspection over covenant workarounds. While Kaspa's implementation differs in some details due to its unique architecture and requirements, the core principles and many design decisions were informed by BCH's successful deployment of these features. We appreciate the extensive research and documentation provided by the BCH community in CHIP-2021-02.

5. BCH Implementation Reference
- Bitcoin Cash Node implementation: [BCHN MR 1208](https://gitlab.com/bitcoin-cash-node/bitcoin-cash-node/-/merge_requests/1208)
- Test cases: [BCHN Native Introspection Tests](https://gitlab.com/bitcoin-cash-node/bitcoin-cash-node/-/blob/6fff8c761fda0ad15c9752d02db31aa65d58170f/src/test/native_introspection_tests.cpp)