Only this pageAll pages
Powered by GitBook
1 of 49

RGB Blackpaper

Loading...

General information

Loading...

Loading...

Loading...

Loading...

Loading...

Loading...

Consensus layer

Loading...

Loading...

Loading...

Loading...

Loading...

3.3.2. Opret commitments

Loading...

Loading...

Loading...

4.1. Strict types system

4.2. AluVM virtual machine

Loading...

5.1. Schema

Loading...

5.3. Contract operations

Loading...

Application layer

Loading...

Loading...

Loading...

Loading...

Loading...

10.1. Bitcoin Finance (BiFi) on Lightning

10.2. Non-financial applications

Other information

Loading...

Loading...

Loading...

12. Protocol properties

12.1. Privacy

Loading...

Loading...

12.4. Global state & avaliability

Loading...

Loading...

Appendices

References

Appendix A: Related standards

Appendix B: Reference implementation

Appendix C: Glossary

RGB Blackpaper

Turing-complete, Scalable & Confidential Smart Contract Layer for Bitcoin & LN

Maxim Orlovsky 1,2; Peter Todd 1; Giacomo Zucco 1; Federico Tenga 3; Olga Ukolova 1,2

1.LNP/BP Standards Association

2.Pandora Prime

3.iFinex Inc

Abstract

This paper proposes a novel β€œpost-blockchain” smart contract system, named RGB. It is based on the concept of client-side-validation, separating contract state and operations from the consensus level. With this approach, contracts are sharded (each contract is a standalone shard), kept and validated only by contract participants, bringing native privacy and scalability mechanism, exceeding abilities of all existing blockchain-based smart contracts while not compromising on security or decentralization. RGB as a smart contract system doesn’t require any specific token/coin to operate and is implemented on top of bitcoin blockchain, as the most secure decentralized system. It also can operate on top of layer-2 protocols, such as sidechains, lightning network and other future protocols. It is fully compatible with all existing bitcoin technologies (scriptless scripts, DLCs, atomic swaps) and future possible bitcoin softforks and doesn’t require any changes to the base bitcoin layer. RGB uses specially-designed functional registry-based RISC virtual machine AluVM, which is Turing-equivalent* and is able to operate global state with the same availability guarantees as with existing blockchain-based systems. RGB has a strong privacy-preserving emphasize, using modified form of Blockstream’s confidential transaction technology (based on Pedersen commitments, enhanced with Bulletproofs++ range proofs) and cryptographic hash concealments for non-fungible state, such that even contract participants do not see full information about past contract history - while still be able to validate it. The paper presents an initial implementation of RGB technology and discusses possible applications of it for building rich, private, scalable and censorship-resistant applications on top of bitcoin and lightning network, including bitcoin finance (β€œBiFi”) and non-financial forms of smart contracts.

* in the same terms as EVM and WASM-based smart contracts, i.e. nearly computationally universal, bound by number of operation steps, measured by gas consumption in Ethereum-like systems, and by accumulated computational complexity measure in case of AluVM.

2.1. Design goals

The smart contract system proposed in this work is designed according to the following criteria:

Scalability, achieved at multiple layers: ability to scale in terms of data size due to client-side-validations; ability to scale in terms of transaction throughput due to lightning network compatibility.

Strong ownership: smart contract operates "owned state" which have a well-defined owner(s). Nobody except this owner(s) can update the state of the contract. Contracts always define types of rights as a set of operations which may be performed over the contract and these rights are assigned to be either "public" or "owned", utilizing right-specific validation logic.

Confidentiality: data should be known only to contract participants, namely state owners, unless they decide to make them public (disclose). All parts of the protocol must be protected from tools like chain analysis and the protocol should not store any information in the public ledgers.

Separation of concerns: the protocols must be designed in a modular and layered way, where each module solves one and only one task. The layers must be well abstracted, meaning that the layers below must be unaware of the structure of the layers above. Such separation of concerns provides a foundation for the protocol interoperability, security, composability and forward-compatibility.

Extensibility: it must be possible to create advanced forms of smart contracts without the need to change the core of the protocol or add code & recompile RGB libraries.

LNP/BP interoperability: RGB must work well with all existing bitcoin and lightning technologies and be compatible with possible future upgrades.

Determinism: the RGB validation logic must be deterministic in a sense that giving the provided set of inputs and the state of commitment layer (blockchain or lightning channel) it always produces the same result independently of the used platform or linked libraries. This is achieved by two main components: (1) the core of the validation logic generic to all contracts is implemented in rust language and must be used from any system running RGB using language bindings, (2) all contract-specific validation logic runs on – a highly deterministic functional virtual machine providing platform-independent instruction set.

AluVM

1. Introduction

This document is targeting technical readers, who would like to understand, audit, extend or build new applied tech with RGB. The document presents an explanation of design principles and provides deep technical insights into how RGB system is structured and works. It is not a formal RGB specification, however the information is based on underlying standards defining parts of the RGB protocol and related technologies.

LNPBPs

2. Protocol design

RGB is a suite of protocols for scalable & confidential smart contracts for Bitcoin & Lightning Network. It embraces the concepts of private & mutual ownership, abstraction and separation of concerns and represents "post-blockchain", Turing-complete form of trustless distributed computing which does not require introduction of "tokens".

3.1. Proof of publication

Client-side-validation is the paradigm proposed by Peter Todd in 2016. Its core idea is the fact that the validation of a state in a distributed system doesn’t need to be performed globally by all parties participating a decentralized protocol; instead, only parties invloved in a specific state transition need to do the validation. With this approach, the state transition, instead of being published into a global network, is convolved into a short cryptographic commitment (for instance, by utilizing cryptographic hash functions), which needs to become a part of a certain β€œproof-of-publication” medium, exhibiting three main qualities:

  1. Proof of receipt: ability to proof that each member of some audience has received a message (like commitment); β€œa real world analogy is a legal notice being published in a major newspaper - we can assume any subscriber received the message and had a chance to read it.” - writes Peter Todd […],

  2. Proof of non-publication: ability to proof that some specific message was never published; β€œExtending the above real world analogy the court can easily determine that a legal notice was not published when it should have been by examining newspaper archives. (or equally, because the notice had not been published, some action a litigant had taken was permissible)” [ibid]

  3. Proof of membership: ability to proof that some member indeed participates in some audience. β€œIn the case of our newspaper analogy because we know what today’s date is, and we trust the newspaper never to publish two different editions with the same date we can be certain we have searched all possible issues where the legal notice may have been published.” [ibid]

The first client-side-validation system was the OpenTimeStamps protocol, again, proposed and developed by Peter Todd in 2014-2016

3.3. Deterministic bitcoin commitments

Deterministic bitcoin commitments (DBC) provide a way to create provably unique commitments inside bitcoin transactions. RGB protocol allows two types of DBC: based on taproot outputs (so-called β€œtapret”) and based on OP_RETURN outputs (so-called β€œopret”), useful for old hardware which doesn’t support taproot.

3.3.1. Tapret commitments

Tapret commitment is structured as an OP_RETURN-based script, containing the multi-protocol commitment, placed inside an unspendable script path within taproot script tree. Thus, the script/commitment is never exposed to the external world inside bitcoin transaction or blockchain data (neither in script output nor witness); and only scriptPubkey of the transaction output contains a commitment to the actual tapret data created with the standard taproot procedure defined by BIP-341.

The tapret commitment script (tapret leaf script) always consists of 64 bytes: this allows distinguishing of tapret leaf script from a data used in production of taproot branch hash, such that the proof of the absence of an alternative tapret commitment can be validated by simple comparison of the first of the child node hashes to the tapret leaf script prefix.

The leaf with the tapret leaf script is always put into a leaf the same depth of the taproot script tree, and this depth is 1 (in 0-based indexing of depth levels, where depth 0 corresponds to the merkle tree root). The commitment is always put into the rightmost node of the tree by using consensus ordering of the nodes, as it is defined in BIP-341 merkle path construction (lexicographic ordering). This precise definition of the possible place of the commitment allows to prove the uniqueness of the commitment, i.e. the absence of any alternative tapret commitment in the same tree.

If at depth 1 in the rightmost position of the tree another taproot node is present (either leaf script or branch), an additional branch node is created with both tapret leaf script and the parent of the rightmost depth-1 node becoming its children.

If the original taproot script tree does not have depth 1 nodes on its right-side (in terms of consensus lexicographic ordering of each branch child hashes), a subtree (tapret subtree) consisting of repeated tapret script leaves is created and inserted at the depth of the last node of the tree on the right-side merkle path. The height of the subtree is selected to put the taproot script leaves at depth 1.

Since addition of the new node will change the merkle hashes of all its parents, and the merkle hash value is used in the lexicographic ordering of the tree, this operation with 1 - 1/(2 ^ 1) = 50% probability will make just inserted tapret subtree merkle root to be non-rightmost node of the modified tree. Since the deterministic nature of the tapret commitments requires ability to prove the absence of any alternative commitment in the same tree, two components are used to keep the determinism of the commitment position and ability to prove its uniqueness.

First, a special one-byte variable (nonce) is added to the taproot leaf script, which allows "mining" the hash value in a way that the added subtree will appear at the right-side of the tree. At depth 1 there might be only 2 possible tree position, and 256 iterations (per one nonce value) should be enough to solve the issue.

Second, if it was not possible to solve the issue with the nonce, a special uniqueness proof is produced, which ensures that none of the nodes at depth 1 on the right side of the tree does not contain alternative commitment. This proof includes leaf script (for leaf nodes) or two child node hashes (for branch nodes) for each of the nodes right to the tapret leaf script.

The tapret commitment is put into a transaction output scriptPubkey as a modified BIP-341 output key value, which is produced from the same internal key and new merkle root of the taproot script tree containing the embedded tapret commitment. The number of the transaction output with the commitment, if multiple taproot outputs are present in the same transaction, must be deterministically defined by an upper-level protocol using the present tapret commitment scheme.

Internal key value, merkle proof and uniqueness proof are combined to construct tapret proof, passed to the validators as off-chain data for client-side validation.

1.2. Background

Distributed protocols, like bitcoin, or more complex smart contract systems, need a way to synchronize the state across all parties that participate in the protocol. Thus, operations under such a protocol must be organized in atomic transactions (or, more generally, state transitions) - and the sequence in which these operations are applied to an initial (genesis) state must be clearly defined. The rule of the ordering is named consensus rule, and the protocol that has a well-defined consensus rule is named consensus protocol.

Blockchain originated as a specific form utilized by distributed protocols (initially bitcoin) which combined consensus mechanism with actual operations (transactions, in case of bitcoin), organized into a time-ordered chain (i.e. sequence), named ledger. Thus, bitcoin blockchain is a consensus (PoW Nakamoto consensus) plus transaction ledger, whose finality and ordering is maintained by that consensus. The same applies to most of other existing blockchains.

It is quite clear that the main value for a distributed system is maintaining the consensus - event ordering - and not keeping the data of the actual events. Instead, it is sufficient to have a way for consensus layer to keep only short cryptographic commits to the ledger events, keeping/storing the actual event information (ledger) outside of the blockchain. This approach originates from the works of Peter Todd where he names it β€œclient-side-validation”. It solves two major issues specific to any blockchain: scalability in terms of the size of the data kept onchain, and privacy, where both the transaction graph and actual transactions data are publicly known. With client-side-validation we can again use blockchain for the single task it does well: consensus, moving the idea of keeping a ledger of transactions into the oblivion it deserves.

3. Client-side-validation

The topics discussed in this chapter are not specific to RGB smart contracts design and can be leveraged and used by other protocols, all of which would form a family of client-side-validation protocols. One may see OpenTimeStamps as the first of the protocols in this sphere, with RGB being the second *.

* other teams taking RGB ideas, sometimes β€œforgetting” to reference to their origin β€” like Lightning Labs with their CMYK protocol, later renamed into β€œTaro” β€” are de facto using fruits of the client-side-validation development efforts over half of decade, fundraising on simplified and restricted versions of the work made by others.

3.2. Single-use-seals

This proof of publication medium can be of a different nature, including centralized forms, like a newspaper from the example in previous chapter. However, in RGB we are interested only in using decentralized medium, which has to be censorship-resistant, like a bitcoin blockchain – and we need a form of cryptographic commitment which can achieve the properties of proof-of-publication. This form was, again, proposed by Peter Todd as a β€œsingle-use-seal”: a commitment to make a future commitment such that it can be proven that no alternative commitment can be ever created.

Existing cryptographic commitment primitives does not allow to create "two-level" commitments, whether at initial stage a committer commits to commit to a certain (potentially yet unknown) message in the future, once and only once. Given a trustless way of performing verification of such commitments the primitive may be a basic building block for creating decentralized, private and censorship-resistant state machines and smart contracting systems which will be protected from "double-spend" attacks. Analogous to the real-world, physical, single-use-seals used to secure shipping containers, a single-use-seal primitive is a unique object that can be closed over a message exactly once. In short, a single-use-seal is an abstract mechanism to prevent double-spends.****

Single-use-seal cryptographic primitive was proposed by Peter Todd in 2016 as an abstract concept developing idea of timestamps further. LNP/BP Standards Association have developed an application of the single-use-seals to bitcoin transactions, which allows multiple independent protocols to use the same transactions for the single-use-seal operations without knowledge of each other. This construction is called β€œdeterministic bitcoin commitments” and is defined in a series of LNPBP standards (___).

  1. not be able to detect the presence of the commitment in a given transaction graph (hiding property of TxO seals) even if the original message is known,

The defined procedure is not the only way in which bitcoin blockchain or transaction graph can be used as a seal medium for single-use seals (for instance, a seal may be defined as a first time some specific public key appears in the blockchain); however these options are not part of the current standard.

Witness transaction: transaction spending an output specified by a given seal.

Closed seal: a seal for which a transaction spending output matching seal definition is known. This transaction MAY be part of longest block chain, or MAY not be a part of it (existing only within a Lightning network channel or as a part of any other off-chain transaction graph). It's up to particular implementation to decide whether such transaction (named witness transaction) should be considered valid or not; however this rules MUST require that the witness transaction MUST be a valid bitcoin transaction (i.e. it can be validated with libbitcoinconsensus or Bitcoin Core instance).

Defined seal consists of 256-bit consensus-defined double SHA-256 hash of a fully-signed valid bitcoin transaction (transaction identifier, β€œtxid”) and 32-bit transaction output index. The transaction identifier may be skipped if a new seal is defined within the witness transaction closing another seal, such that the txid is not known; however in such case protocols (like RGB) must provide guarantees that the witness transaction is deterministically and non-ambigius defined.

Seal must be considered defined only and only all of transaction data are known, the transaction is fully signed and both transaction structure and signatures validated with bitcoin consensus rules using Bitcoin Core β€” or is a part of most recent signed state of a state channel (like in Lightning Network, using trusted lightning node).

Briefly, bitcoin transaction output-based single-use-seals (TxO seals) is a particular application of to bitcoin transaction graph, either as a part of any bitcoin blockchain (longest PoW chain, federated sidechain etc) or state channel (Lightning network channel and other types of state channels), i.e. in terms of single-use-seals, seal medium is represented by a bitcoin transaction graph.

The parties running protocol agree on some transaction output in any given bitcoin transaction graph as a place with special meaning ("seal"), and require that a future transaction spending this output ("witness transaction") contained a to some a message. Any independent party having access to the transaction graph MUST:

being provided information about specific protocol used for message commitments and access to deterministic bitcoin proof data (see ) be able to verify the commitment such as it will be valid only and only for the message with which the original commitment was created (verifiably property of TxOSUS).

Seal or defined seal: Bitcoin transaction outpoint: a combination of transaction identifier (consensus-defined double SHA256 hash of fully-signed valid bitcoin transaction) and transaction output number. Transaction output number MUST be represented as a 32-bit unsigned integer.

single-use-seals
deterministic bitcoin commitment
LNPBP-8
1

1.1. Motivation

The idea of smart contracts, originating from Nick Szabo, remains an inspiration for an almost a generation of innovators. However its promises to become a foundation for technically-guaranteed agorism, anarcho-capitalism and cryptoanarchism were never fulfilled - since all l existing systems claiming to be β€œsmart contract platforms” so far fail to deliver required properties of the smart contract trilemma:

  1. Be scalable

  2. Has sufficient programmability (be nearly-equivalent to a universal Turing machine)

  3. Be decentralized and censorship-resistant

The last decade the joint work of a number of cryptographic researches and cypherpunk thinkers has brought a new foundations which can be utilized in achieving the goal. This includes concepts of client-side-validation and single-use-seals by Peter Todd and client-validated β€œcolored coins” of Giacomo Zucco able to operate as a scalable layer on top of bitcoin and lightning network. In this proposal we merge this ideas with prominent privacy-preserving tech (confidential transactions by Blockstream, enhanced with Bulletproofs++ range proofs) and novel concepts of partially-replicated state machines, functional confined type system and registry-based virtual machine developed by me in UBIDECO Institute to create a new programmable, secure, privacy-preserving, censorship-resistant and scalable smart contract system called RGB.

2.2. Design overview

The RGB smart contract system operates on multiple levels, abstracted from each other.

RGB smart contracts operate with client-side validation paradigm, meaning that all data is kept outside of bitcoin transactions, i.e. bitcoin blockchain or lightning channel state. This allows the system to operate on top of the Lightning Network and also gives a foundation for a high level of protocol scalability and privacy.

The base level of RGB is bitcoin blockchain, including both Nakamoto PoW consensus and transaction ledger: while we do not require to store any data outside of cryptographic commitment on-chain, we still have to follow existing infrastructure and re-utilize bitcoin transactions as a storage for those commitments. This is done with other bitcoin protocol layers on top, creating the foundation of client-side-validation: deterministic bitcoin commitments, single-use-seals and multi-protocol commitments. While used by RGB, these protocols are not RGB-specific and designed to allow RGB to work together without collisions with other (future) protocols utilizing client-side-validation paradigm.

As a security mechanism RGB uses single-use seals defined over bitcoin transaction outputs, which provides ability for any party having a smart contract state history to verify its uniqueness. In other words, RGB leverages Bitcoin script for its security model and definition of the ownership and access rights.

Additionally to the aforementioned set of bitcoin protocols providing foundations for the client-side-validation, RGB smart contracts are also based on ubiquitous deterministic computing, including strict types and AluVM, utilized by RGB schema: a set of rules defining how smart contracts can evolve over time and how they are validated on the client-side. Taken together these layers enable the core consensus-level functionality of RGB contracts, on top of which a set of contract interfaces is defined to allow applications to interact with the contracts. Lightning channels, operating (some) of RGB contract state, as well as more complex applications, including DEX and decentralized data network are built using those interfaces.

Each RGB smart contract is represented by some genesis state, created by smart contract issuer (or, put simply, issuer) and a directed acyclic graph (DAG) of state transitions kept in form of client-validated data (i.e. this data is not stored on the blockchain or within LN transactions/channel state). The state is assigned to unspent bitcoin transaction outputs, which defines them as single-use seals. The party that is able to spend corresponding transaction output is named a party owning a state: it is a party that has the right to change the corresponding part of the smart contract state by creating a new state transition and committing to it in a transaction spending the output containing a previous state. This procedure represents closing of a seal, and a pair of spending transaction and corresponding extra-transaction data on the state transition are named witness.

State transition assigns state to a set of defined single-use seals. Each smart contract may maintain different forms of state and define different kinds of single-use seals with different validation rules. Additionally to this, state transition may define different global state and contain metadata, used by schema scripts during state transition validation on AluVM.

Which types of global and owned state, seals, metadata are allowed within state transitions is defined by schema. Thus, schema can be seen as set of validation rules for client-side validation; schema is always defined by the issuer in state genesis. Schema also may contain Turing-complete scripts defining parts of the business logic for client-side validation.

RGB operates in β€œshards”, where each contract has a separate state history and data; different smart contracts never directly intersect in their histories. This allows another level of scalability; and while the term β€œshard” is incorrect, we use it to demonstrate that RGB actually achieves what was planned to be achieved with β€œEthereum shards”.

While being separately maintained, RGB contracts may interact via Bifrost protocol over the Lightning Network, allowing multiparty coordinated state changes, which, for instance, enables functionality like DEX over Lightning etc.

Thus, by their abilities RGB smart contracts go beyond what is possible with Ethereum-like smart contract system, providing more layered, scalable, private and safe approach, where the ownership of a smart contract state is separated from the smart contract creation.

As a smart contract system RGB is quite different from previous approaches, both Bitcoin-based (Colored coins, Counterparty, OMNI) and non-bitcoin (Ethereum, EOS and others):

  • RGB separates concept of smart contract issuer, state owners and state evolution

  • RGB keeps the smart contract code and data off-chain

  • RGB uses blockchain as a state commitment layer and Bitcoin script as an ownership control system; while smart contract evolution is defined by an off-chain schema

4. Ubiquitous deterministic computin

5. Contracts, state & operations

RGB contracts are bearer agreements which are being maintained independently of each other.

Each user has a partial view on the contract state.

Contract state forms: owned and global

Types of contract state. Data type system. Formal verifiability.

Definition of a contract. Interfaces, Schemata, Genesis.

State transitions.

State extensions (β€œdecentralized genesis”). The way they work.

RGB smart contract defines state, owners of that state, and operations, which participants of the contract (owners and sometimes more broad public) can execute to update the state.

Operations include genesis operation (issuance of the contract), state transitions updating the existing state (or adding to the state data) and state extension, which represent a mechanism how anybody (public) can participate in the contract operations.

State of the contract consists of state atoms of different data types. Data types are defined in the same terms as variable types in any structural language (C, Rust, Haskell, etc).

RGB contract always have a well-defined parties of the contract, which hold ownership rights over atoms of state. The state owned by a contract party is called owned state.

Let's start with writing a simple contract managing decentralized identity backed by a PGP key. The "smartness" of the contract (comparing to normal PGP/GPG and Web of Trust) comes from the fact that when a revocation operation is executed, everybody in the world will know about it (since they can see that the UTXO, associated with the key -- the owned state -- was spent), and it can be proven whether at any given moment of time the identity was valid -- or it was already revoked.

5.5. Availability of the global state

3.3.3. Deterministic output selection

3.4. Multi-protocol commitments

There could be two different protocols willing to put different commitments into a single transaction output; and only one of the protocols may succeed since a transaction can contain only a single commitment. It is also possible that some protocol may require committing to a number of messages within a single transaction and public key with the requirement that some dedicated information from these messages (like the message type) should be unique across the whole message set. For instance, this is required for the state updates, where such updates separated into different blocks (messages) and should be kept private, such that a single party will know the information about a single update and should not see any information about the rest. However, in this case, there should be a proof that the other state updates do not affect the state of the analyzed one, thus excluding state collisions. In such a setup, each state may be assigned with a unique integer identifier (like cryptographic digest), and a special form of zero-knowledge proof should be utilized to prove the fact that all the states are different without exposing the actual state ids.

While both cases are impossible at the level of deterministic bitcoin commitment standards, a dedicated procedure for structuring multiple independent messages was proposed, named β€œmulti-protocol commitments”. With it, some properties of the committed messages may be proven in a zero-knowledge way, i.e. without revealing any information about the source messages or the properties themselves.

Multiple commitments under different protocols are identified with a unique per-protocol 256-bit identifiers (like tagged hashes of a protocol name and/or characteristic parameters) and serialized into 256-bit slots within N * 32 byte buffer such as N >> M, where M is the number of the individual commitments. The rest of the slots is filled with random data deterministically generated from a single entropy source. The position n for a commitment with the identifier id is computed as n = id mod N, guaranteeing that no two commitments under the same protocol with a given id may be simultaneously present.

5.2. Contract state

5.4. Contract validation

8. P2P communications

Includes information about Consignments etc

7. Interacting with contracts

But how the wallet makes the sense of the contract? RGB contract can do a lot of things, and if schema developers would need to do a separate wallet for each schema the entrance threshold would be too high. To avoid such situation a concept of contract interface was created. A contract interface is a standard way communicating with RGB Node asking it for a semantically-meaningful state and creating operations. Such concept of interface is similar to the concept of ERC standards and ABI files in Ethereum world; the most common interfaces are called "RGBxx" and are defined as a separate LNP/BP standards.

Here, instead of using existing interface standards we will create an interface for a generic fungible token from scratch to explain the way they work:

interface FungibleToken:
   global Ticker -> String -- this is similar to schema definition; in fact
                           -- it is a requirement that the schema must provide
                           -- a global state of the String type and link it to
                           -- the "Ticker" name
   global Name -> String

   owned Inflation :: Zk64 -- pretty much the same applies to assigned state
   owned Asset :: Zk64

   op Issue :: Inflation -> [Asset]?, Inflation? -- and operations
   op Transfer :: {Asset} -> [Asset]

-- Specific schema state may use different naming, for instance because a
-- schema can define multiple assets with different names; in that case we
-- will have multiple interface implementations referencing different state.
implement FungibleToken for DecentralizedIdentity
   global Ticker := IOYTicker -- this creates a _binding_ of the state defined
                              -- in the schema (*IOYTicker* in this case) to
                              -- the interface
   global Name := IOYName
   owned Inflation := IOYIssue
   owned Asset := IOYTokens
   op Issue := Promise
   op Transfer -- here we skip `:=` part since the interface operation name
               -- matches the name used in the schema. In such cases we can
               -- also skip the declaration at whole

RGB smart contract can implement multiple interfaces. In our case it would be desirable to expose the identity information as well:

interface PgpIdentity
  owned Identity :: PgpKey
  exec Revocation :: old Identity -> new Identity

implement PgpIdentity for DecentralizedIdentity
  -- we do not need to put anything here since schema state and operation
  -- names matches interface requirements and the compiler is able to guess
  -- the bindings

6. Writing contracts. Scripting.

Contract business logic in RGB is defined through so-called schema; the specific RGB contract must implement some schema. One may think of a schema as a "class" definition in the OOP world; in that terms specific RGB contracts are "class instance" created by the schema constructor (genesis operation). Such approach allows to separate role of contract developer (in RGB called schema developer) and contract issuer: the first one needs to be an experienced developer, while the second one is not required to know anything about coding or security at all. This also promotes re-use of common codebase by different issuers for the same typical use cases (like fungible assets), reducing the risk of mistakes.

RGB uses specially-designed virtual machine AluVM, which is Turing-complete in the same terms as EVM and WASM-based smart contracts (i.e. nearly computational universal, but is bound by number of operation steps, measured by gas consumption in Ethereum-like systems, and by accumulated computational complexity measure in case of AluVM).

-- We have to start with definition of a data type representing
-- the key. This is not a part of the contract itself and may be
-- imported into multiple contracts from a _data type library_.
data PgpKey :: curve U8, key Bytes

schema DecentralizedIdentity
   -- This defines the atom of the contract state called `Identity`
   -- which has data type `PgpKey`.
   -- The `owned` keyword means that there is always a party
   -- which owns the identity
   owned Identity :: PgpKey
   -- an implicit part of the story is the fact that owned state
   -- is always assigned to a single-use-seal definition, so the
   -- proper way of writing the above statement will be
   owned Identity :: SingleUseSeal -> PgpKey
   -- but we leave the part which repeats for each and every owned
   -- state to reduce boilerplate of writing `SingleUseSeal ->`
   -- over and over again.

   -- This says that to construct contract the user must provide
   -- information about exactly one identity
   genesis :: Identity

   -- Now let's define what a owner of identity can do,
   -- He can execute his rights by creating state transitions
   -- ("operation" on the state) of predefined forms, like
   op Revocation :: old Identity -> new Identity
   -- which does what it says: it revokes existing identity
   -- and creates a new one.

The schema defines a rules of how the contract operates. Now let's put it into a practice by creating a specific identity contract, and then doing a revocation:

contract meSatoshiNakamoto implements DecentralizedIdentity
   -- this defines a genesis state and assigns it to a single-use-seal
   assign orig Identity := (0xfac503c4641c3deda72a2d00bc9d6ff1094b15276c386efea403746a91436772, 1)
                        -> PgpKey(0, 0x028730eeeec41802621d177507b086f390ae600ba3ca5e428b13913af4c2cd25b3)

transition iLostMyKey executes Revocation
   via meSatoshiNakamoto.orig -- specifies the single-use-seal we close to match requirements
                              -- on the valid operation execution conditions
   assign upd Identity := (~, 2) -- here we use txid of the bitcoin transaction which will be
                                 -- created to hold the commitment to this state transition,
                                 -- called "single-use-seal witness". Since we can not know the
                                 -- txid upfront we use ~ to indicate the witness transaction id
                       -> PgpKey(0, 0x0219db0a4e0eb8cb833608c08d76b9b279ec44a851ab82cc6fd68a9b32624bfa8b)
   -- the above defines new state and assigns it to a single-use-seal

Now, let's add some tokens to the contract, in form of "I owe you" obligations provided by the decentralized identity:

schema DecentralizedIdentity
   owned Identity :: PgpKey
   owned IOYIssue :: Zk64
   -- `Zk64` means 64-bit unsigned integer hidden with zero-knowledge
   owned IOYTokens :: Zk64

   global IOYTicker :: String
   global IOYName :: String

   genesis :: Identity, IOYTicker, IOYName

   op Revocation :: old Identity -> new Identity

   op Promise :: used IOYIssue -> given [IOYTokens]?, remaining IOYIssue?
      assert used == sum given + (remaining ?? 0)

   op Transfer :: spent {IOYTokens} -> received [IOYTokens]
      assert sum spent == sum received

Here we see multiple new things, let's try to explain them one by one.

First, it is the global keyword used to define asset ticker and name as two strings.

We already covered owned state composed of the rights holder and state atoms; but in some situations a contract needs a state which is "global" for the contract and is not "owned" by anyone (i.e. not assigned to a UTXO single-use-seal). The name of the asset (and ticker) is that sort of information: in the examples above it does not "belong" to a contract party but instead is a "property" of the contract itself. Another example could be the name of the identity holder which can't be changed and thus can't be assigned to a UTXO single-use-seal. Such state is defined with the global keyword.

It is important to note, that while the global state is not "directly owned" by any party, it still may be updated through state transitions -- but only if schema enables that explicitly. In such cases the use of the global state (as compared to the owned state) is reasonable only when the user may opt-out from future state updates (i.e. do not define a new single-use-seals) but still needs to keep the state. The asset name is again such an example, since even if the asset can be renamed, future renames after certain renaming may be prohibited (i.e. no new owned state can be created), but the asset name should stay. global allows exactly that.

Second, the use of braces, brackets and question mark around and next to the state name. Both braces and brackets mean that the operation works not with a single state atom, but instead an array (braces) or set (brackets) of state atoms. Set differs from an array in the fact that all elements of the set must be unique, while in array they may repeat. Coming back to our operations, asset transfer may spend a number of assets from different owners, but all of them must be unique (to prevent double-spend), i.e. form a set. However, when defining a receivers, multiple state atoms may be equal (i.e. you can send 10 tokens to the same UTXO N times, such that the receiver will get 10*N tokens in total, but through different "inputs", which may increase privacy).

Question mark is used to inform that the state may be absent, i.e. in case of array or set it can be empty - or in case of a single item, it is optional.

At the very beginning we had mentioned so-called state extensions. State extension can be created by anybody without doing an on-chain commitment (i.e. without closing any single-use-seals). In this it is similar to genesis. However, the state created by the extension is not "final" (compare to a non-mined transaction in the bitcoin mempool) until it gets included into a valid state transition (like transaction gets mined by being included into bitcoin valid block).

Probably the simplest way to understand state extensions is by example. Let's assume we'd like to do an asset which can be issued by anybody in the world through burning equivalent amount of bitcoins. Such operation can't be a state transition, since we do not have a predefined set of single-use-seals to define a "rights of issue" for an open and unknown set of participants. We can't also do "multiple geneses", since each genesis will define a new RGB contract and the assets under different RGB contracts are not fungible. State extensions were created exactly to address this issue. A contract using them may look in the following way:

-- We need some basic bitcoin-related types
-- We can do `import BP.{Utxo, RedeemScript, ...}`, but here we'd like to use
-- this opportunity to showcase how type definitions work
data Utxo :: Txid, vout U16
data Txid :: [Byte^32]
data RedeemScript :: Bytes
data CompressedPk :: [Byte^33]
data XonlyPk :: [Byte^32]
data OutputDescriptor :: Wpkh | Tr
data Wpkh :: CompressedPk
data Tr :: XOnlyPk

data ProofOfBurn ::
  burned Utxo,
  descriptor OutputDescriptor
  -- output descriptor is used to prove that the bitcoins can't be spent.
  -- in the validation logic below we define that PoB output must be either
  -- SegWit v0 WPKH or taproot output with a keypath-spending; in both cases
  -- the key given as a prove must be tweaked with its own hash, which will
  -- construct provably-unspendable key

schema RgbWrapBtc
  global Ticker :: String
  global Name :: String

  owned Value :: Zk64 -- the assets will be ownable and transferable as any
                      -- other fungible asset

  valency Burn -- the valency declares a possibility of the public
               -- participation in the contract logic.
               -- If the contract may have different forms of public
               -- participation, each of them must be declared first.

  genesis :: Ticker, Name, -- in genesis we can't issue anything, we just
                           -- declare specific name and ticker for our wrapped
                           -- bitcoin
             Burn -- we also say that the genesis allows state extensions to
                  -- be directly linked to the contract

  -- this is the state extension procedure: a "public" method of the contract
  -- which takes information about the proof of burn and allows to issue the
  -- wrapped bitcoins assigned to a single-use-seal(s), which are lately can
  -- be transferred with a usual state transition.
  public Issue :: Burn, proof ProofOfBurn -> issued [Value]
    -- here we verify that the UTXO input constructed with the key given in
    -- the proof according to the provably-unspent procedure exactly matches
    -- output existing onchain
    let spk' = match proof.descriptor
      Wpkh(pk) =>
        pk |>
        Hash.sha256 |>              -- h = Hash.sha256 pk
        SECP.gen |>                 -- tweak = SECP.gen h
        SECP.add pk |>              -- pk' = SECP.add pk, tweak
        Hash.hash160 |>             -- h' = Hash.hash160 pk''
        BP.wpkhScriptPubkey         -- BP.wpkhScriptPubkey h'
      Tr(xpk) =>
        xpk |>
        BIP340.selfTweak |>         -- xpk' = BIP340.selfTweak xpk
        BP.trScriptPubkey           -- BP.trScriptPubkey xpk'

    let spk = assert BP.readScriptPubkey proof.burned
    assert spk == spk'
    assert BP.notSpent proof.burned
    assert BP.value proof.burned == sum issued

  op Transfer :: spent {Value} -> received [Value]
    assert sum spent == sum received

9. Wallet interaction

Transferring a state involves several stages.

First, a wallet has to compose a PSBT file defining the structure of an underlying witness transaction.

Based on this PSBT, a list of spent outputs is passed to the RGB Node, given a specific contract id. The Node prepares a state transfer consignment, which contains the whole history for the spent outputs.

Next, RGB Node is asked to finalize the consignment and prepare a disclosure. It includes the following operations:

  • Extracting all other contracts affected by the operation; preparing "blank" state transitions for them;

  • Packing state transitions under the main contract with additional blank transitions under other affected contracts into an anchor;

  • Updating the consignment with the newly formed anchor and state transition;

  • Preparing a disclosure, that will contain the remaining blank state transitions. This disclosure will be used later for updating the stash when the witness transaction is mined.

This completes the composition of a new state transfer consignment and corresponding witness transaction. The consignment is sent to the beneficiary, who must return a signature on this transfer. Once the signature is received, the witness transaction from the PSBT should be signed by all signers and published to the network - and RGB Node in parallel should enclose previously prepared disclosure to maintain the state of the remaining smart contracts as valid.

This consignment is now used in transfer preparation, when based on the consignment file, PSBT, list of beneficiaries and available change addresses a (bundled) new state transition(s) for the state transfers are composed. This is performed not by an RGB Node but by a software/library, aware of the contract schema and semantics (assets, NFTs etc); i.e usually by a wallet using some schema-specific helper library, like .

RGB20

10. Possible applications

Bitcoin Finance:

  • Corporate/project tokenized shares, issued centrally, but traded in a decentralized way;

  • Loans and bonds, both centralized and decentralized;

  • Bitcoin and other assets with higher programmability and confidentiality, wrapped into RGB, issued in a decentralized way (but with a semi-federated pegout)

  • RGB-wrapped stablecoins, operating on the Lightning network as a means of payment; issued in a centralized or decentralized way

  • Decentralized exchange;

  • AMM solutions, for instance algorithmic overcollateralized stablecoins.

Non-financial applications:

  • Self-sovereign identity;

  • Decentralized global name registry;

  • Digital ownership right management systems;

  • Non-fungible collectibles and tokenized art;

  • DAOs;

  • Provable and verifiable audit logs.

11. Governance

To reduce the level of complexity and mitigate the risks of cross-dependencies RGB developers took a layered approach, building the technology in a modular way, where the modules are abstracted into different strata - such that the strata below know nothing about the strata above.

Overall, the development around RGB can be classified into the following fields, layered on top of each other:

Core protocol, or consensus-level development. You may think of it as of something which means the same thing for RGB as "Bitcoin Core" means for Bitcoin.

Toolchain development, which includes compilers, linkers, programming languagues and other tools. You may think of it as of Consensys company in Ethereum ecosystem.

  • Schemata development

  • Smart contracts issuance

  • Wallet, exchange and other software integration

Field of development
Overseen by
Developers
Main languagues

Core protocol

LNP/BP Standards Association

RGB core maintainers, but eventually ossified (i.e. no development activity)

Rust

Toolchain

LNP/BP Standards Association

Association & member companies

Rust

Schemata

LNP/BP Standards Association

Independent companies & developers

Contractum (alternatively, Rust)

Smart contracts

nobody

Issuers: independent companies, teams, DAOs, issuing assets & creating smart contracts

JSON & any languagues working with Web

Integration (wallets, exchange etc)

Integration standards proposed by LNP/BP Standards Asociation

Applied software companies: exchanges, wallet devs, outsourcers etc

JavaScript, TypeScript, Python, C, Java, Kotlin, Swift, Rust

Core protocol devs, upon final RGB/1 v1.0 release will perform only the bugfixing.

Toolchain development, managed and sponsored through LNP/BP Standards Association, will continue to produce and improve tools for other developer categories.

Schemata development consists of two main tasks:

  • Defining standards for API used in most common use cases.

  • Develop specific schemata, which may be seen as "RGB smart contract templates created by domain professionals".

The first case is covered by LNP/BP standards. Anybody can propose a new standard for a Schema (these standards are called "Schema (API) standards"). The standards are reviewed by the same process as any other LNP/BP standard, and are overseen by the LNP/BP Standards Association quite similar to how IETF oversees Internet standards (RFCs).

Development of a schema confirming to some, multiple, or even none of the Schema Standards can be performed by anybody, independently from the LNP/BP Standards Association or any other body. The only requirement is to unserstand how to develop a Schema and have the ability to write them using Contractum languague.

Due to using schemata, the development of actual smart contracts require no coders and conding: it comes down to the selection of a schema (or multiple schemata) which the contract must confirm to - and filling in the data specific to that schemata in pretty much the same way as filling in paper forms. This is done with some data-oriented languagues, like JSON, YAML, XML - or using some user interface tools supplied by LNP/BP Association or independent companies for existing schemata types (like fungible asstets, NFTs, identity etc).

LNP/BP Standards Association maintains , however any other body may create an independent registry, so multiple registries may co-exist. The process of adding an implementation to the LNP/BP registry is very simple: just submit a PR request providing all the necessary information about your schemata.

registry of the schemata

11.2. Ossification & upgradability

11.1. Organizations

12.3. Trust model

12.2. Censorship-resistance

12.5. Comparison to other systems

Parameter
RGB
Liquid
Ethereum, RSK etc
Stacks
CMYK ("Taro")

Native currency

βœ… BTC

⚠️ LBTC (federated peg)

🚫 ETH

🚫 ?

βœ… BTC

Requires token

βœ… No

βœ… No

🚫 Yes (except RSK)

🚫 Yes

βœ… No

Issues token

βœ… No

βœ… No

🚫 Yes

🚫 Yes

βœ… No

Gas

βœ… No

βœ… No

🚫 Yes

?

βœ… No

Non-token smart contracts

βœ…

🚫

βœ…

?

🚫

Data network for NFTs and attachments

βœ… Storm on LN paid in sats

🚫

⚠️ IPFS (no incentivation)

?

Unknown

Support for arbitrary structured data

βœ…

🚫

βœ…

🚫

🚫

Virtual machine

Bitcoin Script + AluVM

Bitcoin Script

EVM, sometimes EWASM

?

Bitcoin Script

Turing completeness

βœ…

🚫

βœ…

?

🚫

Separation of state from ownership

βœ…

🚫

🚫

🚫

βœ…

Client-side-validation (scalability & privacy)

βœ…

🚫

🚫

🚫

βœ…

Zero knowledge

βœ… Bullet proofs

βœ… Range proofs

⚠️ n/a, maybe STARKs

🚫

🚫

Breaks transaction graph & chainanal

βœ…

🚫

🚫

🚫

🚫

Released / used in production

βœ…

βœ…

βœ…

βœ…

🚫

13. History & acknowledgements

Many inputs into protocol design ideas and suggestions came from personal conversations of Dr Maxim Orlovsky and Giacomo Zucco with notable cryptographers, specialists on distributed systems and game theorists, including: Adam Back, Andrew Poelstra, Christian Decker, Christopher Allen, Pieter Wuille, Peter Todd, Rene Pickhardt.

We are thankful to the early adopters of RGB protocols, who invested and continue to invest into RGB integration and independent peer reviews: Bitfinex & Tether, inbitcoin, DIBA, SuredBits, Blockchain Of Things, Atomic Finance.

RGB was originally envisioned in 2016 by Giacomo Zucco (BHB Network) as a "non-blockchain based asset system" basing on earlier ideas of Peter Todd about client-side-validation and single-use-seals and implemented as original MVP around 2017 by BHB Network with support from Poseidon Group. Since 2019, Dr Maxim Orlovsky, Pandora Prime AG, acts as the main designer and lead contributor to the RGB protocol, designing and implementing it in its current form. Since 2019 RGB was restructured and re-thought from scratch as a generic form of computing and confidential smart contracting system. This development was managed by LNP/BP Standards Association, created in 2019 by Maxim Orlovsky & Giacomo Zucco and funded by iFinex Inc and Fulgur Ventures (2019H2-2020H1, 2022Q4-2023), Pandora Prime AG (2020H2-2021), personal funds of Dr Maxim Orlovsky (2020H2-2021, 2022H2), Hojo Foundation (2022-2023), DIBA Inc (2023) and anonymous community donations. A lot of input into RGB design, re-design and protocol peer-review came from a broader community, which included contributions from more than 50 people and organizations, including: Alekos Filini, Alessandro Salvetti, Armando Christian Dutra, Christophe Diederichs, ClΓ‘udio de Castro, Chris Stewart, Emil Bayes, Fabrizio Armani, Federico Tenga, Francisco Calderon, Juraj Bednar, Hunter Trujillo, Max Hillebrand, Marco Amadori, Masaki Muranaka, Martin HabovΕ‘tiak, Nadav Kohen, Nicola Busanello, Olga Ukolova, Rajar Shimaitra, Rene Pickhardt, Reza Bandegi, Sabina Sachtachtinskagia, , Stefano Pellegrini, ZmnSCPxj, Zoe Faltiba, . The community management since 2019 was performed by Olga Ukolova.

Sosthene
yojoe
zkao