Skip to content
Developer Handbook

Cash Improvement Proposals

Unforgeable Groups

On this page

CHIP-2021-02 · Proposal · Tokens

Proposes consensus-enforced token groups for issues, balances and token transfers.

Original proposal

Specification

    Title: Unforgeable Categories: Native Token Primitives for Bitcoin Cash
    First Submission Title: Group Tokenization for Bitcoin Cash
    First Submission Date: 2021-02-23
    Owners: bitcoincashautist (ac-A60AB5450353F40E)
    Type: Technical
    Layers: Consensus, Script, Network
    Status: INFORMATION / ARCHIVED
    Current Version: 8.0
    Last Edit Date: 2022-06-19

On May 15th 2023, Bitcoin Cash (BCH) activated CHIP-2022-02-CashTokens: Token Primitives for Bitcoin Cash

This CHIP is left as a record of a big portion of discussions and process that led to activating the CashTokens CHIP, which the owner of this CHIP fully endorsed.

See changelog for more context.

Contents

  1. Summary
  2. Deployment
  3. Motivation
  4. Benefits
  5. Technical Description
  6. Specification
  7. Security Analysis
  8. Implementations
  9. Test Cases
  10. Activation Costs
  11. Ongoing Costs
  12. Costs and Benefits Summary
  13. Risk Assessment
  14. Evaluation of Alternatives
  15. Discussions
  16. Statements
  17. Changelog
  18. Copyright
  19. Credits

Summary

[Back to Contents]

This proposal describes an upgrade to Bitcoin Cash peer-to-peer electronic cash system that enables unforgeable contracts and native tokens. Those features will scale as well as current Bitcoin Cash features and will not interfere with Bitcoin Cash scaling or its utility as peer-to-peer cash. The upgrade will be deployed as part of Bitcoin Cash upgrade schedule, that allows for clean upgrades using orderly hard-forks. Only validating node software needs to be upgraded while other applications won't require an upgrade, meaning everyone can continue using Bitcoin Cash (BCH) as they're used to, no action required. Upgrading old applications or creating new ones will be on a voluntarily basis by those that want to access new features, and at their own pace. We expect that many will be attracted to build and access products using those features, and that such products will bring more utility to Bitcoin Cash.

Motivation section will show the fundamental limitation of current Bitcoin Cash blockchain capabilities in that it currently can not create contract instances that can not be counterfeited.

Benefits section will show why those features are essential in facilitating a parallel economy founded on Bitcoin Cash. Money is always exchanged for something, be it a good or a service. The proposed features will allow units of BCH to create persistent blockchain structures, programmable pots of money that can not be counterfeited, that can be made to interact with each other, thus increasing utility of BCH. Using those programmable pots of money, goods and services may be represented natively on the blockchain so that they can be trustlessly exchanged for cash, Bitcoin Cash. Even some business processes may live as interconnected pots of money, so that organizations could transparently and trustlessly guarantee delivery of cash to those that can prove a claim. This will enable creation of organizations with a great degree of decentralization and censorship resistance.

Technical description section will show how this will be achieved by natural extension of Bitcoin Cash UTXO blockchain model.

Specification will define formal consensus specificaton rules, to be used by implementers.

Security analysis section will demonstrate soundness of the proposed system, and show that it doesn't introduce new DoS or malleability vectors.

Example Uses will outline high-level constructions made possible by this proposal.

Activation costs section will demonstrate that it is mandatory only for node software to upgrade, and unupgraded non-node software can continue to function without an upgrade. Only accessing new features will require an upgrade of other software, where it is expected that the cost of such upgrade will be offset by the benefits of new features.

Ongoing costs section will demonstrate that the proposal doesn't change the scaling "big O", and that it doesn't introduce new scaling bottlenecks or node operating costs.

Costs and benefits summary will show how this upgrade brings ever-growing benefits to all stakeholders while keeping activation costs fixed and contained to a scheduled node software upgrade.

Risk assessment will demonstrate that the upgrade is by nature low risk, because it is well contained and risk factors are entirely controlled by node developers.

Deployment

[Back to Contents]

This proposal targets May 2023 activation.

Motivation

[Back to Contents]

The May 2022 Bitcoin Cash upgrade was arguably the biggest upgrade Bitcoin (the original invention) has seen since genesis because it has successfully activated:

The upgrade has already sparked innovation by enabling development of:

Contracts now have full access to the whole transaction they're being spent in and can make decisions based on content and satoshi value of any other input and output in the same transaction. This alone enables much versatility in designing application, and one important class of application is the covenant. Covenant is a class of contracts that requires its own code to be passed on to newly created outputs, on top of which further requirements may be placed. One simple example of a covenant would be a contract that allows only a fixed amount of BCH to be taken out at fixed time intervals, that has been made much simpler and smaller (900 bytes per transaction down to 243 bytes) by introduction of introspection opcodes.

Covenant contracts create chains of transactions that each link-up and lead back to the first one, the contract's instance genesis transaction. The covenant's self-replication code ensures that the chain can't be broken by future spenders - if they want to spend then they MUST extend the covenant's chain.

Problem on Bitcoin Cash blockchain is, anyone can copy the contract code and create a new chain. Someone who inspects just the last transaction has no way of knowing from which starting point the tip of the chain is coming - he must follow the whole chain back to the contract's instance genesis transaction. This is easy to verify by external observers: they query the blockchain for past transaction until they reach the tip.

However, what if we wanted to create some other contract that required a spend from a particular chain? What if we wanted to create a non-fungible token (NFT) contract where we'd want to be sure it's the real one without having to look up the whole history? With current Bitcoin Cash blockchain features - such contracts are impossible to construct because a covenant contract can't prove its own genesis using a fixed size proof. The problem has been independently discovered by many individuals interested in Bitcoin Cash developments, and is well illuminated here. Later, an example demonstrated how even with the latest upgrade, the same fundamental problem prevents such contracts from being made.

Cornerstone feature of this proposal is solving the proof-of-genesis problem by enabling unforgeable contracts, contracts that carry a compact fixed-size proof of their own genesis transaction.

To actually make those contracts practical and useful in building decentralized applications, two hard-coded unforgeable contracts are proposed on top of unforgeable contracts, that will enable native token primitives: fungible token (FT) super-contracts and non-fungible token (NFT) super-contracts. Those will allow decentralized applications to be built simply and efficiently, by using Script VM to combine them in a way that allows complex structures to exist on Bitcoin Cash blockchain, and all without impacting scaling properties of the network.

Benefits

[Back to Contents]

By enabling token primitives on Bitcoin Cash, this proposal offers several benefits.

Cross-Contract Interfaces

Using non-fungible tokens (NFTs), contracts can create messages which can be read by other contracts. These messages are impersonation-proof: other contracts can safely authenticate and act on the message, certain that it was produced by the claimed contract.

With contract interoperability, behavior can be broken into clusters of smaller, coordinating contracts, reducing transaction sizes. This interoperability further enables covenants to communicate over public interfaces, allowing diverse ecosystems of compatible covenants to work together, even when developed and deployed separately.

Critically, this cross-contract interaction can be achieved within the "stateless" transaction model employed by Bitcoin Cash, rather than coordinating via shared global state (like that required of the Ethereum virtual machine). This allows Bitcoin Cash to support comparably contract functionality while retaining its >1000x efficiency advantage in transaction and block validation.

Decentralized Applications

Beyond enabling covenants to interoperate with other covenants, these token primitives allow for byte-efficient representations of complex internal state - supporting advanced, decentralized applications on Bitcoin Cash.

Fungible tokens are critical for covenants to represent on-chain assets - e.g. voting shares, utility tokens, collateralized loans, prediction market options, etc. - and implement complex coordination tasks - e.g. liquidity-pooling, auctions, voting, sidechain withdrawals, spin-offs, mergers, and more.

Non-fungible tokens are critical for coordinating activity trustlessly between multiple covenants, enabling covenant-tracking tokens, depository child covenants, multithreaded covenants, and other constructions in which a particular covenant instance must be authenticated.

Universal Native Token Primitives

By exposing basic, consensus-validated native token primitives, this proposal supports the development of higher-level, interoperable token standards (e.g. SLP). Token primitives can be held by any contract, wallets can easily verify the authenticity of a token or group of tokens, and tokens cannot be inadvertently destroyed by non-token-aware wallet software.

Technical Description

[Back to Contents]

Bitcoin Cash already is programmable cash, where every unit of cash carries a program (a "smart contract") that determines how it may be spent. Most common such program is known as an "address", which simply requires a signature in order to spend the cash unit. We will first introduce the concept of unforgeable contracts, that enables units of BCH to be marked with an unique identifier which will serve as proof that some BCH amount came from a particular contract instance. Bitcoin Cash units that inherit from the same unforgeable contract instance can be thought of as forming an exclusive category of cash units, where membership is controlled exclusively by current members, thus we title this proposal unforgeable categories (of BCH outputs). We will then use that as a fundamental feature on top of which to build native token primitives through introducing two essential "super-contracts", non-fungible token (NFT) and fungible token (FT) contracts enforced by native consensus code, that can be seamlessly used by Bitcoin Cash Script contracts to create efficient token systems tailored to their purpose.

Transaction format will be extended to allow transaction outputs to optionally carry a category identifier using the non-breaking PreFiX method. We will refer to all transaction outputs (TXOs) having a common identifier as a category (of BCH outputs), and individual such outputs as categorized outputs. New outputs will be allowed into an existing category only by spending an unspent transaction output (UTXO) of the same category in the same transaction, allowing only existing members to introduce new members. Transaction input format will be extended similarly to outputs, so inputs may be spent as category genesis inputs. Such inputs will be the only way to allow creation of outputs with a newly generated category identifier. The identifier will be deterministically generated based on the input's unique data, therefore every category genesis transaction will be unique. By induction, every category will be exclusive to descendants of the category's genesis input, therefore category membership will be unforgeable.

Additionally, the format will allow categorized outputs to encode token state using a fixed-size nft type field, a fixed-size fungible token (FT) amount field, and a variable-length non-fungible token (NFT) message field. Native tokens will be enabled by two native token "super-contracts", kind of contract directly enforced by consensus code, that will place immutable rules on how token state may evolve across any single transaction involving categorized outputs. The enforcement will be transaction-local, and immutable category properties will be globally guaranteed by induction:

  • unforgeability of the category identifier,
  • non-fungible tokens cardinality (number of outputs),
  • non-fungible tokens message authenticity,
  • fungible tokens accounting equation.

[Introspection opcodes] will be extended to access categorized output fields and input's category genesis fields.

Transaction signing will be updated with a new signature hash type which will be mandatory for signing transactions involving categorized outputs.

Network rules will be updated to allow transactions with categorized output templates to be relayed while the network message format will remain the same.

Wallet address format update will be discussed and shown to be unnecessary.

Transaction Format

We will extend the output format using the non-breaking PreFiX method and will refer to the full output prefix with its fields as "category annotation".

Categorized Output Format
  • transaction outputs
    • output 0
      • satoshi amount, 8-byte uint
      • locking script length, compact-size uint
      • locking script
        • OPTIONAL: PFX_CATEGORY, 1-byte constant 0xEE
          • category ID, 32 raw bytes
          • nft type, 1 raw byte
          • nft message length, compact-size uint
          • OPTIONAL: nft message, variable number of raw bytes
          • fungible token amount, compact-size uint
        • real locking script, variable number of raw bytes
    • ...
    • output N

The nft type field will encode a non-fungible token (NFT) state, and 0-value will indicate "no NFT", a NULL NFT state.

The nft message field will extend the NFT state by enabling it to carry a message. It will be limited to 520 bytes, which is chosen to match the MAX_SCRIPT_ELEMENT_SIZE limit, so that every nft message may be read and manipulated by Script VM. NFT message may only be encoded if the output encodes an NFT state. The message is optional, and 0-value nft message length will indicate "no NFT message", a NULL NFT message state.

The fungible token amount will encode a fungible token (FT) state, and 0-value will indicate "no FT", a NULL FT state. Range of fungible token amount will be limited to the positive part of signed 64-bit integer range, so that every amount may be read by Script VM (using transaction introspection opcodes) and manipulated as a Script number.

NFT Type

Categorized outputs may encode one of 4 NFT states:

  • NFT_NULL = 0x00 (b00000000),
  • NFT_TRANSFER = 0x03 (b00000011),
  • NFT_EDIT = 0x07 (b00000111),
  • NFT_MINT = 0x0F (b00001111).

All other values are reserved and reading a reserved value will immediately fail the transaction. Here we're only concerned with transaction format so we have only defined allowed values and have not described their purpose, which will be done in the next section.

Categorization Consensus Rules

Existing Bitcoin Cash rules will apply the same to both pure and categorized outputs. Categorization consensus rules are an additional set of rules exclusive to categorized outputs.

Category membership and category genesis rules will apply to ALL transactions involving categorized inputs and outputs. They're sufficient to enable unforgeable categories and unforgeable contracts features.

On top of that, we will introduce two essential and independent token "super-contracts": non-fungible tokens and fungible tokens. They will allow applications to set additional constraints over all descendants of the category genesis input, in effect enabling native token primitives that can be extended using Script VM to build any imaginable token system.

Category Membership

New outputs of some category_id may be created in a transaction if:

  • the transaction spends at least one prevout with the same category_id, or
  • there exists an input with prevout index 0 and output's category_id matches the prevout's TXID.

This also means that an input could be both adding a pre-existing token into the transaction and allowing creation of new token outputs with another ID. We don't unnecessarily restrict this, because a Script contract could easily control it, and even make good use of it for constructions such as transitions between distinct categories.

Category initial state is created by the first batch of outputs with the ID generated from the genesis input's TXID. The category genesis input can be thought of as only authorizing creation of first set of outputs - it is the so created outputs that initialize the state of the category. This is consistent with coinbase inputs, they only authorize a change in the UTXO state, but the state is actually changed by creating the coinbase output.

New outputs can only be added to the category by inheriting membership from existing member outputs or from the genesis input which will be the first member of any category.

Category Genesis

The genesis consensus rule will be the only possible way to create a new category. Creation of new categories will be authorized by category genesis inputs, which are defined as inputs that spend any prevout that has its index in the parent transaction equal to 0.

Consensus code will recognize every such input as allowing creation of any number of outputs with the category_id that equals the genesis input's parent TXID.

There can be multiple such inputs in a transaction, allowing creation of any number of categories.

Usage of category genesis input annotation with coinbase inputs will NOT be allowed since its TXID is all 0s.

With such definition, a category genesis transaction is self-evidently valid or invalid and not depending on non-local data. A new category is created simply by spending any index-0 output and it will allow creation of outputs that match the generated category_id.

With this setup we need an introspection opcode to access genesis information, because any genesis input could be carrying information about 2 tokens:

  1. Some pre-existing token, carried by the prevout being spent
  2. The new token, created in-situ with the genesis input and related outputs

Introspection opcodes will enable reading either or both, so contract writers will have full control over genesis setups.

Category Super-contracts

We will introduce two fundamental "super-contracts" that can be used as primitives to build any imaginable token system. They're enforced independent of each other, which means that fungible token amounts can freely flow between outputs of the same category, independent of the output's NFT state.

Non-fungible Tokens Super-contract

This set of consensus rules will enforce non-fungible token (NFT) logic by defining how NFT UTXO state may evolve from any category's initial NFT state. The domain of the super-contract is only the NFT state, contained in categorized UTXOs that encode NFTs.

Non-null NFT states will be referred to as NFT capabilities and are defined as follows:

  • Transfer: The NFT UTXO being spent may pass its NFT state to only one new NFT output, and it must inherit the NFT message state of the parent.
  • Edit: The NFT UTXO being spent may pass its NFT state to only one new NFT output, and the NFT message state may be freely changed.
  • Mint: The NFT UTXO being spent may pass its NFT state to many new NFT outputs, and their NFT message states may be freely changed.

New NFT outputs of some capability may inherit it from an existing UTXO spent in the same transaction or category genesis input in the same transaction. Capability may be freely demoted.

Any transaction input may implicitly destroy an NFT by not carrying its state over to newly created NFT output(s) of the transaction. This means that spending a mint-capable NFT input may be used to effectively edit lesser-capable NFTs of the same category, because in a same transaction they can be destroyed and recreated as descendants of the minting input.

If a category is created without some NFT capability, then ALL NFTs of the category will be permanently without the capability and without the possibility of obtaining it later. Sometimes this will be desirable, and sometimes capability will be preserved but a Script covenant will be placed on the NFT to limit the use.

This allows for creation of any imaginable blockchain structure, and even implementing fungible tokens using Script, where they could use the NFT message field for their amount state. Because fungible tokens are essential building blocks of blockchain applications, we propose to introduce them as the only other super-contract.

Fungible Tokens Super-contract

This set of rules will enforce fungible token (FT) logic by defining how FT UTXO state may evolve from any category's initial FT state. The fungible token amount field is dedicated for this super-contract and enforcement isn't opt-in as with the NFT's message field. The domain of the super-contract is only the FT state, contained in categorized UTXOs that encode FTs.

The super-contract will enforce input and output sums of the respective fungible token amount field to balance across a transaction. The entire supply is created with the genesis transaction, and later it may only be reduced by omitting amounts from the output side. In other words, for each distinct category in a transaction the sum of amounts in must be less than or equal than the sum of amounts out.

Category Annotation Transaction Introspection

We will extend CHIP-2021-02: Native Introspection Opcodes with 6 unary opcodes. Each will pop one stack item as a Script number: an input or output index and return the token state from the inspected input or output.

Name Codepoint Description
OP_UTXOTOKENCATEGORY 0xce (206) Pop the top item from the stack as an input index (VM Number). Push the concatenation of category ID and nft type of the Unspent Transaction Output (UTXO) spent by that input to the stack. If the UTXO includes no tokens, push a 0 (VM Number).
OP_UTXOTOKENCOMMITMENT 0xcf (207) Pop the top item from the stack as an input index (VM Number). Push the token commitment of the Unspent Transaction Output (UTXO) spent by that input to the stack. If the UTXO includes a non-fungible token with a zero-byte commitment or if the UTXO does not include a non-fungible token, push a 0 (VM Number). If the token commitment is longer than the stack item length limit, fail evaluation.
OP_UTXOTOKENAMOUNT 0xd0 (208) Pop the top item from the stack as an input index (VM Number). Push the token amount of the Unspent Transaction Output (UTXO) spent by that input to the stack as a VM Number. If the UTXO includes no fungible tokens, push a 0 (VM Number).
OP_OUTPUTTOKENCATEGORY 0xd1 (209) Pop the top item from the stack as an output index (VM Number). Push the concatenation of category ID and nft type of the output at that index to the stack. If the output includes no tokens, push a 0 (VM Number).
OP_OUTPUTTOKENCOMMITMENT 0xd2 (210) Pop the top item from the stack as an output index (VM Number). Push the token commitment of the output at that index to the stack. If the output includes a non-fungible token with a zero-byte commitment or if the output does not include a non-fungible token, push a 0 (VM Number). If the token commitment is longer than the stack item length limit, fail evaluation.
OP_OUTPUTTOKENAMOUNT 0xd3 (211) Pop the top item from the stack as an output index (VM Number). Push the token amount of the output at that index to the stack as a VM Number. If the output includes no fungible tokens, push a 0 (VM Number).

Note that raw transaction format uses the "compact-size uint" number serialization to encode numbers in a more compact form which is incompatible with Script VM. Introspection opcodes will be specified so that numbers are always pushed to Script VM stack in their deserialized form, so that Script VM may directly use the returned value instead of having to extract it from the encapsulation.

Transaction Signing

In order to prevent transactions involving categorized outputs from being malleable, output's category annotation must be included in Bitcoin Cash signature preimage format. Additionally, we want to prevent old software from being able to accidentally spend token outputs, i.e. it should not be able to produce valid signatures for prevouts that carry tokens. It is also desirable for signature preimage to contain information about tokens, so offline signers can know what they're signing. When there are no tokens to be included, signatures should be compatible with unupgraded software.

Malleability will be prevented without having to change output signing because, already with current specification, whole outputs get committed to the preimage so the annotation will be "automatically" included as part of outputs hash "locking script".

However, to prevent accidental burns by unupgraded software and allow offline signers to see token details, we must include the prevout's annotation, and in a way that will intentionally make signatures involving token prevouts incompatible with unupgraded software. We will achieve that by including prevout's annotations as a distinct field inside signature "recipe". The whole prevout's annotation will be added to the signature preimage first, just before adding the "modified locking script" serialization. This way signature preimages won't match when they include token inputs or outputs, because the annotation would be committed "outside" the modified locking script field, and unupgraded sofware would include them "inside" the field (P2PKH) or not at all (P2SH).

With only the above changes, and when there isn't any token data in their preimage -- signatures will be built the same by both non-upgraded and upgraded software.

This way:

  • Transactions won't be malleable;
  • Accidentally burning tokens by non-upgraded wallets will be prevented;
  • Offline signers will have access to prevout's token information;
  • Compatibility will be preserved for non-token signatures.

Network Rules

The standard locking script rules need to be updated to recognize categorized output format. Because categorized UTXOs will be bigger, another dust limit will be defined for categorized outputs. Treatment of data carrier and 0-value fungible tokens will be defined to be consistent with Bitcoin Cash rules.

Wallet Address Type

Because we require transactions involving categorized outputs to be signed using a new signature hash type bit, funds unintentionally sent to non-upgraded wallets can't be accidentally lost and will be recoverable by importing the recipient's wallet into upgraded software.

The existing CashAddress standard supports extending the address through the use of a type bit, which could be used to indicate wallet support for receiving tokens:

Encoding the size of the hash in the version field ensure that it is possible to check that the length of the address is correct.

Type bits Meaning Version byte value
0 P2KH 0
1 P2SH 8

Further types will be added as new features are added.

However we expect that, over time, most wallets will support receiving and sending tokens. Introducing two more address types just to signal readiness to receive tokens would only have a temporary benefit, while the cost of having to maintain two more address encodings would be permanent.

Therefore, we do NOT recommend a new address type.

Fungible Token Supply Definitions

Several measurements of fungible token supply are standardized for wider ecosystem compatibility.

By design, Genesis Supply, Reserved Supply, Circulating Supply, and Total Supply of any fungible token category will not exceed 9223372036854775807 (the maximum VM number).

Genesis Supply

A token category's genesis supply is an immutable, easily-observed, maximum possible supply, known since the token category's genesis transaction. It overestimates total supply if any amount of tokens have been destroyed since the genesis transaction.

The genesis supply of a fungible token category is known simply by using the genesis input introspection opcode. Blockchain-external agents, e.g. block explorers, can simply find the genesis transaction of the category and tally the outputs created. Blockchain-internal agents, i.e. contracts, can learn a token's genesis supply in two main ways:

  • Contracts executed in the same transaction can easily verify a new token's supply by using introspection opcodes to retrieve the initial amount.
  • Contracts executed in a later transaction can verify it by requiring the whole genesis transaction and the genesis input's parent TX as proof.
Total Supply

A token category's total supply is the sum – at a particular moment in time – of tokens which are either in circulation or may enter circulation in the future. A token category's total supply is always less than or equal to its genesis supply.

The total supply of a fungible token category can be computed by retrieving all UTXOs which contain token prefixes matching the category ID, removing provably-destroyed outputs (spent to OP_RETURN), and summing the remaining ft_amounts.

Software implementations should emphasize total supply in user interfaces for token categories which do not meet the requirements for emphasizing circulating supply.

Reserved Supply

A token category's reserved supply is the sum - at a particular moment in time - of tokens held in reserve by the issuing entity. This is the portion of the supply which the issuer represents as "not in circulation".

The reserved supply of a fungible token category can be computed by retrieving all UTXOs which contain token prefixes matching the category ID, removing provably-destroyed outputs (spent to OP_RETURN), and summing the ft_amounts held in prefixes which also carry an NFT with some capability.

Token standards may allow multiple UTXOs to hold the reserved supply, or they may require it to be held in a single UTXO. NFT capabilities allow for both scenarios, e.g. if the genesis input initialized an edit-only capable NFT then transactions affecting the reserved supply will be guaranteed to form a chain instead of a DAG and be easier to trace.

Circulating Supply

A token category's circulating supply is the sum - at a particular moment in time - of tokens not held in reserve by the issuing entity. This is the portion of the supply which the issuer represents as "in circulation".

The circulating supply of a fungible token category can be computed by subtracting the reserved supply from the total supply.

Software implementations might choose to emphasize circulating supply (rather than total supply) in user interfaces for token categories which:

  • are issued by an entity trusted by the user, or
  • are issued by a covenant (of a construction known to the verifier) for which token issuance is limited (via a strategy trusted by the user).

Specification

[Back to Contents]

The technical description section is intended to explain design choices and mechanics of rules presented here. This section defines formal rules for validating transactions that involve categorized inputs and outputs and is intended for implementers.

S1 Transaction Format Changes

Definitions

We define transaction output prefix byte that will indicate presence of optional category output annotation:

  • OUTPUT_PREFIX_BYTE_CATEGORY = 0xD0.

We define the maximum length for NFT messages:

  • MAX_SERIALIZED_NFT_MESSAGE_LENGTH = 520.
S1.1 Transaction Outputs

If OUTPUT_PREFIX_BYTE_CATEGORY byte is encoded at index 0 of a transaction outputs's locking script serialization then it will mark the start of a data structure that will encode the output category annotation. The whole annotation, including the prefix byte, will be removed from the locking script before handing it to Script VM:

<satoshi value><locking script length> [OUTPUT_PREFIX_BYTE_CATEGORY <fields>] <real locking script>.

Category output annotation is defined as:

OUTPUT_PREFIX_BYTE_CATEGORY <category_id> <nft_type> <nft_message_length>[nft_message] <ft_amount>

where:

  • category_id - a 32-byte value
  • nft_type - a 1-byte value
  • nft_message_length - a compact-size uint value that may encode a 1, 2, 4, or 8 byte uint
  • nft_message - byte array of nft_message_length bytes, encoded only if nft_type > 0 && nft_message_length > 0
  • ft_amount - a compact-size uint value that may encode a 1, 2, 4, or 8 byte uint

Value of ft_amount must obey these limits: minimum value 0 and maximum value 9223372036854775807 (0x7fffffffffffffff). (REQ-1.1.1.)

Value of nft_message_length must obey these limits: minimum value 0 and maximum value equal to MAX_SERIALIZED_NFT_MESSAGE_LENGTH defined above. (REQ-1.1.2)

Only outputs with non-null nft_type may encode the nft_message field, which is an optional extension of the NFT state.

If any categorized output satisfies nft_message_length > 0 && nft_type == 0 the transaction shall fail immediately. (REQ-1.1.3)

The annotation SHALL NOT count against length limits placed on locking script. (REQ-1.1.4)

S2 Transaction Validation Changes

These consensus rules will be enforced over every transaction that involves categorized inputs or outputs. The enforcement is transaction-local, i.e. everything required to validate the transaction is contained in the transaction and the prevouts (UTXOs) it references.

Token Type and Category Genesis rules will be enforced for individual inputs and outputs that encode a category annotation, while Category Membership, Fungible Tokens and Non-fungible Tokens rules will be enforced for aggregates of categorized inputs and outputs in the transaction.

S2.2 Categorization Consensus Logic
Category Genesis

Category genesis inputs are to be inferred just from their prevout's output index. If the index is 0, then it is a genesis input with category_id set to the prevout's TXID.

For purposes of computing transaction aggregates (sums and counts) required for validating transaction balancing rules, the genesis input will be considered as having a "maxed out" token state: maximum allowed fungible token amount, and the most capable nft token type with a null nft message.

Category Membership

For each distinct category_id observed in transaction's outputs there MUST exist a prevout with a matching category_id or a category genesis input with a matching category_id. (REQ-2.2.1)

Inputs may introduce two token states into the input-side balance: that of the genesis input, and that of a pre-existing output token state being spent as input's prevout. (REQ-2.2.2)

Fungible Tokens

For each distinct category_id observed in a transaction, sum of ft_amount values on the input side MUST not exceed the maximum value of 9223372036854775807 (0x7fffffffffffffff). (REQ-2.2.3)

For each distinct category_id observed in a transaction, sum of ft_amount values on the output side MUST not exceed the maximum value of 9223372036854775807 (0x7fffffffffffffff). (REQ-2.2.4)

For each distinct category_id observed in a transaction, sum of ft_amount on the output side MUST be less than or equal than the sum of ft_amount on the input side. (REQ-2.2.5) Note: Any genesis input will be accounted for as if having the maximum ft_amount value.

Non-fungible Tokens

The nft_type shall encode the output's NFT state, and here we will define allowed values:

  • NFT_NULL = 0x00 (b00000000),
  • NFT_TRANSFER = 0x03 (b00000011),
  • NFT_EDIT = 0x07 (b00000111),
  • NFT_MINT = 0x0F (b00001111).

Value of output's nft_type MUST equal one of the 4 allowed values. (REQ-2.2.6)

For each distinct category_id observed in a transaction, if there exists an output with NFT_MINT then there must exist a genesis input for the category or at least one input with NFT_MINT. (REQ-2.2.7)

For each distinct category_id observed in a transaction, the count of outputs with NFT_EDIT must be less than or equal than the count of inputs with NFT_EDIT, unless there exits an input with NFT_MINT or unless the category is being created by the genesis input. (REQ-2.2.8)

We define a nft_edit_budget as a difference between those two counts, and only if there's more such inputs then outputs and it's not a genesis transaction of the category and there doesn't exist an input with NFT_MINT for the category.

We define a nft_message_unmatched as a total of differences between count of inputs and outputs for each distinct category_id || nft_message_length || nft_message observed in a transaction that have NFT_BASIC NFT type and tallied only for cases where there's more such outputs than inputs.

The aggregate nft_message_unmatched MUST be less than or equal than nft_edit_budget, unless there exits an input of the same category_id with NFT_MINT or unless the category is being created by the genesis input. (REQ-2.2.9)

Suggested Implementation

Validation of these rules could be implemented using a temporary transaction-local data structure, one that would keep track of all aggregates needed to validate above requirements. We suggest a single temporary (per transaction) key-value store categories indexed by category_id, where its value would be a structure consisting of:

  • inputCount
  • inputFTSum Note: REQ-2.2.3 must be validated during accumulation. Set to max value if genesis.
  • inputNFTHasMint Note: true if genesis.
  • inputNFTEditCount
  • outputCount
  • outputFTSum Note: REQ-2.2.4 must be validated during accumulation
  • outputNFTHasMint
  • outputNFTEditCount
  • *categoryNFTMessages Sub-index instantiated for each distinct category, and used to index distinct NFT message observed for the category, with key defined as concatenation of categoryID, nftMessageLength and nftMessage. It will have at least 1 element and at most (parent.inputCount + parent.outputCount) elements. If genesis then use nftMessageLength=0 and no nftMessage. The value will consist of:
    • inputNFTBasicCount
    • outputNFTBasicCount

Then, while processing inputs and outputs, add categorized input's and output's token state to the tally.

Note: REQ-2.2.6 must be validated during accumulation.

Note: if an input is both a new category genesis input and also spends a categorized prevout, then that input will update 2 entries in the index, one for the prevout's category_id and another for the genesis input's category_id.

Finally, verify that it all balances for the transaction being evaluated:

    for (each category in tx.categories) {
        // Category Membership
        if(category.outputCount > 0 && category.inputCount < 1)
            fail() // (REQ-2.2.1)

        // Fungible Token rules
        if(category.inputSum < category.outputSum)
            fail() // (REQ-2.2.5)

        // Non-fungible Token rules
        if(category.inputNFTHasMint == 0) {
            nftMessageUnmatched = 0;
            nftEditBudget = 0;
            if(category.outputNFTHasMint == 1)
                fail() // (REQ-2.2.7)
            if(category.outputNFTEditCount > category.inputNFTEditCount)
                fail() // (REQ-2.2.8)
            if(category.outputNFTEditCount < category.inputNFTEditCount)
                nftEditBudget = category.inputNFTEditCount - category.outputNFTEditCount
            for (each nftMessage in category.categoryNFTMessages)
                if (nftMessage.outputNFTNoneCount > nftMessage.inputNFTBasicCount)
                    nftUnmatched = nftUnmatched + (nftMessage.outputNFTBasicCount - nftMessage.inputNFTBasicCount)
            }
            if (nftUnmatched > nftEditBudget)
                fail() // (REQ-2.2.9)
        }
    }
S2.3 Pay-to-Script-Hash (P2SH)

When combined with the category annotation, both current 20-byte P2SH and simultaneously proposed 32-byte P2SH output patterns MUST activate BIP-0016 redeem script consensus logic all the same:

  • P2SH20: OUTPUT_PREFIX_BYTE_CATEGORY category_state OP_HASH160 <hash_20> OP_EQUAL
  • P2SH32: OUTPUT_PREFIX_BYTE_CATEGORY category_state OP_HASH256 <hash_32> OP_EQUAL

(REQ-2.3.1)

S3 Script Virtual Machine Changes

Note that the code point 0xD0 will be repurposed and used in 2 contexts:

  • Category genesis introspection Script VM opcode, labeled OP_UTXOTOKENAMOUNT, which will be defined below;
  • Category output annotation, labeled OUTPUT_PREFIX_BYTE_CATEGORY.

This is possible because the prefix annotation gets snipped off from its respective script before being handed to Script VM and the 0xD0 byte was a disabled opcode.

S3.1 Category Annotation Introspection Opcodes

We will extend CHIP-2021-02: Native Introspection Opcodes with 6 unary opcodes. Each will pop one stack item as a Script number: an input or output index and return the token state from the inspected input or output.

Name Codepoint Description
OP_UTXOTOKENCATEGORY 0xce (206) Pop the top item from the stack as an input index (VM Number). Push the concatenation of category ID and nft type of the Unspent Transaction Output (UTXO) spent by that input to the stack. If the UTXO includes no tokens, push a 0 (VM Number).
OP_UTXOTOKENCOMMITMENT 0xcf (207) Pop the top item from the stack as an input index (VM Number). Push the token commitment of the Unspent Transaction Output (UTXO) spent by that input to the stack. If the UTXO includes a non-fungible token with a zero-byte commitment or if the UTXO does not include a non-fungible token, push a 0 (VM Number). If the token commitment is longer than the stack item length limit, fail evaluation.
OP_UTXOTOKENAMOUNT 0xd0 (208) Pop the top item from the stack as an input index (VM Number). Push the token amount of the Unspent Transaction Output (UTXO) spent by that input to the stack as a VM Number. If the UTXO includes no fungible tokens, push a 0 (VM Number).
OP_OUTPUTTOKENCATEGORY 0xd1 (209) Pop the top item from the stack as an output index (VM Number). Push the concatenation of category ID and nft type of the output at that index to the stack. If the output includes no tokens, push a 0 (VM Number).
OP_OUTPUTTOKENCOMMITMENT 0xd2 (210) Pop the top item from the stack as an output index (VM Number). Push the token commitment of the output at that index to the stack. If the output includes a non-fungible token with a zero-byte commitment or if the output does not include a non-fungible token, push a 0 (VM Number). If the token commitment is longer than the stack item length limit, fail evaluation.
OP_OUTPUTTOKENAMOUNT 0xd3 (211) Pop the top item from the stack as an output index (VM Number). Push the token amount of the output at that index to the stack as a VM Number. If the output includes no fungible tokens, push a 0 (VM Number).
S3.2 Signature Changes
Signature Preimage

Preimage format will be modified to accommodate the category annotation.

When present on an input's prevout, the whole prevout's category annotation serialization SHALL be inserted just before the prevout's "modified locking script" serialization. (REQ-3.2.1)

The prevout's "modified locking script" serialization SHALL NOT include the prevout's category annotation. (REQ-3.2.2)

When present on an output, the whole output's category annotation serialization SHALL be included as part of the output's "locking script" serialization. (REQ-3.2.3)

S4 Network Rules

S4.1 Standard Locking Scripts

It is required to update the standard locking script rules to recognize existing locking script patterns combined with output's category annotation.

We will summarize standard outputs below:

  • P2PK (deprecated): <key> OP_CHECKSIG
  • P2PKH: OP_DUP OP_HASH160 <hash_20> OP_EQUALVERIFY OP_CHECKSIG
  • P2MS: <m><<key 1>...<key n>><n> OP_CHECKMULTISIG
  • OP_RETURN: OP_RETURN [data 0]...[data N]
  • P2SH20: OP_HASH160 <hash_20> OP_EQUAL
  • P2SH32 (proposed for 2023): OP_HASH256 <hash_32> OP_EQUAL

Standard locking script rules MUST allow those templates combined with category annotation:

  • P2PK (deprecated): OUTPUT_PREFIX_BYTE_CATEGORY category_state <key> OP_CHECKSIG
  • P2PKH: OUTPUT_PREFIX_BYTE_CATEGORY category_state OP_DUP OP_HASH160 <hash_20> OP_EQUALVERIFY OP_CHECKSIG
  • OP_RETURN: OUTPUT_PREFIX_BYTE_CATEGORY category_state OP_RETURN [data 0]...[data N]
  • P2SH20: OUTPUT_PREFIX_BYTE_CATEGORY category_state OP_HASH160 <hash_20> OP_EQUAL
  • P2SH32: OUTPUT_PREFIX_BYTE_CATEGORY category_state OP_HASH256 <hash_32> OP_EQUAL

(REQ-4.1.1)

Depending on implementation, the above rules may not need an upgrade at all because the PFX annotation can be removed from the locking script and only the real locking script would be pattern-matched against standard templates.

S4.2 Dust Limit

If the output encodes category annotation and the output is not a data carrier output then value of satoshi_amount MUST be greater than CATEGORIZED_DUST_LIMIT, here defined as CATEGORIZED_DUST_LIMIT = 798. (REQ-4.2.1)

S4.3 NULL Token State

If the output is not a data carrier output then the output MUST NOT encode a category annotation with ft_amount and nft_type both set to 0. (REQ-4.3.1)

S4.4 Data Carrier Outputs (OP_RETURN)

Data carrier output may encode a category annotation with ft_amount and nft_type both set to 0. (REQ-4.4.1)

Security Analysis

[Back to Contents]

Category Genesis Soundness

Soundness of the proposed system relies on assumption that any category_id set on genesis transaction may be used only by outputs that have that transaction as an ancestor. It must not be possible to have another genesis transaction mined that would result in the same category_id as some previously-mined genesis transaction. This property is guaranteed the same way uniqueness of TXIDs and block hashes is guaranteed.

Using prevout TXID for the category_id ensures that token genesis input's generated category_id will be unforgeable and unique. In other words, for any category_id there can only ever exist exactly one genesis input. It is so because a duplicate category genesis TX would be rejected for double-spending the same output. Crafting 2 transactions using distinct outputs while re-rolling other parts of category_id preimage in attempt to find a hash collision is computationally impossible because it would take 2^(256/2) attempts. In other words, Wagner's birthday attack on category_id is impossible because it will have 128 bits of security against such attack, same as block hashes and TXIDs, so category_id will be as secure as those.

Note that the risk of a birthday attack is not the same as with Bitcoin Cash addresses where collisions are feasible with the 160-bit address format. A colliding address pair will have the same owner and is generally not a problem. A colliding category_id could be used to post another genesis TX after it's already been created for that category_id, which would destroy confidence in the whole system by disproving the unforgeability conjecture.

Category Genesis Malleability

Category genesis annotation will not be signed by current signature algorithms. At first look, it may seem that it would open a transaction malleability vector:

  1. Construct a category genesis transaction.
  2. Sign using SIGHASH_ALL.
  3. Broadcast.
  4. Attacker modifies PFX_I_CATEGORY_GENESIS arguments.
  5. TXID is changed, and signature still valid.
  6. Modified transaction is accepted into the blockchain.

This is not a viable attack and it would fail at 6. because:

  • Signature would indeed be valid.
  • Transaction itself would be invalidated for violating categorization consensus rules:
    • Any genesis category_id generated by the input declaration MUST appear in at least one output.
    • Any category_id seen on outputs MUST appear in at least one input (either ordinary or genesis).

In other words, removing the category genesis annotation or changing any part of it would either remove the category_id from the input or change it to some other one, not present on outputs. This would orphan signed outputs, and orphans are not allowed by categorization consensus rules.

Because outputs are signed, attacker can't update the related category_id on the outputs to make the transaction valid, as that would invalidate the signature since outputs, including their category annotation, are part of the signature preimage. Also note that changing the genesis input index would invalidate the signature (SIGHASH_ALL).

When using P2SH, the genesis annotation can be locked by using introspection opcodes to verify genesis parameters against expected ones.

Immutable Category Properties

They're guaranteed by induction, similarly to BCH properties. By consistently using consensus to enforce category rules for each transaction, below listed category properties will be globally immutable:

  • Single DAG root (genesis input) for the category;
  • Every category member will carry a partial proof of its genesis;
  • Accounting equation over the token_amount will hold globally for all fungible tokens of the category.
  • NFT messages are guaranteed to have come from either the category's genesis TX or an edit-capable NFT output.
  • If genesis input declared an NFT without cloneable capability, it will be guaranteed that there can only ever exist 1 NFT UTXO of the category.

DoS Vectors

Category Genesis

Category genesis verification requires a hash operation only if category_genesis_hash_type == 0x02. In other cases, it uses an already computed value (TXID or previous block hash). The number of genesis inputs is not limited, so could posting a TX filled with genesis inputs slow down transaction validation and be used as a DoS vector?

The data to be hashed is rigidly defined (TXID || index) and doesn't introduce a DoS vector considering many more hash operations and over much bigger messages can already be executed by locking and redeem scripts.

Transaction Local Index Size

Validating categorization consensus rules will require some transaction-local temporary indexes to be built in memory. The size of the index could grow to a maximum number of inputs or outputs that carry a distinct category_id or (category_id, NFTHasMessage(), nft_message). Could posting a TX filled with the maximum number of distinct category IDs be used as a DoS vector?

Upper bound of the temporary index can be calculated from current consensus limits on transaction size. Outputs have less overhead and are therefore a cheaper way to inflate the number of possible distinct category IDs. Consensus limits transaction size to 1MB, and the smallest input is an anyone-can-spend with OP_1 as the signature, which would be 42 bytes. Smallest output would be an amountless category type with an OP_RETURN output script, which would be 44 bytes. From that we can calculate the maximum number of distinct category IDs in a transaction: (1000000-42)/44 == 22726. Index building operations are of O(n*log(n)) time complexity, and with the above transaction size limit local index building will be 4.4*n at worst which is insignificant when compared to the cost of a single signature validation.

Block validation will continue to be O(n).

Invalid Transactions

At worst, detecting an invalid transaction will require processing the whole 1MB transaction after which the TXID can be banned if found invalid.

This is the same as current situation.

Transactions having categorized outputs would reduce density of TX CPU operations because each categorized output has at least 33 bytes of "dumb" data. If an attacker wanted to to load node CPUs, he could pack those same 33 bytes with some expensive opcodes instead.

Implementations must guard against the possibility of invalid transactions causing undefined behavior, such as attempting to overflow tokens sums during accumulation, before consensus validation gets to verifying the sums.

Consensus Failure

The proposal specification can be implemented with the structures and flow of existing codebases i.e. it doesn't require implementing some new untested hashing algorithm, serialization function or similar.

Implementation will rely on:

  • Raw bytes manipulation (slicing, concatenation);
  • Bitwise operations;
  • Local cache index building (in-memory maps and vectors, in C++ terms);
  • SHA-256 function;
  • Arithmetic operations.

Experienced node developers should have no trouble guarding against textbook "gotchas" such as endianness mismatch, overflows, off-by-one, etc.

Implementations

[Back to Contents]

For reference, older proof of concept, based on version 3 of the CHIP.

For reference, original implementation with a broader set of features:

Test Cases

[Back to Contents]

{TODO}

For reference, tests for the original implementation:

Example Uses

The following examples outline high-level constructions made possible by this proposal. The term covenant is used to describe a Bitcoin Cash contract which inspects the transaction which spends it, enforcing constraints - e.g. a contract which requires that users send an equal number of satoshis back to the same contract (such that the contract maintains its own "balance").

Covenant-Tracking, Non-Fungible Tokens

A covenant can be associated with a "tracking" non-fungible token, requiring that spends always re-associate the non-fungible token with the covenant.

Beyond simplifying logic for clients to safely locate and interact with the covenant, such a tracking token offers an impersonation-proof strategy for other contracts to authenticate a particular covenant instance. This primitive enables covenants to design public interfaces, paths of operation intended for other contracts (which may themselves be designed and deployed after the creation of the original covenant).

Because token category IDs can be known prior to their creation, it is straightforward to create ecosystems of contracts that are mutually-aware of each other's tracking token category ID(s).

Notably, tracking tokens also allow for a significant contract-size and application-layer optimization: a covenant's internal state can be written to its tracking token's commitment, allowing the locking bytecode of covenants to remain unchanged across transactions.

Depository Child Covenants

Given the existence of covenant-tracking, non-fungible tokens, it is trivial to develop depository child covenants - covenants which hold a non-fungible token and/or an amount of fungible tokens on behalf of a parent covenant. By requiring that the depository covenant be spent only in transactions with the parent covenant, such depository covenants can allow a parent covenant to hold and manipulate token portfolios with an unlimited quantity of fungible or non-fungible tokens (despite the limitation to one prefix codepoint per output).

Voting with Fungible Tokens

This proposal allows decentralized organization-coordinating covenants to hold votes using fungible tokens (without pausing the ability to transfer, divide, or merge fungible voting token outputs during the voting period).

In short, covenants can migrate to a new token category over a voting period – shareholders trade in amounts of "pre-vote" shares, receiving "post-vote" shares, and incrementing their chosen result by the amount of share-votes cast.

This construction reveals additional consensus strategies for decentralized organizations:

  • Vote-dependent, post-vote token categories - covenants which rely on absolute consensus - like certain sidechain bridges (which, e.g. must come to a consensus on an aggregate withdrawal transaction per withdrawal period and then penalize or confiscate dishonest shares) - can issue different categories of post-vote tokens based on the vote cast. This allows for transfer and trading of post-vote tokens even before the voting period ends. When different voting outcomes impact the value of voting tokens (after the voting period ends), such differences will immediately appear in market prices of post-vote tokens. This observation presents further consensus strategies employing hedging, prediction markets, synthetic assets, etc.
  • Covenant spin-offs - in cases where a covenant-based organization plans a spin-off (e.g. a significant sidechain fork), covenant participants can be allowed to select between receiving shares in the new covenant or receiving an alternative compensation (e.g. a one-time BCH payout or additional shares in the non-forking covenant).
Sealed Voting

"Sealed" voting - in which the contents of votes are unknown until after all votes are cast - is immediately possible with this proposal.

Voting begins with a "ballot box" merkle tree, containing at least as many empty leaves as outstanding shares. Voters submit a sealed vote: a message containing 1) the number of share-votes cast and 2) a hash of their vote concatenated with a salt. Sealed votes are submitted by replacing an empty leaf in the ballot box (as demonstrated in CashTokens v0). Once the voting period has ended, each participant can reverse the process: prove the contents of sealed votes within the tree by submitting the preimage, then aggregating results in another part of the covenant's state.

This basic construction can be augmented for various use cases:

  • voting quorum - requiring some minimum percentage of sealed votes before a voting period ends.
  • unsealing quorum - requiring some minimum percentage of sealed votes to be unsealed before vote results can be considered final.
  • sealing deposits - requiring voters to submit a deposit with sealed votes which can be retrieved by later unsealing the vote.
  • enforced vote secrecy - allowing holders of either pre-vote or post-vote tokens to submit sealed "unsealing proofs", proving that another voter divulged their unsealed vote prior to the end of the voting period. Such proofs could reward the submitter at the expense of the prematurely-unsealing voter, frustrating attempts to coordinate malicious voting blocs. (A strategy developed for Truthcoin.)

(Note, secret ballot voting would require the introduction of additional VM opcodes.)

Multithreaded Covenants

While most account-based contract models are globally-ordered by miners (e.g. Ethereum), the highly-parallel, UTXO model employed by Bitcoin Cash requires that contract users determine transaction order. This has significant scaling advantages - transactions can be validated in parallel, often before their confirming block is received, enabling validation of 25,000 tx/second on modest hardware (as of 2020). However, this model requires contract developers to account for transaction-order contention.

Transaction-order contention is of particular concern to covenants, contracts which require the spending transaction to match some pattern (e.g. returning the covenant's balance back to the same contract). Covenants typically offer a sort of "public interface", allowing multiple entities - or even the general public - to interact with a UTXO: depositing or withdrawing funds, trading tokens, casting votes, and more.

Spend races occur when multiple entities attempt to spend the same Bitcoin Cash UTXO. Spend races can degrade the user experience of interacting with covenants, requiring users to retry covenant transactions, and possibly preventing a user from interacting with the covenant at all.

To reduce disruptions from spend races, contracts must carefully consider spend-race incentives:

  • To reduce frontrunning, covenants should allow actions to be submitted over time, treating all submitted actions equally (regardless of submission time) at some later moment.
  • To disincentivize DOS attacks - e.g. where an attacker creates and rapidly broadcasts long chains of covenant transactions, spending each successive UTXO before other users can spend it in their own covenant transactions - covenants should ensure covenant actions are authenticated and/or costly (e.g. can only be taken once by each token holder, require some sort of fee or deposit, etc.).
  • To resist censorship or orphaning of unconfirmed covenant transaction chains by malicious miners, covenants should ensure important activity can occur over the course of many blocks, and wallet software should maintain logic for recovering (possibly re-requesting authorization from the user) and retrying covenant transactions which are invalidated by malicious miners.

Beyond these basic strategies, this proposal enables another strategy: multithreaded covenants can offload logic to "thread" sub-covenants, allowing users to interact in parallel with multiple UTXOs. Threads aggregate state independently, allowing input or results to be "checked in" to the parent covenant in batches. Multithreaded covenants can identify authentic threads using tracking non-fungible tokens (issued by the parent contract), and threads can authenticate both other threads and the parent covenant in the same way.

Thread design is application-specific, but valuable constructions include:

  • Lifetimes - to avoid situations where the parent covenant is waiting on an overactive thread (e.g. a DOS attack), threads should often have a fixed lifetime - a decrementing internal counter which prevents the thread from accepting further transactions after reaching 0. (And leaving a check-in with the parent covenant as the only valid spending method.)
  • Heartbeats - a derivation of lifetimes for long-lived threads, heartbeats allow a thread's lifetime to be renewed to some fixed constant after a period (by validating locktime or sequence numbers). This guarantees occasional periods of inactivity during which a check-in can be performed.
  • Proof-of-work - some threads may have use for rate limiting by proof-of-work, requiring users to submit preimages which hash to a value using some required prefix. (Note, for most applications, fees or minimum deposits offer more uniform rate limiting.)
  • modified zero-confirmation escrows (ZCEs) - and similar miner-enforced escrows can be employed by contracts to make abusive behavior more costly.

Given typical transaction propagation speed (99% at 2 seconds), multithreaded covenant applications with reasonable spend-race disincentives can expect minimal contention between users so long as the available thread count exceeds 2 per-interaction-per-second. (The wallet software of real users can be expected to select evenly/randomly from available threads to maximize the likelihood of a successful transaction.) Multiple threads can be tracked by the parent covenant (e.g. using a merkle tree), and thread check-ins can be performed incrementally, so covenants can be designed to support a practically unlimited number of threads.

Finally, exceptionally active covenant applications - or applications with the potential to incentivize spend-races - should consider using managed threads: threads which also require the authorization of a particular key, set of keys, or non-fungible token for each submitted state change. Managed threads allow transaction submission to be ordered without contention by the entity/entities managing each thread; they can be issued either to trusted parties or via a trustless strategy, e.g. requiring a sufficiently large deposit to disincentivize frivolous thread creation.

Activation Costs

[Back to Contents]

We define activation cost as any cost that would arise ex-ante, in anticipation of the activation by affected stakeholders, to ensure that their services will continue to function without interruption once the activation block will be mined. In case of this proposal, activation cost is contained to nodes and will amount to:

  • Some fixed amount of node developer man-hours, in order to release updated node software that will correctly validate transactions implementing the new consensus specification.
  • Some fixed amount of work by stakeholders running the node software, in order to deploy the software in anticipation of hard-fork activation.
  • Some fixed amount of effort by others involved in reviewing and testing the new node software version.

This is the same kind of cost that any hard-fork upgrade enabling previously disabled opcodes has had or will have. Nothing is required of stakeholders who are not running validating nodes or involved in node development.

Below we will discuss why this is the case and discuss potential impact in more detail, on both nodes and node-dependent software, and for that we will split activation cost the following way:

  1. Transaction Format
  2. Script Interpreter
  3. Node APIs
  4. Network Rules
  5. Categorization Consensus Logic

Transaction Format

The upgrade is extending transaction outputs with additional output fields using the non-breaking method proposed here.

If nodes just want to be able to validate transactions then they do not need to change their local database structures. Category annotation can continue to live inside the existing UTXO database as if it was part of the output's lockingScript. Existing databases must already be supporting longer lockingScript values than the standard templates because current consensus rules allow for expanded locking scripts instead of just the compressed P2SH variant.

Implementers may decide to restructure UTXO database by segregating the two new fields, but that is not necessary just to be able to validate transactions and be ready for upgrade activation.

Script Interpreter

Script PreFiX on Outputs

Here we will analyze whether output format change will make it necessary to upgrade any non-node software prior to activation.

Upgraded node software will snip off the PFX_O_CATEGORY and its arguments from the lockingScript and pass the remainder to the Script interpreter. The node Script interpreter will never get to see the category annotation.

Such software obtains blockchain data from a node which must be upgraded, and node APIs can be upgraded in a backwards-compatible way by hiding the PFX annotation from responses to queries that would be asking for the lockingScript. The only place where this can't be done is the "raw" transaction query which is the single source of truth about a transaction.

Node-dependent software that would alone extract the lockingScript from the raw format would get to see the category annotation as if it was part of outputs locking script. In the case of services like indexers, block explorers, etc. this is not a problem as they don't interpret the Script, they simply report what's stored in the field.

Software that would interpret the lockingScript would see that it starts with a disabled opcode and would consider the transaction invalid, so that software would need to be upgraded. Wallets that use simple heuristic to detect outputs that belong to them may ignore categorized outputs or they may include their BCH balances but they wouldn't know how to spend the outputs found.

This is the same kind of cost as enabling a new opcode but it would affect only a subset of software, only the software that would get to see the PFX and interpret it as an opcode.

In the below example we will demonstrate how, from the point of view of non-node non-upgraded sofware, introducing a field using the PFX method is no different than enabling a disabled opcode, and therefore will not break any such software. Consider the CHIP-2021-02: Native Introspection Opcodes, that was successfully activated in May 2022.

The nullary opcode OP_INPUTINDEX uses the previously disabled 0xC0 opcode. Ignoring network relay rules, it will allow anyone with some hash-power to mine a transaction with the locking script:

(1) OP_INPUTINDEX OP_DATA_31 random_data_31 OP_2DROP OP_DUP OP_HASH160 <PubkeyHash> OP_EQUALVERIFY OP_CHECKSIG.

The transaction is really a P2PKH output template prefixed by a no-op pattern. It is spendable using the standard P2PKH input script: <Sig> <PubKey>. Wallets that would scan for P2PKH pattern anywhere in the lockingScript and ignoring the total length of the lockingScript field could detect this pattern and be able to spend it. An unspendable variant is possible, too:

(2) OP_INPUTINDEX OP_0 OP_DATA_30 random_data_30 OP_DROP OP_DUP OP_HASH160 <PubkeyHash> OP_EQUALVERIFY OP_CHECKSIG.

Here, the prefix pattern would not be a no-op because the prefix would leave a dirty stack, making the transaction unspendable. Wallets that would scan for P2PKH pattern anywhere in the lockingScript and ignoring the total length of the lockingScript field could detect this pattern and not be able to spend it, which may prevent the user from spending their other outputs if the wallet would try to spend it alongside others, resulting in wallet downtime until the bug is resolved. User funds would never be at risk. This would affect only the wallets that scan for known patterns in this particular way, the way that ignores the position of the pattern and the total length of the lockingScript field.

Some categorized P2PKH NFT output full locking script would look like the following:

(3) PFX_O_CATEGORY random_data_33 OP_DUP OP_HASH160 <PubkeyHash> OP_EQUALVERIFY OP_CHECKSIG.

For some unupgraded software dealing with the raw unlockingScript field, transactions (2) and (3) would be equivalent in that they are:

  • Both starting with a disabled opcode, one with 0xC0, the other with 0xEE,
  • Both of the same length, 58 bytes,
  • Both ending with a known 24-byte P2PKH pattern.

Comparing raw bytes side by side better illustrates this:

  • (1): C0 1F112233445566778899001122334455667788990011223344556677889900116D 76A9 {PubkeyHash} 88AC
  • (2): C0 001E11223344556677889900112233445566778899001122334455667788990075 76A9 {PubkeyHash} 88AC
  • (3): EE 112233445566778899001122334455667788990011223344556677889900112280 76A9 {PubkeyHash} 88AC

All 3 examples could be detected by some wallet scanning for the 76A9 {PubkeyHash} 88AC suffix, where:

  • (1) is spendable,
  • (2) is unspendable, and
  • (3) would be spendable only by upgraded wallets because they require a slightly different signature
Script PreFiX on Inputs

Here we will analyze whether input format change will make it necessary to upgrade any non-node software prior to activation.

Upgraded node software will snip off the PFX_I_CATEGORY_GENESIS and its arguments from the unlockingScript and pass the remainder to the Script interpreter. The node Script interpreter will never get to see the category genesis annotation. Node APIs can be upgraded in a backwards-compatible way by hiding the PFX annotation from responses to queries that would be asking for the unlockingScript. The only place where this can't be done is the "raw" transaction query which is the single source of truth about a transaction.

The same that was demonstrated for output format applies here for the input format just the same.

Introspection Opcodes

Costs of activating those are documented in CHIP-2021-02: Native Introspection Opcodes and apply all the same here.

Signature Opcodes

This proposal intentionally makes signatures incompatible with old software.

Any software that wants to be able to sign and verify transactions that contain categorized outputs will have to be upgraded. Non-upgraded software will still be able to send and receive BCH, so the upgrade will not break current functionality and wallets may implement support for new signature types at their own pace.

Node APIs

This proposal doesn't specify how node APIs providing transaction and output data are to be upgraded, that is at discretion of each individual node developer team. All existing node APIs can remain the same to support the upgrade without breaking API-dependent software, in which case the dependent software will be unaware of outputs using extended fields. New API endpoints can be added to enable software to efficiently make use of the new features, and that can be done at any time, before or after the upgrade. Exception is the "raw" transaction API discussed above, where even non-upgraded software would get to see the extended fields.

Network Rules

This proposal changes nothing in the network message format and only requires update of network relay rules. This is a cost contained to node software, whether they validate transactions or not.

Categorization Consensus Logic

The proposal requires validating nodes to activate additional code paths in order to verify outputs whose unlockingScript or lockingScriptstarts with thePFX_I_CATEGORY_GENESISorPFX_O_CATEGORY"magic" byte0xEE`. Implementing the rules is a cost contained to validating node software. Transaction validation costs are part of the ex-post costs, discussed in the next section.

Ongoing Costs

[Back to Contents]

We define ongoing cost as any cost that would arise post upgrade. They could be simply an addition to node operating costs, or development costs to support new features that would become viable post activation. Here we have to make an important distinction, and we will define two broad categories:

  1. Unavoidable costs, such as node operating costs required to validate new rules.
  2. Opt-in costs, such as block explorer upgrade and operating costs to support native tokens ecosystem.

We don't see a significant increase in unavoidable costs and on that we will elaborate below. With opt-in costs, it is reasonable to expect that those will be part of some economic calculation which would result in a net benefit. We will discuss both nevertheless.

Unavoidable Ongoing Costs

These will be contained to node software, and consist of:

  • Node software maintenance costs.
  • Node operating costs.
Node software maintenance costs

The proposal has a clear logical structure and can be entirely implemented in procedural programming paradigm. Therefore, we posit that it is easy to reason about and we do not see this proposal as introducing potential surprises to those who would later maintain the code.

Still, some consideration will have to be given to existence of categorization code. For information, listed below are some changes that would NOT be significantly affected by this proposal's implementation:

  • Network rules;
  • Block and transaction size limits;
  • Pruning;
  • New opcodes;
  • New signature schemes;
  • UTXO commitments.

Some future upgrades might be affected:

  • Changing numerical precision for BCH & tokens, and it would be possible to change BCH precision independently of tokens;
  • Totally new state scheme e.g. utreexo.
Node operating costs

Impact on node operating costs can be analyzed through:

  1. Network bandwidth requirements.
  2. Node local storage requirements.
  3. Node CPU time required for transaction validation.
Additional network bandwidth requirements

Category annotation may add 34 to 84 bytes to each categorized BCH output. Size of inputs spending categorized outputs is not increased. Pure BCH outputs can be mixed with categorized outputs in the same transaction. Only category genesis inputs and categorized outputs will add some extra data to transactions.

In general, transactions will be at most nGOut * 84 bigger than comparable non-categorized pure BCH transactions, where nGOut is the number of categorized outputs in a transaction.

When discussing transaction sizes, this is no different than some custom input script, increasing the number of bare multisig keys, or OP_RETURN protocols. The user who has a need for the extra feature has to add some more data to the transaction which encodes his use of the feature, and for that he pays the miner's fee. Difference is in that categorized outputs require storing their state in the "premium" part of the blockchain, the UTXO set, which we will discuss below.

Node local storage requirements

When a node performs transaction validation then, in addition to the data provided by the transaction itself, it must also fetch each referenced UTXO from the database so that it can access previous output's satoshi amount and locking script. This holds the same for both pure BCH outputs and categorized outputs. No new data structures are required, and no additional database access operations are required.

It is only the size of the lockingScript field which is increased, and that field is part of the UTXO set, for which nodes already build and maintain an index. Consensus rules already support lockingScript sizes of variable length, and even network rules allow a variable length with the P2MS output template.

Node CPU time required for transaction validation

Category format and type are trivial to verify, as it is simply verifying the structure and allowed values of the PFX embedded inside the lockingScript field.

Category genesis, membership, and native token super-contracts require more complex operations, and we will discuss those below.

Category Genesis Transactions

Genesis transaction verification requires hashing 40 bytes using the double SHA-256 function, and only for inputs that opt to use hash_type == 0x01 (hash of prevout's TXID and index). This translates to additional 72*n bytes having to pass through the SHA-256 function (1st round 40, 2nd round 32), where n is the number of genesis inputs appearing in the transaction.

This is insignificant when compared to CPU load required to verify input signatures or redeem scripts that can execute hash operations on orders of magnitude more bytes.

Category Native Token Super-contracts

Validation of category super-contracts requires no cryptographic operations at all. It requires only simple operations such as comparison, arithmetic, and bitwise operations. It also requires some transaction-local temporary indexes to be built in memory that would store distinct category IDs seen in the transaction being validated and keep track of aggregate sums and counts for each category.

We have already discussed the cost of building these temporary indexes, and demonstrated how they are cheap when compared to other TX-validation operations.

We could argue that presence of category annotation in fact reduces CPU cost per byte, because the annotation is non-executable "dumb" data.

Opt-in Ongoing Costs

These can be thought of as cost of accessing the new features. For example, a wallet doesn't need to support new features and cost to that wallet's developers and users will be 0 unless they want to access the new features.

P2PKH and P2MS Native Token Users

Wallets will need to add the category P2PKH and P2MS templates and then they will be able to see categorized outputs, this is a trivial parsing task. To be able to actually spend them, the wallets will need to implement and maintain native token categorization logic, so that they can construct transactions that would satisfy the super-contract rules.

P2SH Users

Updates will be required to some libraries, transaction compilers, and other software which implements the BCH VM (e.g. Bitauth IDE).

SPV Servers

Without a change to SPV servers, upgraded wallets could still use the new feature by subscribing to the lockingScript as it would include the category annotation. This would come with a caveat that wallets would need to decide what token IDs they'll subscribe for.

Explicitly supporting new features would require an upgrade to SPV server software API, so that the lockingScript would not include the category annotation. That way, it would notify wallets of any amount received to a particular address, BCH or token.

Here we must note that it should be a new API endpoint, to avoid non-upgraded wallets querying lockingScript through an upgraded API and getting a categorized output they don't know how to spend.

Other Software

Block explorers, exchanges, indexers, etc. may be running some custom node-dependent software. While this upgrade wouldn't break their existing functionality, accessing the new features would require an upgrade of their software stack.

Ecosystem Building

We hope to see standards emerge around native token use, such as NFT standards, metadata extensions, and standardization of baton contracts placed on token genesis prevouts. Developing such standards is also a cost to be recognized, albeit one that is expected to be offset by ecosystem-wide benefits.

Costs and Benefits Summary

[Back to Contents]

General costs and benefits:

  • (+) Efficiency and scalability advantage of UTXO native tokens in comparison to account-based blockchains.
  • (+) Enabling efficient UTXO powered DeFi.
  • (+) Attracting new users, talent, and capital thus helping grow the entire ecosystem centered around Bitcoin Cash.
  • (+) Future proof. Since every categorized output is also a BCH output, it should seamlessly work with everything that can work with BCH, therefore categorized outputs and native tokens can reap benefits from future upgrades.
  • (+) Every categorized output created also creates marginal demand for BCH.

1 Node Stakeholders

  • (-) One-off costs of upgrading node software (coding, reviewing, testing, deployment).
  • (0) No impact on operating costs, scaling "big O" unchanged.
1.1 Miners
  • (+) More fee revenue through increased demand for transactions.
1.2 Big nodes

Exchanges, block explorers, backbone nodes, etc.

  • (+) Easy to implement other currencies through same familiar design patterns that are now used for Bitcoin Cash alone.
1.3 User nodes
  • (0) No impact.
1.4 Node developers
  • (-) One-off workload increase.
  • (-) Future maintenance cost.
  • (+) Later it just works, downstream developers create utility.

2 Userspace stakeholders

  • (+) Barrier to entry to token usage lowered.
2.1 Business users
  • (+) Access to financial instruments previously not available, or access to them at a better price and quality than competition can provide.
  • (+) Enables potential new business models.
2.2 Userspace developers
  • (+) Easy to implement other currencies through the same familiar design patterns that are now used for Bitcoin Cash alone.
  • (+) With more growth there will be more opportunity for professional advancement within the ecosystem.
2.3 Individual users
  • (+) Get to enjoy the best peer-to-peer electronic cash system!

3 Holders and speculators

3.1 Long
  • (+) Adoption correlates with increase in price.
  • (+) Even other tokens marginally increase demand for BCH, so the more transactions of any kind, the better.
  • (+) More liquidity in the market.
3.2 Short
  • (-) Adoption correlates with increase in price.
  • (+) More liquidity in the market.

4 Opinion holders who are not stakeholders

  • (0) We are hoping developments like this will move them towards becoming stakeholders!

Risk Assessment

[Back to Contents]

If we define risk as probability times severity then we could make an estimate using the risk matrix.

Generic consensus upgrade risks apply. Probability of bugs and network splits is entirely controlled by node developers and quality of their work. After the node software QC process is completed, the probability of a bug is expected to be very low.

Wrong Wallet Implementation

If a wallet would obtain a categorized output but be unable to spend it, then it could cause it to temporarily become unusable until the issue is resolved.

This could happen in two ways:

  1. Non-upgraded and badly implemented wallet registering a categorized output as one of its own, which is unlikely and has been discussed;
  2. Upgraded wallet having a bug in transaction building, which can be expected since bugs happen, and not all wallets pass through the same quality assurance processes.

Burning funds by non-upgraded wallets will not be possible since they wouldn't be able to produce a valid signature, and it would at worst result in temporary loss of service - users unable to send their funds until the issue is resolved. The same would hold for upgraded wallets that are upgraded but have a bug that would prevent them from producing valid transactions.

The riskiest class of bugs is that of an upgraded wallet able to produce signatures but failing to properly account amounts to create categorized "change" outputs that would capture amounts not intended to be spent. This risk was already present with pure BCH wallet implementations, where the result would be a donation to miners in form of fees. With this proposal, the risk applies the same to token amounts - but instead of being donated they'd be burned.

This is a risk external to protocol development, and the only mitigation available is to write good documentation and suggest using wallet software that has good quality-assurance processes. Since most popular wallets have proper processes in place and upgrades are reviewed and tested by multiple developers, we consider this risk to be low.

Wrong SPV Server Implementation

As discussed in the costs section, upgrading wallet APIs is at discretion of SPV server software developers. If the API would not be versioned and instead upgraded to provide annotation data as part of legacy queries then non-upgraded SPV wallets may end up seeing a categorized output as pure BCH output, which they'd be unable to spend.

Likelihood of such obviously bad API upgrade is low. Even if it occurred, funds would not be at risk and consequence would be temporary loss of service until the issue is resolved, so this is considered low risk.

Evaluation of Alternatives

[Back to Contents]

Script Tokens

Script token contracts that want to do conceptually simple things would have to be complicated and limited in number of inputs/outputs that they could support. For example, an NFT contract would require over 300 bytes of unlocking script that would have to be repeated with every transfer, just to prove that an NFT is an NFT.

With this proposal, it is possible to remove the burden on Script and users by providing consensus-enforced super-contracts which can interface with the Script layer, retaining flexibility of Script while allowing easy and efficient P2PKH tokens.

Other Blockchains

The below table compares the proposed token solution with other popular blockchains.

ERC-20 Native tokens Native tokens
Backing blockchain Ethereum Cardano Bitcoin Cash
Relationship to the blockchain A contract standard, users copy-paste the standard code and modify it. Not a standard. Most functionality is built into the ledger itself. Not a standard. Most functionality is built into the ledger itself.
Controlled by A Solidity smart contract A minting policy script in any scripting language supported by Cardano A minting policy Bitcoin Cash Script
Requires a smart contract to mint/burn? Y Y Optional, by placing a P2SH Script contract on the genesis output
Minting logic can be customized? Y Y Y
Requires a smart contract to transfer? Y N N
Can be used by other smart contracts without special support? N Y Y
Can be transferred alongside other tokens? N Y Y
Transfer logic provided by? Copy-pasting from the ERC-20 template The Cardano ledger itself The Bitcoin Cash ledger itself
Transfer logic can be customized? Y N Y, by having the minting contract require that minted amounts inherit a P2SH contract
Requires special fees to transfer? Y N N
Requires additional event-handling logic to track transfers? Y N N
Supports non-fungible tokens? N Y Y
Human readable metadata Provided by the operating smart contract Provided by the off-chain metadata server Provided by the off-chain metadata server; Metadata updating/locking contracts possible

Note: table adapted from here.

Industry Acceptance

Cardano

Cardano blockchain provides native tokens which can be used in contracts.

Native tokens behave the same as ada in most ways. However, Ada is the “principal” currency of Cardano, and is the only one which can be used for some special purposes, such as paying fees.

Ada Native tokens Comment
Can be sent in transactions Y Y
Can be kept in UTXO outputs Y Y
Can be locked with script outputs Y Y
Can be sent to an exchange address Y Y
Can be minted/burned N Y Ada cannot be created or destroyed, its policy ID does not correspond to a script
Can be used to pay fees, receive rewards, etc. Y N Ada is the only currency which can be used for fees and rewards.
Can be used to cover the minimum UTXO value Y N Ada is the only currency which can be used for deposits.

Link to source.

The same table could be used to summarize proposed Bitcoin Cash native tokens, simply by swapping ADA with BCH.

IOTA

The proposed IOTA tokenization is a functional subset of this proposal, but notably uses the exact same technique of annotating UTXOs with token identifiers.

ION

ION tokens are ported directly from Andrew Stone's Group Tokenization work, which is an ancestor of this proposal.

Blockstream Liquid

"Confidental Assets" uses the same general approach of "...attaching to each output an asset tag identifying the type of that asset, and having verifiers check that the verification equation holds for subsets of the transaction which have only a single asset type."

Discussions

[Back to Contents]

Statements

[Back to Contents]

A lot of work and research has gone into the technical specification of this CHIP. However, in its current form, GP does not think it is simple / minimal enough to be considered for acceptance into the network. Furthermore, important sections about costs, risks and alternatives are incomplete or have wrongfully been asserted as non-existent. GP would like to see a minimum viable change isolated from the current large scope, and then a deeper evaluation of costs, risks and alternatives.

<a href="https://read.cash/@GeneralProtocols/general-protocols-statement-on-chip-2021-02-group-tokenization-for-bitcoin-cash-e7df47a0"><p align="right">2021-04-02, General Protocols, General Protocols Statement on "CHIP-2021-02 Group Tokenization for Bitcoin Cash"

</a>

GROUP tokens are by far the most streamlined proposal to achieving token-supported covenants which could definitely help Bitcoin Cash unlocking its potential to mass adoption. Group tokens are not only needed for gaining user adoption, but also developer adoption. Builders need more scripting capabilities to building meaningful dapps of which Group proposal could definitely contribute to.

<a href="https://youtu.be/f9wTZzNk1ro?t=4319"><p align="right">2021-04-05, Burak, SwapCash

</a>

As a developer and co-founder of Mint SLP https://mintslp.com/

I believe miner validated tokens is a smart step in the right direction! The Group Token proposal seems like a big improvement over SLP.

Thank you @andrewstone and others involved for working on and pushing this feature into BCH.

I hope the community can come together to support the Group Token proposal or something similar! You have my support for what it is worth!

<a href="https://bitcoincashresearch.org/t/chip-2021-02-group-tokenization-for-bitcoin-cash/311/29?u=bitcoincashautist" align=right><p align="right">2021-04-06, MaxHastings, Mint Slp

</a>

Changelog

[Back to Contents]

This section summarizes the evolution of this document.

Note that, through interaction with various stakeholders of the Bitcoin Cash ecosystem, this proposal has significantly deviated from past versions which were made to match Andrew Stone's original proposal titled: Group Tokenization.

The first version of this CHIP was created to capture that proposal and was naturally named after that. It has since the title two times to better match the technology it describes:

  1. Group Tokenization For Bitcoin Cash
  2. Unforgeable Groups for Bitcoin Cash
  3. Unforgeable Categories for Bitcoin Cash

Shortly after v6.0 release of this proposal, another proposal, CHIP-2022-02-CashTokens: Token Primitives for Bitcoin Cash, was released by Jason Dreyzehner.

From that point, this proposal started moving in direction of converging on a solution to be finally activated on the Bitcoin Cash network, by implementing revelations found in CashTokens and with the ultimate goal of merging the two proposals to enable token primitives for Bitcoin Cash.

The key revelation of CashTokens was that non-fungible tokens (NFTs) and fungible tokens (FTs) must be allowed to independently exist within the same group because NFTs are more than FTs with amount=1 and fundamental use of NFTs is as messengers between smart contracts.

2022-06-19 8.0 Unforgeable Categories: Native Token Primitives for Bitcoin Cash

  • Complete merging 2 CHIPs into 1 by harmonizing naming
  • Improve signature specification
  • Complete all sections (ongoing)

2022-06-05 7.0 Native Token Primitives

  • Converge towards "CHIP-2022-02-CashTokens: Token Primitives for Bitcoin Cash" by implementing its NFT approach
  • Repurpose groupType to groupOutputType
  • Allow groups to have both NFTs and FTs under the same groupID
  • Allow grouped outputs to encode FTs, an NFT, or both
  • Implement NFT sub-types
  • Allow NFTs to carry a 0-40 byte message
  • Functionally matches CashTokens 2.0, main difference is the genesis setup, and a minor difference is output encoding

2022-02-28 e148a4dc 6.1 Fungible Tokens

  • Acknowledge existence of "CHIP-2022-02-CashTokens: Token Primitives for Bitcoin Cash" and start working towards merging the two proposals
  • Extract groupType to its own field to enable signing group genesis from the redeem Script without the problem of malleating the nonce
  • Align groupType with CT2.0
  • Remove singularity amount overload, entire fungible token supply of the group must be minted at genesis
  • Modify genesis - prevout hash now optional

2022-02-21 f11857a5 6.0 Explicit Genesis

  • Whole new approach to group genesis: instead of inferring it from the TX, it will be explicitly declared as an input prefix that can use the same byte because it will be exclusive to input context.
  • One more introspection opcode to access the genesis input's generated groupID preimage.
  • Change group amount format from VarInt to fixed width uint.

2022-02-12 7fd63e09 5.0 Simplify the spec, CHIP sections

  • NFT and satoshi tokens group types dropped.
  • Only native tokens group type is allowed.
  • Genesis simplified.
  • Removed the examples appendix.

2022-01-25 09e93d79 4.3 Spec tweaks, CHIP sections

  • Remove the groupAmount == 1 requirement for satoshi tokens so contracts can make use of the free groupAmount field.
  • Tweak group introspection opcodes so we can use them to check for groupAmount existence.
  • Tweak "singularity" amount encoding and with that limit the groupAmount range to match script numbers range.
  • Remove option to change TX format.
  • Remove NFT | HAS_AMOUNT group flag combination, keep it reserved for a more versatile NFT upgrade.
  • Change groupType to 1 byte width, define a flag to extend it to 2 bytes if needed.
  • Sighash and genesis preimage tweaks: mask genesis generated bits instead of omitting them.
  • Genesis now increments SigChecks counter.
  • Big update to CHIP outline and sections, mainly costs and evaluation of alternatives sections.

2021-12-21 5b10c05b 4.2 Tweak GENESIS preimage

2021-12-08 3090f8a2 4.1 Tweak GENESIS and add NFT group flag

  • Add a NFT group flag so we can have NFTs that carry some state
  • Tweak GENESIS to compress each input in the preimage
  • Add PMv3 GENESIS and SIGHASH sections
  • Wording

2021-11-29 b96c2f35 4.0 Unforgeable Groups

  • Simplified the output format and consensus layer
  • Generalized output groups as "carried digest", having only the GENESIS rule enforced
  • Group amount field is now optional and indicated using the LSB of groupID so the whole group must have or not have it
  • Native token groups and Satoshi token groups (aka "holds BCH") are then a more restricted variant of a generalized group, having token logic enforced over respective amount fields, and NFT logic enforced over amountless token groups.
  • 0-amount indicates "singularity", i.e. an infinite source or an infinite sink which allows token amount creation and destruction
  • Any advanced features, such as metadata updating, are to be implemented using unforgeable Script covenants, as demonstrated in the examples section
  • Reworked CHIP sections

2021-11-11 2904667d 3.1 Sections Overhaul

  • Added back MELT and infinite MINT
  • Tweaked authority-type NFTs
  • Tweaked the tokenID preimage to enable Script covenants
  • Renamed "baton" back to "authority", renamed metadata LOCK_X to EDIT_X
  • Reworked CHIP sections: made motivation more concise, added intro section intended for wider audience, added contents, changelog, reworked technical description, updated examples, added example Script covenant contract...

2021-05-09 8c9cb4a2 3.0 One Token Standard

  • Result of brainstorming with Emil Oldenburg
  • Authority system restricted to exactly one UTXO per token
  • Introduced metadata locks

2021-04-17 4be89a3b 2.0 Full Overhaul

  • Original scope sliced down in response to feedback received
  • All advanced features removed
  • Reworked technical description to flow better
  • Included group consensus rules flowchart

2021-03-14 fa4964d2 1.1 Completed the First Draft

  • Copied Andrew Stone's specification into the CHIP body.
  • Reworked technical description to include advanced Group features: subgroups, hold BCH, and covenant.

2021-02-23 646232cc 1.0 First Draft, CHIP published on Bitcoin Cash Research forum

  • CHIP created to describe Andrew Stone's original specification.
  • First draft technical description incomplete, introduced only the token transfer, authority, and genesis features.

[Back to Contents]

To the extent possible under law, this work has waived all copyright and related or neighboring rights to this work under CC0.

Credits

[Back to Contents]

Satoshi Nakamoto, invention of Bitcoin: A Peer-to-Peer Electronic Cash System.
Andrew Stone, authoring the original Group Tokenization proposal and full showcase implementation, which was used as genesis of this CHIP.
Jason Dreyzehner, authoring the CashTokens 2.0 proposal, which got integrated into this CHIP.

The CHIP is really authored by everyone who's interacted with it. The owner would like to personally thank:

  • Andrew Stone, for inspiration, being supportive of the initial CHIP versions, and private consultations,
  • Thomas Zander, for inspiration, being the "first responder" to the proposal, and helping the owner realize importance of attention to details and their impact on the full product, and first introducing the idea of setting the category ID to match genesis transaction TXID.
  • matricz, for the inspiring post on how decentralized cooperation should work,
  • imaginary_username, for looking at it with a critical mind and helping the owner find a better way forward,
  • BigBlockIfTrue, for early interaction with the proposal and explaining to the owner nuances of locking and unlocking script,
  • emergent_reasons, for setting the bar high for CHIPs and asking for steel-man arguments,
  • Calin Culianu, for kicking the CHIP into higher gear with the PFX approach,
  • Emil Oldenburg, for having the patience to help the owner see the advantage of having a single authority and enforcing metadata locks,
  • Jason Dreyzehner, for breakthrough revelation with CashTokens 2.0: that of fundamental differences between fungible and non-fungible tokens,

and everyone else who interacted with this proposal and by doing so helped bring it to the level where it currently is:

Sorted alphabetically: AsashoryuMaryBerry, Burak, Estebansaa, FerriestaPatronum, Fixthetracking, Freedom-phoenix, Freetrader, George Donelly, Jonathan Silverblood, Licho, Marc De Mesel, MobTwo, Mr. Korrupto, Saddit42, Shadow Of Harbringer, Supremelummox, Tl121, Tula_s, Twoethy.

If we forgot someone, please let us know!