Introduction to Micropayment Channels

Posted by David Harding

Introduction to Micropayment Channels

Micropayment channels allow a customer to pay a merchant as little as a single satoshi (currently about $0.000004 USD), and do this time and time again over the course of hours or days. No matter how many payments the customer makes---and they can make millions---only two transactions appear on the Bitcoin blockchain and only two transaction fees are paid to miners.

This is accomplished by opening a channel from the customer to the merchant to securely record their payment history. One on-chain transaction opens this channel and one on-chain transaction closes it. Everything that happens in between is private between merchant and customer, and yet the same cryptography used to secure regular Bitcoin transactions is used to secure the micropayment channel.

With Bitcoin transaction fees currently at several thousand satoshis for typical transactions, the customer (who always pays the transaction fees) will likely save money any time they use payment channels rather than on-chain transactions to make three or more payments to the same merchant.

Install 21

How micropayment channels work: an analogy

Alice enters Bob's Bar and asks to open a tab so that she doesn't need to pay for each drink separately. Bob agrees with the following conditions:

  1. Alice lets Bob put a $100 hold on her debit card account for 8 days. This opens the tab and guarantees Alice can pay at the end of the week.

  2. Before she receives each drink, Bob shows Alice how much she owes. Alice confirms that balance is correct and signs next to it to create a record.

  3. At any time, Bob can decide that Alice has had enough and withdrawn the currently-signed balance from the hundred dollars placed on hold earlier, releasing the hold so Alice can now spend the remainder however she would like. This closes the tab.

No matter how many drinks Alice buys, the debit card company sees only two transactions---one to set the $100 lock and one where Bob actually receives money. The signed balance prevents Alice (who might be a bit drunk by now) from being able to dispute the charges.

The micropayment channels smart contract

In Bitcoin we prefer to avoid trusted third parties like debit card companies, so instead we use a decentralized smart contract to create a micropayment channel. Here's how it works:

Alice connects to Bob's server and asks to open a micropayment channel so that she doesn't need to make an on-chain transaction for each micropayment. Bob's server agrees with the following conditions:

  1. Alice locks 100,000 satoshis on the blockchain for 8 days using the CheckLockTimeVerify (CLTV) opcode. This opens the channel and guarantees Alice can pay at the end.

  2. Before she receives each micro-service, Bob's server shows Alice's client how much she owes. Alice's client confirms that balance is correct and signs it with her Bitcoin private key to create a cryptographically-verifiable record.

  3. At any time, Bob can decide that Alice has had enough and use the current signed balance to withdraw that many satoshis from the locked balance, releasing the lock so Alice can now spend the remainder however she would like. This closes the channel.

No matter how many micropayments Alice makes, the blockchain sees only two transactions---one to set the 100,000-satoshi lock and one where Bob actually receives money. The signed intermediate balances are actually valid Bitcoin transactions---although only one gets broadcast---so they prevent Alice from being able to refuse to pay Bob.

Micropayment channels in action

Let's walk through the example above step by step by creating an actual micropayment channel. We'll play the role of the customer and we'll use the 21.co endpoint server as the merchant. You can also optionally setup your own server.

To run this example, you will need 123,000 satoshis in your on-chain balance. The satoshis will be used like this:

  • 100,000 satoshis will be the starting balance of the payment channel. You'll pay 3,001 of these satoshis to the merchant; the remaining 96,999 satoshis will stay under your control.

  • 3,000 satoshis will be a hidden part of the payment channel balance; these satoshis will be returned to you no matter how many satoshis you pay the merchant. This bypasses Bitcoin's dust limit which is discussed below.

  • An additional 20,000 satoshis will be paid to miners for mining the on-chain channel open and close transactions.

To get the 123,000 satoshis necessary to open the channel, you can run the following commands:

  • 21 status will tell you how many satoshis you have available both on-chain and off-chain.

  • 21 sell will provide you with more satoshis in your off-chain balance.

  • 21 flush will move all your off-chain satoshis to the blockchain. Although the command will finish running quickly, the actual transfer will take several minutes. You can keep re-running 21 status to see when the satoshis have moved.

Opening the channel

You, the customer, want to open a channel with the merchant (who is, in this case, the 21.co payment server which normally processes payments for the Marketplace). You will lock 100,000 satoshis on the blockchain for 8 days.

channels open 'https://apps.21.co/payments/channel' 100000 $(( 8 * 86400 ))

Running the command above will print a result similar to this:

Opened https://apps.21.co/payments/channel/e6caff5d2a1f76a349c6941c1fbe08396250be2c9673717ef301b8df712fff59
Deposit txid e6caff5d2a1f76a349c6941c1fbe08396250be2c9673717ef301b8df712fff59
Balance: 100000. Deposit: 100000. Expires in 7 days, 23 hrs, 59 min, 58 sec.

Note the URI you got as you'll need it in the future commands to refer to this specific channel if you have multiple channels open. Let's store that URI as a shell variable so we can automatically refer to it later:

$ CHANNEL_URI='FILL_IN_YOUR_URI_HERE'

For example,

CHANNEL_URI=https://apps.21.co/payments/channel/e6caff5d2a1f76a349c6941c1fbe08396250be2c9673717ef301b8df712fff59

The transaction you just created to lock 100,000 satoshis on the blockchain will be visible on blockchain explorers if you search by the txid printed by channels open. Here is the page for the transaction above.

You can keep track of it from the command line by running the following command line:

$ channels sync ; channels status $CHANNEL_URI

That will print a short summary such as this. Note that it starts out saying, "Confirming deposit".

Confirming deposit

When the confirmation is finished, which may take up to 90 minutes, that will change to "Ready".

Channel ready

Not all merchants will require waiting for confirmation, but the server you're working with in this example currently does require waiting, so you should periodically re-run the sync/status command above until it says "Ready".

If you try making a payment in the channel before it's ready, it will print "Error: Channel not ready".

Making a payment

To pay the server 3,000 satoshis, you can run the following command:

$ channels pay $CHANNEL_URI 3000

That will print a single line with a 64-character hexadecimal string:

Paying 3000 satoshis in a channel

The string is a Transaction Identifier (txid), but it's not like most Bitcoin txids because no blockchain explorer will ever see a transaction with this txid. That's because you, the customer, created a signed payment here using your private key and gave it to the merchant server---but the merchant server won't broadcast it in order to allow you to make follow-up payments.

Let's check the status to confirm that 3,000 satoshis has been paid:

$ channels status $CHANNEL_URI

Which should look something like this:

Channels balance after paying 3000 satoshis

Note: the minimum amount for the first payment in a channel is 3,000 satoshis. Subsequent payments can be much lower, as we'll see in a moment. The first payment has to be so large because Bitcoin has protection against attackers who use very small transactions (called dust) to excessively slow down full nodes.

Making the smallest possible micropayment

To pay the merchant a single satoshi, run the following command:

$ channels pay $CHANNEL_URI 1

This will look similar to the previous result, except that your balance will have gone down by only a single satoshi this time.

Paying a single satoshi

A single satoshi is the smallest payment possible in Bitcoin, although it is possible to keep track of smaller amounts and round them up to whole satoshis when necessary. The grid computing demo provides a demonstration of that.

Closing the channel

There are two ways the channel can close:

  1. At any time, the merchant can close the channel by broadcasting the latest version you signed.

  2. After 8 days (or whatever time you set), the lock expires and you can optionally spend the 100,000 locked satoshis however you want---including sending them back to yourself rather than to the merchant.

Although only the merchant can close the channel before the 8 day are up, you can request that they close the channel with the following command:

$ channels close $CHANNEL_URI

This will display the results of the close operation:

Closing the channel

After a few moments, you can look up that spend txid on a blockchain explorer. A screenshot from before it confirmed is shown below; by the time you read this, it will have confirmed and will be a part of the blockchain, which you can see here.

Close transaction on blockchain explorer

Getting a full refund

By broadcasting the final payment in the example above, the merchant received his earnings in a regular on-chain Bitcoin transaction. But if he had failed to broadcast before the timelock expires, you could have sent all of the original 100,000 satoshis back to yourself.

You can't test this because the merchant has already closed your channel and, besides, the 21.co merchant server is setup to automatically close channels about 4 days before they expire. However, if you need to do this, run the channels sync command which will automatically close any expired channels and return the full balance back to your on-chain wallet.

Implementation details

You don't need to read or understand this section. We've provided it for people who want to understand why micropayment channels have the same strong security and decentralization as regular Bitcoin transactions.

The customer Alice and the merchant Bob follow three steps:

  1. Making a deposit transaction that timelocks satoshis on the blockchain for 8 days.

  2. Signing (but not broadcasting) intermediate payments.

  3. Broadcasting a payment (before 8 days) or a refund (after 8 days).

Step one: timelocking

Step one is performed by paying 100,000 satoshis (or however much Alice chooses) to an output that uses the BIP65 OP_CHECKLOCKTIMEVERIFY (CLTV) opcode. In a human-readable format, the script looks something like this:

OP_IF
  <Bob's public key> OP_CHECKSIGVERIFY
OP_ELSE
  1452955945 OP_CHECKLOCKTIMEVERIFY OP_DROP
OP_ENDIF
<Alice's public key> OP_CHECKSIG

This says that there are two ways someone can spend the deposit transaction. In both cases, line six of the script specifies that Alice must sign the spend using her private key (which corresponds to the public key provided). But the If/Else block says one or the other of the following conditions must be satisfied:

  1. Spend: Bob must sign with his private key too.

  2. Refund: The transaction must have a locktime greater than Unix time 1452955945 (Sat Jan 16 14:52:25 UTC 2016), meaning it can't be added in a block until after that time.

In other words, if Alice and Bob both sign the same transaction, they can cash out immediately. If Bob doesn't sign, Alice gets her money back at the appointed time (in this case, 8 days after the deposit was made).

Step two: intermediate payments

Step two is making the intermediate payments that fulfill the above script. Specifically, this happens:

  1. Alice's client tells Bob's server what she wants to order.

  2. Bob's server use the 402 payment protocol to tell her client how much it costs.

  3. Alice's client signs a transaction satisfying the spend form of the script above, the one that requires both her and Bob to sign. She gives this to Bob's server as proof of payment.

  4. Bob's server verifies the payment and adds his signature, making it valid. However, it isn't broadcast immediately to allow Alice to make additional payments. Bob's server delivers the digital good that Alice ordered.

Step three: broadcasting

Step three is closing the channel by broadcasting some form of the transaction.

  1. Payment: Bob's server broadcasts the highest-value spend form of the transaction he received from Alice, moving the satoshis out of the timelocked transaction into a Bitcoin address controlled by Bob.

  2. Refund: Alice's client broadcasts the refund transaction allowed by the refund form of the script above, the one that only requires her signature provided a certain time has past.

For even more information about our implementation of CLTV-based micropayment channels, please see our API documentation.

The channels command reference

At any time, a customer can use the channels command to create or manage a channel. (There is no corresponding command for the merchant.) Start by seeing what's available:

$ channels help
Usage: channels [OPTIONS] COMMAND [ARGS]...

  Manage payment channels.

  The `21 channels` command is used for creating, opening, closing, and
  conducting diagnostics for the payment channel micropayments protocol.
  After opening a channel with a merchant, making a payment returns a token,
  which the merchant will accept as proof of payment within the 402 payments
  protocol. Example of opening a channel, making payments, and closing the
  channel:

  $ channels open https://mkt.21.co/21dotco/payments/channel 100000 120

  $ channels pay https://mkt.21.co/21dotco/payments/channel 100

  $ channels pay https://mkt.21.co/21dotco/payments/channel 100

  $ channels pay https://mkt.21.co/21dotco/payments/channel 100

  $ channels info https://mkt.21.co/21dotco/payments/channel

  $ channels close https://mkt.21.co/21dotco/payments/channel

Options:
  --json      JSON output.
  --version   Show the version and exit.
  -h, --help  Show this message and exit.

Commands:
  list    List channels.
  sync    Sync channels.
  open    Open channel.
  pay     Create payment to channel.
  status  Get status of channel.
  info    Get details of channel.
  close   Close channel.
  help    Print help.

List all channels (channels list)

The channels list command shows us the channel currently open between the customer and the merchant:

$ channels list

http://[::]:9123/payment/4063e7f7444245b402dea0426c56825c236e407459ac05d1af0e3329b8053e8b
    Status          Ready
    Balance         96919
    Deposit         100000
    Created         Fri Jan  8 00:45:18 2016
    Expires         7 days, 23 hrs, 56 min, 4 sec
    Deposit txid    4063e7f7444245b402dea0426c56825c236e407459ac05d1af0e3329b8053e8b
    Spend txid      None

The fields here are:

  • URI: the hostname of the merchant, the resource /payment/, and the transaction identifier (txid) of the deposit transaction.

  • Status: When the channel is open, this is "Ready". When the channel is closing, this is "Confirming spend". When the channel has finished closing, this is "Closed". (Note: you may need to run channels sync before this updates from Confirming to Closed.)

  • Balance: the spendable value of the channel in satoshis.

  • Created: when the channel was opened.

  • Expires: the time left until the customer can attempt to steal back all funds paid into the channel (except for transaction fees) if the channel close transaction has not been confirmed yet. (Closing the channel before this time is the merchant's responsibility, and the channels library defaults to closing the channel 3 days before expiration to ensure the close transaction is confirmed in time.)

  • Deposit txid: the txid of the deposit transaction. This may be looked up on any blockchain explorer. If it isn't confirmed, it is possible for the customer to double-spend the deposit transaction and receive all services for free.

  • Spend txid: the txid of the channel close transaction. Since the example channel above is still open, no txid is provided here.

Get channel status (channels status)

If you just want a summary about the channel, you can use the channels status command:

$ channels status 'http://[::]:9123/payment/4063e7f7444245b402dea0426c56825c236e407459ac05d1af0e3329b8053e8b'
Ready. Balance: 96919. Deposit: 100000. Expires in 7 days, 23 hrs, 55 min, 20 sec.

Get detailed channel status (channels info)

If you want even more information, you can use the channels info command (note: information previously shown in the channels list text above is not repeated below):

$ channels info 'http://[::]:9123/payment/4063e7f7444245b402dea0426c56825c236e407459ac05d1af0e3329b8053e8b'

    Transactions
         Deposit tx
             010000000193bb32e9f8bf348b63a61814f2c25910bc394f00a0e06a2158be9e2c16ead075010000006b483045022100ecea8b9889fdd0ddc39bed0e63c9b4be952e688dcdcc7653cdb5b36e6cfc532602202722e7a852a1581fa0192bbd1effb829aa23649d5a9d9c6366ce4a80db94a583012102bb1da37d4764ea19aab528f198f072695308890a7ee1fc4449437c3922849d6fffffffff0268b30200000000001976a9148861f5a29bc73d06d8a3cdc174705d625b85d8f988ac68b901000000000017a914cdd5201a0e7c4b493be5c7a5f9f5b557990dc50d8700000000
         Refund tx
             01000000018b3e05b829330eafd105ac5974406e235c82566c42a0de02b4454244f7e76340010000009c47304402201a303d9e698f161e850a0701278cbf2ca65feef364e5f0e61f96d2c6d5b75804022061b1f3a906622fb2086987c7ca7fe8963bf22415635031a9b604b887b710929b0101004c50632102193beaec00a8d79fc67e2059d2b74d3262e320880bb39a8676edcc3f76b47421ad67041e589056b1756821039a44cfc79f3f29aecdea36d1a25488f4458df060dad60716a62de34e6b3a4800acfeffffff0158920100000000001976a9148861f5a29bc73d06d8a3cdc174705d625b85d8f988ac1e589056
         Payment tx (half-signed)
             01000000018b3e05b829330eafd105ac5974406e235c82566c42a0de02b4454244f7e76340010000009c483045022100f3cee2fa7b7d8599542556041de04d5caf60c26a25c237fbf84071adcd4fb15b022053700678176d468551a6a9a550e23d3877fa2317348f4f3ca87e48fa7507b72b01514c50632102193beaec00a8d79fc67e2059d2b74d3262e320880bb39a8676edcc3f76b47421ad67041e589056b1756821039a44cfc79f3f29aecdea36d1a25488f4458df060dad60716a62de34e6b3a4800acffffffff02090c0000000000001976a914b222824414ec08a3a611a1aba8219e9e07df3eb288ac4f860100000000001976a9148861f5a29bc73d06d8a3cdc174705d625b85d8f988ac00000000
         Spend Tx
             None

These new fields each contain a raw transaction:

  • Deposit tx: the transaction used to open the channel.

  • Refund tx: the transaction the customer can use to reclaim all non-fee funds paid into the channel. Note the final 8 characters (4 bytes) of the hexadecimal string are not zeroes like the other transactions. Those bytes belong to the transaction locktime, and their non-zero value indicates that this transaction can't be confirmed in a block until that time.

  • Payment tx (half-signed): an alternative form of the refund transaction (note that all of the early bytes are the same) that doesn't have any locktime (notice the last four bytes are zeroes) meaning it can be confirmed in a block immediately. Unlike the refund transaction, this transaction has been signed by the customer to pay the merchant the satoshis spent for the file data transfer used earlier.

    The transaction has only been signed by the customer so far; the merchant also needs to sign and broadcast it in order for it to be considered for confirmation in a block by a miner.

  • Spend tx: when the channel is closed, either the refund tx or a signed version of the payment tx will be confirmed. This field will contain that transaction.

If you have Bitcoin Core installed, you can inspect each of the transactions using bitcoin-cli decoderawtransaction.

Force channel synchronization (channels sync)

The implementation of micropayment channels used in two1 keeps track of changes to the balance in a sqlite database and then updates the payment tx every few seconds by default. If you want to manually trigger an update of that payment tx, you can use the channels sync command:

$ channels sync
[no output indicates success]

The sync command will also check the channel's expiration date and close the channel if appropriate. For the customer, this means waiting until the expiration time is in the past and then broadcasting the refund tx to reclaim all non-fee funds paid into the channel.

(Note: the time used for determining when a locktime-protected transaction can be added to a block is the median of the time of the previous 11 blocks; this is usually about 90 minutes behind real time.)

Execute a micropayment (channels pay)

If the customer wants to pay the merchant through the channel, the channels pay command may be used. For example, to pay 1000 satoshis to the merchant:

$ channels pay 'http://[::]:9123/payment/4063e7f7444245b402dea0426c56825c236e407459ac05d1af0e3329b8053e8b' 1000
3236d24cee193f76ad4d8543e6fbeaa547294f85d33e9a69cbe3daadd002ef5d

After paying, the command prints the txid of the updated payment tx (although the micropayment is incomplete until the merchant signs it, which will update its txid).

Closing a micropayments channel (channels close)

To close the channel, use the channel close command. This syncs the channel with the current balance and tells the merchant that they should now broadcast the payment tx.

$ channels close 'http://[::]:9123/payment/4063e7f7444245b402dea0426c56825c236e407459ac05d1af0e3329b8053e8b'
Channel closed. Balance: 95919. Deposit: 100000.
Expected spend txid 036656c45edab28ac2a5c3fcc7589da1166cf07d2da51a8379244ffb4b4a9d44

Open a micropayments channel (channels open)

channels open will open a channel with a merchant. It takes several parameters:

  • URL: the URL of the merchant, such as http://[::]:9123/payment

  • Deposit: the amount of the deposit transaction (not including fees) in satoshis. This is the maximum amount the customer can pay to the merchant using this channel.

  • Expiration: the number of seconds until the channel expires and you can broadcast the refund transaction that reclaims all non-fee funds. For example, 86400 specifies the channel expires in a day.

You may also specify some additional optional arguments:

  • --fee (default: 10000): the transaction fee to pay in satoshis. The customer pays all fees. The same fee is paid for both the open transaction and the close transaction, so if you enter 10000 satoshis here, the total fee paid will be 20000 satoshis. Merchants will want this fee to be high to help ensure the transactions confirm.

  • --zeroconf (default: 0 (False)): whether to use the channel before the deposit transaction is confirmed (zeroconf). Ultimately the merchant decides whether they accept zeroconf, but if you know they do accept zeroconf, this let's you take advantage of it.

  • --use-unconfirmed (default: 0 (False)): whether to use an unconfirmed transaction as an input to the deposit transaction. This has risks for both the merchant and the customer, so it is disabled by default and merchants don't usually allow it.

Security notes

Channel micropayments create multiple local versions of Bitcoin transactions, so they have the same fundamental security as any other Bitcoin transaction with one exception: the merchant must broadcast his transaction before the customer's refund can be confirmed or the customer can take back any satoshis they paid the merchant. (By default, the two1 library broadcasts three days before expiration to provide a large safety margin.)

For this reason, merchants should only accept micropayment channels in production if they know their server will be up and running near the channel expiration time.

Customers using micropayment channels don't need to take any special actions. By opening a channel, their deposits are locked up for a certain period of time (8 days) but they can get those funds back after 8 days by running the channels sync command if the merchant becomes uncooperative.