This is a read note of Mastering Bitcoin Chapter Ch12: Blockchain Applications. The Bitcoin system was designed as a decentralized currency and payment system. However, most of its functionality is derived from much lower-level constructs that can be used for much broader applications. It uses a transactional scripting language with low-level cryptographic functions. Thus, the Bitcoin blockchain can become an application platform offering trust services to applications, such as smart contracts, far surpassing the original purpose of digital currency and payments.

1 Prmitives

When operating correctly and over the long term, the Bitcoin system offers certain guarantees, which can be used as building blocks to create applications. These include:

  • No double-spend
  • Immutability
  • Neutrality
  • Secure timestamping
  • Authorization
  • Auditability
  • Accounting: the outputs cannot exceed the inputs
  • Nonexpiration
  • Integrity
  • Transaction atomicity
  • Discrtete (indivisible) units of value: UTXO can either be spent or unspent in full
  • Quoram of control: the M-of-N multisignature
  • Timelock/Aging
  • Replication: durable and silient to power loss, data loss, etc
  • Forgery protection
  • Recording external state: A transaction can commit a data value, via OP_RETURN, representing a state transition in an external state machine.
  • Predictable issusance

Some examples of applications from building blocks are:

  • Proof-of-existence (digital notary): immutability + timestamp + durability.
  • Kicstarter (lighthouse): Consistency + Atomicity + Integrity. If you sign one input and the output (Integrity) of a fundraiser transaction, others can contribute to the fundraiser but it cannot be spent (Atomicity) until the goal (output value) is funded (Consistency).
  • Payment Channels: Quorum of Control + Timelock + No Double Spend + Nonexpiration + Censorship Resistance + Authorization. A multisig 2-of-2 (Quorum) with a timelock (Timelock) used as the “settlement” transaction of a payment channel can be held (Nonexpiration) and spent at any time (Censorship Resistance) by either party (Authorization). The two parties can then create commitment transactions that double-spend (No Double-Spend) the settlement on a shorter timelock (Timelock).

2 Counterparty

Counterparty is a protocol layer built on top of bitcoin. The Counterparty protocol offers the ability to create and trade virtual assets and tokens. In addition, Counterparty offers a decentralized exchange for assets. Counterparty is also implementing smart contracts, based on the Ethereum Virtual Machine (EVM).

Counterparty can be used as a platform for other applications and services, in turn. For example, Tokenly is a platform built on top of Counterparty that allows content creators, artists, and companies to issue tokens that express digital ownership and can be used to rent, access, trade, or shop for content, products, and services. Other applications leveraging Counterparty include games (Spells of Genesis) and grid computing projects (Folding Coin).

3 Payment Channels and State Channels

Payment channels are a trustless mechanism for exchanging bitcoin transactions between two parties, outside of the Bitcoin blockchain. A payment channel is a state channel where the state being altered is the balance of a virtual currency. State channels are virtual constructs represented by the exchange of state between two parties, outside of the blockchain. There are no “channels” per se and the underlying data transport mechanism is not the channel. We use the term channel to represent the relationship and shared state between two parties, outside of the blockchain.

A state channel is established between two parties, through a transaction that locks a shared state on the blockchain. This is called the funding transaction or anchor transaction. This single transaction must be transmitted to the network and mined to establish the channel.

The two parties then exchange signed transactions, called commitment transactions, that alter the initial state. These transactions are valid transactions in that they could be submitted for settlement by either party, but instead are held off-chain by each party pending the channel closure. In practice this means that thousands of transactions per second can be exchanged. When exchanging commitment transactions the two parties also invalidate the previous states, so that the most up-to-date commitment transaction is always the only one that can be redeemed.

Finally, the channel can be closed either cooperatively or by either party, by submitting a final settlement transaction to the blockchain. In the entire lifetime of the channel, only two transactions need to be submitted for mining on the blockchain: the funding and settlement transactions.

The only way to cancel a transaction is by double-spending its inputs with another transaction before it is mined. Each subsequent commitment transaction must have a shorter timelock so that it may be broadcast before its predecessors and before the refund transaction. The ability to broadcast a commitment earlier ensures it will be able to spend the funding output and preclude any other commitment transaction from being redeemed by spending the output. The guarantees offered by the Bitcoin blockchain, preventing double-spends and enforcing timelocks, effectively allow each commitment transaction to invalidate its predecessors.

4 Asymmetric Revocable Commitments

A better way to handle the prior commitment states is to explicitly revoke them. Even though a transaction cannot be canceled, it can be constructed in such a way as to make it undesirable to use. The way we do that is by giving each party a revocation key that can be used to punish the other party if they try to cheat. This mechanism for revoking prior commitment transactions was first proposed as part of the Lightning Network.

Here is an example. First, A and B each puts 5 bitcoin to a 2-of-2 multisig funding transaction that has one or more inputs from each side. The inputs are slightly higher than the channel capacity in order to cover the transaction fees. The founding transaction has to be signed before it is transmitted.

Now, instead of creating a single commitment transaction that both parties sign, each party creates an asymetric commitment transaction. For example, A creates the following commitment transaction:

Input: 2-of-2 funding output, signed by B

Output 0 <5 bitcoin>:
    <B's Public Key> CHECKSIG

Output 1 <5 bitcoin>:
    <1000 blocks>
    <A's Public Key> CHECKSIG

B also create a commitment transaction that pays A 5 bitcoin and pay B, after 1000 block, 5 bitcoin. By imposing a delay on the redemption of one of the outputs, we put each party at a slight disadvantage when they choose to unilaterally broadcast a commitment transaction.

Now we introduce the final element of this scheme: a revocation key that prevents a cheater from broadcasting an expired commitment. The revocation key allows the wronged party to punish the cheater by taking the entire balance of the channel. The revocation key is composed of two secrets, each half generated independently by each channel participant. It is similar to a 2-of-2 multisig, but constructed using elliptic curve arithmetic, so that both parties know the revocation public key but each party knows only half the revocation secret key.

In each round, both parties reveal their half of the revocation secret to the other party, thereby giving the other party (who now has both halves) the means to claim the penalty output if this revoked transaction is ever broadcast. Each of the commitment transactions has a “delayed” output. The redemption script for that output allows one party to redeem it after 1000 blocks, or the other party to redeem it if they have a revocation key, penalizing transmission of a revoked commitment.

When the channel is advanced to the next state, Hitesh has to revoke this commitment transaction before Irene agrees to sign the next commitment transaction. To do that, all he has to do is send his half of the revocation key to Irene. The revocation protocol is bilateral, meaning that in each round, as the channel state is advanced, the two parties exchange new commitments, exchange revocation secrets for the previous commitments, and sign each other’s new commitment transactions. As they accept a new state, they make the prior state impossible to use, by giving each other the necessary revocation secrets to punish any cheating.

5 Hash Time Lock Contracts (HTLC)

Payment channels can be further extended with a special type of smart contract that allows the participants to commit funds to a redeemable secret, with an expiration time. This feature is called a Hash Time Lock Contract (HTLC), and is used in both bidirectional and routed payment channels.

To create an HTLC, the intended recipient of the payment will first create a secret R. They then calculate the hash of this secret H: H = Hash(R). This produces a hash H that can be included in an output’s locking script. Whoever knows the secret can use it to redeem the output. The secret R is also referred to as a preimage to the hash function. The preimage is just the data that is used as input to a hash function.

The second part of an HTLC is the “time lock” component. If the secret is not revealed, the payer of the HTLC can get a “refund” after some time. This is achieved with an absolute time lock using CHECKLOCKTIMEVERIFY.

The script implementing an HTLC might look like this:

    # Payment if you have the secret R
    # Refund after timeout.
    <Payer Public Key> CHECKSIG

6 Routed Payment Channels (Lightning Network)

The Lightning Network is a proposed routed network of bidirectional payment channels connected end-to-end. A network like this can allow any participant to route a payment from channel to channel without trusting any of the intermediaries.

“Lightning Network” refers to a specific design for a routed payment channel network, which has now been implemented by different open source teams. The independent implementations are coordinated by a set of interoperability standards described in the Basics of Lightning Technology (BOLT) specification. The Lightning Network is one possible way of implementing routed payment channels. There are several other designs that aim to achieve similar goals, such as Teechan and Tumblebit.

Whenever a node wishes to send a payment to another node, it must first construct a path through the network by connecting payment channels with sufficient capacity. Nodes advertise routing information, including what channels they have open, how much capacity each channel has, and what fees they charge to route payments. The routing information can be shared in a variety of ways and different routing protocols are likely to emerge as Lightning Network technology advances. Some Lightning Network implementations use the IRC protocol as a convenient mechanism for nodes to announce routing information. Another implementation of route discovery uses a P2P model where nodes propagate channel announcements to their peers, in a “flooding” model, similar to how bitcoin propagates transactions.

Only the intial sendere knows the router. All other participants in the payment route see only the adjacent nodes. his is a critical feature of the Lightning Network, because it ensures privacy of payments and makes it very difficult to apply surveillance, censorship, or blacklists. The Lightning Network implements an onion-routed protocol based on a scheme called Sphinx. Using this onion-routed protocol, Alice wraps each element of the path in a layer of encryption, starting with the end and working backward. She encrypts a message to Eric with Eric’s public key. This message is wrapped in a message encrypted to Diana, identifying Eric as the next recipient. The message to Diana is wrapped in a message encrypted to Carol’s public key and identifying Diana as the next recipient. The message to Carol is encrypted to Bob’s key. Thus, Alice has constructed this encrypted multilayer “onion” of messages. She sends this to Bob, who can only decrypt and unwrap the outer layer. Inside, Bob finds a message addressed to Carol that he can forward to Carol but cannot decipher himself. Following the path, the messages get forwarded, decrypted, forwarded, etc., all the way to Eric. Each participant knows only the previous and next node in each hop. This routing protocol ensures that a payment sender can construct and communicate a path through the Lightning Network such that:

  • Intermediate nodes can verify and decrypt their portion of route information and find the next hop.
  • Other than the previous and next hops, they cannot learn about any other nodes that are part of the path.
  • They cannot identify the length of the payment path, or their own position in that path.
  • Each part of the path is encrypted in such a way that a network-level attacker cannot associate the packets from different parts of the path to each other.
  • Unlike Tor (an onion-routed anonymization protocol on the internet), there are no “exit nodes” that can be placed under surveillance. The payments do not need to be transmitted to the Bitcoin blockchain; the nodes just update channel balances.

A Lightning Network is a second-layer routing technology. It can be applied to any blockchain that supports some basic capabilities, such as multisignature transactions, timelocks, and basic smart contracts.