Introduction to 21

Posted by Balaji S. Srinivasan, David Harding

Introduction to 21

In the beginning was the World Wide Web, built on HTML. Then came the Social Web, built on personalization. But we believe that there is a third web yet to be built: the Machine-Payable Web, built on Bitcoin.

Technologists have desired a Machine-Payable Web for quite some time. In fact, for 20 years the official HTTP specification has actually included a code for this purpose, marked specifically for future use: 402 - Payment Required.

With 21, we've done our best to help bring that future about.

21 is free software that implements the Payment Required HTTP status code and much more. It makes it easy to (a) send and receive micropayments over HTTP and (b) write new kinds of programs that use this basic technology as an intrinsic primitive, like machine-payable APIs and intelligent agents.

If these concepts interest you, and if the idea of a third web based upon machine-to-machine micropayments is exciting, it may be worth your time to learn 21. Let's get started.

Overview

This quickstart guide will introduce you to the capabilities of 21, free software that makes it easy to programmatically buy and sell digital goods for bitcoin. You can think of 21 in four different ways:

  • App: The simplest way to understand 21 is as a command line application that you can quickly install on any device to get bitcoin in a variety of ways.

  • Marketplace: The next way to understand 21 is as a marketplace which allows you to trade API calls (and thereby machine resources) for bitcoin. You can view the directory of API calls available for sale at 21.co/mkt, and you can use 21 to publish your own machine-payable APIs with a few keystrokes.

  • Network: The third way to understand 21 is as a sort of "capitalist network", where you can monitor the earnings of your various machines and find other developers who are building machine-payable services.

  • Library: The final way to understand 21 is as a Python 3 library called two1, which allows you to build your own custom machine-payable applications. With two1 you can add micropayments to new or existing web services with one line of code.

As each of these pieces interfaces with the others, the best way to understand them is to learn by doing. So let's get started by installing 21, and then explore each of these four aspects in turn.

Before you proceed, please note that 21 is currently in beta, and some of the commands (especially 21 sell) involve running a server locally. While we strive to be security conscious, it's best during the beta phase to install 21 on a 21 Bitcoin Computer, a DIY Bitcoin Computer, an Amazon Virtual Machine, an old computer, or some other standalone device that is not your main personal laptop.

Installation

21 is currently supported on Ubuntu Linux 14.04 run on Amazon AWS and Mac OS X 10.7+. Most functions are also supported on other Debian-based platforms, such as 21 Bitcoin Computers or DIY Bitcoin Computers. Support for other platforms is coming soon.

Installation is simple. Just type this at the command line:

curl https://21.co | sh

Feel free to preview the script before installation. Note that the use of https is mandatory here. Once you've installed the script, please visit the signup page to create your 21 account.

21 login: Log in to your 21 account

Once you've installed 21 and set up your 21 account, you can log in to your 21 account at the command line as follows:

21 login

Here's what that looks like:

You do not have a Bitcoin wallet configured. Let's create one. Press any key ...

Wallet successfully created.

You can recover the private key to your wallet using the following 12 words (in this order) :

champion hotel review lake toaster immense picnic soldier glimpse candy girl side

Write down and store these words in a safe place.

Press any key ...

If you don't have a 21 account, visit https://21.co/signup to create one. 

Username: harding4
Password (Typing will be hidden): 
logging in harding4
Setting default payout address to: 115kjVQznK4Skp8z9TYKanWgLU5oQXS1Bp
Check out our introductory guide to learn the basics of 21: https://21.co/learn/intro-to-21/

As shown, you will first be prompted to create a Bitcoin wallet. Follow the instructions, and be sure to record the mnemonic provided to you. This is the backup for access to your wallet. Please note that 21 cannot help you restore your Bitcoin wallet if you lose the mnemonic.

Next, you'll be prompted to enter the 21 username you just created along with your 21 password. Before proceeding, we recommend making your system password secure by running passwd if you have not already done so (your system password is distinct from your 21 password).

21 market: Join a virtual private marketplace

Note: this section only applies to users of the 21 Bitcoin Computer, virtualized Docker, and Amazon EC2.

When a new device connects to the internet it typically acts as a client, namely something that can initiate connections to domains like google.com to download information. However, the 21 software also allows your machine to act as a server that sells machine-payable resources for bitcoin. To do this, it needs to allow other machines to be able to send packets to your machine to request digital goods without knowing the specific machine IP address or domain name in advance.

Run the following command to join the network:

21 market join

Its output looks like:

WARNING
-------
Note that the 21 Network operates very similarly to a public Wi-Fi
access point, and carries with it the same security risks as a public
"hotspot" that allows each device to connect to all other devices on the
same network.  By executing this command to join the 21 Network, you make
it possible for others to directly connect to your device.  In addition
to being able to buy your digital goods for bitcoin, they will be able
to access other services shared by your device such as shared folders
(including Dropbox and Time Capsule folders) and streaming media (such
as provided by iTunes).  Accordingly, you may also see services shared
by other users.

Please remember that the 21 software is in beta and not ready for
commercial release.  WE ARE PROVIDING THE 21 SOFTWARE AS-IS, AND YOU
ASSUME ALL RISK OF USING 21 WHILE IN BETA.

To help protect the security of your systems when using 21 while in
beta, we recommend you running the software on an EC2 instance, an old
laptop that doesn't provide any shared resources, or a small standalone
machine such as a 21 Bitcoin Computer (21.co/buy) or DIY Bitcoin Computer
(21.co/diy).

Network: 21mkt

I understand and wish to continue [y/n]: y
You might need to enter your superuser password.
Joined network 21market. It may take a few seconds for joining to take effect.
Run 21 market status to verify you have successfully joined.

This command makes your machine join a virtual private marketplace where other computers on the 21 network can buy and sell files with you directly. As shown, the command will warn you about the risks of joining the network and inform you that it may need superuser permissions to run. If it doesn't print any other error messages, that means you've successfully joined the network, which you can confirm by running 21 market status.

Note: After running 21 market, your machine will be on a private network with a virtual IP. The main difference from the internet is that every virtual IP on this network is running 21, and therefore has a bitcoin wallet plus the ability to buy and sell digital goods for bitcoin. It would be nice if all of the other computers on this network were friendly, but we cannot guarantee it. During the beta period, running 21 on a standalone device like a VM or a 21 Bitcoin Computer will provide an added level of security.

21 doctor: Test your 21 installation

You can now test that your installation is fully functional by running the following command.

21 doctor

Its output looks like:

21 doctor

Checking health..


Checking general settings..

  IP Address                         ->  10.137.2.13                          [PASS]
  Operating System                   ->  Linux                                [PASS]
  Operating System Release Version   ->  4.1.13-9.pvops.qubes.x86_64          [PASS]
  Python Version                     ->  3.4.2                                [PASS]
  21 Tool Version                    ->  3.3.0                                [PASS]

5/5 Checks passed, 0 failed, 0 warnings, and 0 skipped

Checking dependencies..

  Two1 CLI                           ->  /home/user/dotco/jupyter/venv/bi...  [PASS]
  Two1 Dotenv                        ->  /home/user/.two1/two1.json           [PASS]
  Two1 Library                       ->  /home/user/dotco/jupyter/venv/li...  [PASS]
  Two1 Wallet                        ->  /home/user/dotco/jupyter/venv/bi...  [PASS]
  Zerotier CLI                       ->  /usr/bin/zerotier-cli                [PASS]

5/5 Checks passed, 0 failed, 0 warnings, and 0 skipped

Checking servers..

  21 API                             ->  https://api.21.co                    [PASS]
  21 Logging                         ->  https://logger.21.co                 [PASS]
  21 Pool                            ->  swirl+tcp://grid.21.co:21006         [PASS]
  21 Blockchain Provider             ->  https://blockchain.21.co             [PASS]
  21 Pypicloud                       ->  https://pypi-3844.21.co              [PASS]
  21 Slack                           ->  https://slack.21.co                  [PASS]
  21 Marketplace                     ->  https://21.co/mkt                    [PASS]
  21 Website                         ->  https://21.co                        [PASS]

8/8 Checks passed, 0 failed, 0 warnings, and 0 skipped

Summary

18/18 Checks passed, 0 failed, 0 warnings, and 0 skipped

As shown, the command will print a status report that confirms everything is working correctly or else give a list of errors that need to be fixed. If you've attempted to resolve these errors and you need help with your 21 installation, please don't hesitate to go to our Slack channel.

App

Now that you've installed 21, the simplest way to understand it is as a command line app that allows you to quickly get bitcoin on any device in a variety of ways. Specifically, 21 allows you to obtain bitcoin in one of several complementary ways:

  • Selling microservices for bitcoin
  • Earning it by performing microtasks
  • Mining it with a built-in mining chip
  • Buying it from an exchange

21 also allows you to see how much bitcoin you have, and where you got it from. All of these things can be done programmatically via the two1 library, but we will first show how to do them manually by going through several commands:

  • 21 status: monitor how much bitcoin you have
  • 21 earn: earn bitcoin by performing microtasks
  • 21 mine: mine bitcoin in the background via a mining chip
  • 21 sell: sell microservices from your machine from bitcoin
  • 21 log: see the log of historical increments and decrements of your bitcoin balance
  • 21 flush: move bitcoin from off-chain buffer to your on-chain wallet
  • 21 send: send your on-chain bitcoin to another address

Let's go through these in turn.

21 status: Monitor your bitcoin balance

You can check how much bitcoin you have by running the following command:

21 status

The output will look similar to the following, but with your personal information substituted.

Logged in as: heybitcoin
Total Balance
    Your spendable buffer at 21.co [1]                        : 76937 satoshis
    Your spendable balance on the Blockchain [2]              : 1663863 satoshis
    Your spendable balance in Payment Channels                : 95000 satoshis
    Amount flushing from 21.co buffer to Blockchain balance   : 0 satoshis

    [1]: Available for off-chain transactions
    [2]: Available for on-chain and payment channel transactions
    (See 21.co/micropayments for more details)

    To see all wallet addresses and open payment channels, use '21 status --detail'

Use 21 buy to buy API calls for bitcoin from 21.co.
For help, do 21 buy --help.

There are four lines under 'Total Balance' worth discussing:

  • Your spendable buffer at 21.co. To improve performance, 21.co buffers payments from itself and from other users who send from their buffers. This buffer allows users to spend bitcoin amounts smaller than the current 3000-5000 satoshi minimum enforced by some Bitcoin miners. The size of the buffer is currently limited to a maximum of about $10 USD, and can be used to make what we call "off-chain payments" for API calls. Note that off-chain buffer cannot be sent directly to other users; it is purely for increasing performance and can only be used within the 21 system. To send bitcoin to other users you must use your on-chain Bitcoin balance.

  • Your spendable balance on the Blockchain. These are the on-chain satoshis you've received on the Bitcoin Blockchain. They are exclusively controlled by your wallet, with the private keys locally stored on the machine where you are running 21 status. This balance can be used to make what we call "on-chain payments".

  • Your spendable balance in Payment Channels. These are the satoshis you've deposited into a micropayment channel, which is a blockchain-based smart contract that allows you to send and receive payments down to a single satoshi without having to use a third-party buffer like the 21.co buffer. We'll discuss micropayment channels in more detail later in this tutorial.

  • Amount flushing from 21.co buffer to Blockchain balance. These satoshis are being moved from your buffer to your blockchain balance; this requires confirmation from a Bitcoin miner which typically takes from 5 to 20 minutes. We'll discuss 21 flush in a subsequent section.

One important note: your off-chain buffer is associated with your 21.co account, but your on-chain balance is associated with your local machine. If you set up 21 on another machine but log in with the same account, the off-chain buffer value will be the same but the on-chain balance will be different. This is by design - it allows you associate multiple wallets with your 21 account while keeping full control of the private keys.

To sum up: run 21 status to know how much bitcoin you have and where it is located. If you are running it on a clean installation, you will have zero bitcoin. Let's start fixing that.

Get bitcoin from connecting social media accounts

If you browse to your profile page by clicking your profile icon in the top-right corner of this page, visiting your profile, and then clicking Edit, you'll see the option to connect your 21 account to various social accounts:

Social media integrations

Click any one of the buttons and you'll be directed to a page where you can confirm you want to link the indicated social media account to your 21 account. For more information, please see the Network section later in this document.

After you've connected a social account, you may receive an instant increase to your buffer, so check your amounts:

21 status

To earn more satoshis, you can use 21 sell as described later in this document.

21 mine: Mine bitcoin in background or foreground

Another way to get bitcoin is by mining it with 21 mine. Note that this command only works on a 21 Bitcoin Computer. Upon first invocation, it starts the onboard mining chip as shown:

21 Bitcoin Chip detected, trying to (re)start miner...
minerd is not running.
2016-02-07 04:35:02.361 Running miner rpi2miner self-test...
2016-02-07 04:35:02.748 Miner self-test passed: BIST test results: 256 / 256. Work Builder test results: 256 / 256. Expected total hashrate: 51.20 GH/s.
2016-02-07 04:35:02.750 Starting minerd 0.2.0 with miner rpi2miner...
2016-02-07 04:35:02.756 Daemonizing...

Do 21 mine --dashboard to see a mining dashboard.
Do 21 log to see more aggregated stats.
Or just do 21 status to see your mining progress.

After this point, it continues mining bitcoin in the background, which you can see by doing 21 mine --dashboard. If invoked again, it allows you to mine bitcoin in the foreground.

satoshi_nakamoto, you are mining 40000 Satoshis from 21.co
This may take a little while...

...........................................
...........................................

satoshi_nakamoto, you got 40000 Satoshis in 4.0 seconds!

Here's the new status after mining:


Total Balance
    Your spendable buffer at 21.co [1]                        : 40000 Satoshis
    Your spendable balance on the Blockchain [2]              : 0 Satoshis
    Your spendable balance in Payment Channels                : 0 Satoshis
    Amount flushing from 21.co buffer to Blockchain balance   : 0 Satoshis

    [1]: Available for off-chain transactions
    [2]: Available for on-chain and payment channel transactions
    (See 21.co/micropayments for more details)

    To see all wallet addresses and open payment channels, use '21 status --detail'

Use 21 buy to buy API calls for bitcoin from 21.co.
For help, do 21 buy --help.

View your balance with 21 status, or spend with 21 buy.

You can run 21 log at any time to see when you have mined bitcoin either in the background or foreground.

21 sell: Sell microservices for bitcoin

Perhaps the most interesting and novel way to get bitcoin with 21 is to sell microservices for bitcoin.

21 makes it easy for you to start selling microservice APIs immediately from any computer or device. You don't need to worry about finding a buyer for these microservices; 21 takes care of that for you through the 21 marketplace. The services which provide those APIs are isolated from the rest of your system by placing them in a sandbox, which doesn't guarantee security but which does significantly enhance it. (Even still, during the beta period you should consider running 21 on a standalone device, like a 21 Bitcoin Computer or an Amazon VM.)

The easiest way to get started is to activate all of the microservices bundled with 21 at once by running the following command:

21 sell start --all

If this is your first time running 21 sell, you will be prompted to install its dependencies. Example output is shown below, but the actual output you see will vary by your platform and what dependencies you already have installed.

Checking dependencies...
  Dependencies                       ->  Installed                            [TRUE]
  21market                           ->  Joined                               [TRUE]
Checking virtual machine status...
  21 virtual machine does not exist. Would you like to create it? [y/N]: y
Configure 21 virtual machine:
Press return to accept defaults.
  Virtual disk size in MB (default = 5000):
  Virtual machine memory in MB (default = 1024):
  Port for micropayments server (default = 8080):
  Network interface (default = zt0):
Creating machine (this may take a few minutes)...
  21 virtual machine                 ->  Created                              [TRUE]
Starting machine (this may take a few minutes)...
  21 virtual machine                 ->  Started                              [TRUE]
Please enter your 21 password:
Building base services (this may take a few minutes)...
  Services                           ->  Built                                [TRUE]
A wallet has been generated for the payment container,
please write down its wallet mnemonic and store it in a safe place:
    fringe useless hover myself couch science finger jump direct profit toaster skirt
Press any key to continue ...
Building market services...
  Services                           ->  Built                                [TRUE]
A wallet has been generated for the service "ping",
please write down its wallet mnemonic and store it in a safe place:
    reflect woman exit claim toaster orbit coin involve double swear garbage accident
Press any key to continue ...
Starting services (this may take a few minutes)...
  Ping                               ->  Service container still spinning     [TRUE]
                                         up…

On Linux, the output above will be different because you'll have to log out of your system account (not your 21 account), log back in, and then run 21 sell start --all again to complete the setup.

You can also start an individual service, such as ping21, by specifying its name instead of the --all flag. Note that for the initial release of the 21 beta, the ping21 microservice is the only one bundled with 21, but more will be forthcoming.

21 sell status

You can check the status of your microservices at any time by running the following command:

21 sell status

The output will vary by platform and by which services you're running, but it should look similar to the example below:

-------------------------------------------------------------------------------------
21 SYSTEM STATUS
-------------------------------------------------------------------------------------
NETWORKING
  ZeroTier One                       ->  Running                              [TRUE]
  21 Marketplace                     ->  Connected                            [TRUE]
                                         Your IP:
                                         [fcce:a977:ee28:e62d:f6d6:0000:0000:0001]
SERVICES
  Router                             ->  Running                              [TRUE]
  Payments                           ->  Running                              [TRUE]
  Ping                               ->  Running                              [TRUE]
BALANCES
  Server                             ->  - Buffer       85250 ($0.5746)     
                                         - Onchain          0 ($0.0000)     
                                         - Channels         0 ($0.0000)     
TRANSACTION TOTALS
  Ping                               ->  Requests: 9                        
                                         - Buffer       27000 ($0.1820)     
                                         - Onchain          0 ($0.0000)     
                                         - Channels         0 ($0.0000)     
EXAMPLE USAGE
  Ping                               ->  21 buy '[fcce:a977:ee28:e62d:f6d6:0000:0000:0001]:8080/ping/?uri=21.co'

Tip: run `21 sell list` to see available microservices you can sell.

The concept behind the ping21 microservice is that you are renting out your machine (along with many others) for distributed uptime monitoring. For further information, see here and here.

21 sell stop

You can stop selling all microservices with a single command:

21 sell stop --all

The output will look similar to the following:

Stopping services.
  ping                               ->  Stopped and removed                  [TRUE]
  ping                               ->  [Totals]                             [TRUE]
                                         Requests: 10                       
                                         Earnings: $0.2022

You also stop an individual service, such as ping21, but specifying its name instead of the --all flag.

21 sell sweep

For security, the services run by 21 sell each have their own wallet separate from your main wallet. This reduces the risk that one compromised service can steal funds earned by other services or which you acquired in other ways.

This means that before you can spend the satoshis you earned with 21 sell, you have to move them to your main wallet. The 21 sell sweep command will do that for you:

21 sell sweep

This will move your sell balance to your main wallet.

For now, let's make sure all services are running so that you can earn bitcoin in the background while you continue this tutorial:

21 sell start --all

21 log: See when you earned and spent bitcoin

You can track when you've receive bitcoin and from where with 21's log command. This will provide you with an ordered list (most recent first) of all your activity.

21 log

Depending on whether or not you've earned any satoshis you using 21 sell, your output may look similar to the following:

[21 Activity Log]


2016-07-15 17:43:05 UTC+00:00 : -3000 satoshis from your 21.co balance
Description: You bought 'http://10.244.137.115:8080/ping/?uri=21.co' from harding4


2016-07-15 17:27:21 UTC+00:00 : -3000 satoshis from your 21.co balance
Description: You bought 'http://10.244.137.115:8080/ping/?uri=21.co' from harding4

21 flush: Flush your off-chain buffer to the blockchain

As noted above, users have a small off-chain buffer as a performance improvement. Users with 20,000 satoshis or more in this buffer can flush all or part of the buffer to their local wallets by running the 21 flush command.

Please note: the satoshis you withdraw from your buffer cannot be added back. Since you need satoshis in your buffer to run many of the 21 tutorials, we recommend that you be careful not to flush all of your buffer.

When used without any parameters, your full buffer is flushed. However, you may also specify the amount you want flushed:

21 flush 20000 satoshis

Which will produce output similar to the following:

Flush to Blockchain
Your mined Satoshis will be sent to you on the Blockchain in the next payout cycle.
Estimated time of payout: ~20 minutes.
To check progress:  https://blockchain.info/address/187VM4pdZzhch8w5wo436cbG5RhYFdLAtg
To get more bitcoin, use 21 sell.

Other units allowed are bitcoin for bitcoin (100 million satoshis) and USD for an approximate number of satoshis using the most recently available BTC/USD price.

After the flushing completes and Bitcoin miners confirm the transaction, those satoshis will be available in your on-chain balance. Note that this will only work if you have at least 20,000 satoshis in your buffer as shown by 21 status. If you have fewer than 20,000 satoshis, you can run 21 mine on a 21 Bitcoin Computer or 21 sell on other supported devices to earn more satoshis, which you can then flush.

Note: before proceeding to the next step, please follow these instructions:

  1. Increase your buffer to at least 163,000 satoshis using 21 sell or other methods.

  2. Flush those satoshis to your blockchain balance by running 21 flush 163000 satoshis

    When combined with the 20,000 satoshis you flushed above, this should give you a total blockchain balance of 183,000 satoshis

  3. Increase your buffer to at least 20,000 satoshis again using 21 sell or another method.

The above instructions will give you the necessary balance and number of spendable "outputs" on the blockchain to be able to follow the rest of this tutorial with minimum interruption.

21 send: Send your on-chain balance to another address

If you have on-chain balance from flushing, selling, or buying bitcoin, you can use the following command to send your bitcoin to another address:

21 send $BITCOIN_ADDRESS 10000 satoshis

The following denominations are valid: satoshis, bitcoin, and usd.

Marketplace

The second way to understand 21 is as a marketplace. We touched on this above, but the marketplace part of 21 is why 21 sell works. You can't just sell machine-payable services into the ether - there must be a buyer, which the 21 marketplace provides after you start 21 sell. 21 exposes several commands for working with the 21 marketplace, including:

  • 21 search: find bitcoin-payable APIs in the marketplace
  • 21 buy: buy bitcoin-payable APIs in the marketplace
  • 21 rate: rate marketplace APIs
  • 21 sell: start a bitcoin-payable API server locally
  • 21 publish: publish the URL of a bitcoin-payable API server to the marketplace

The purpose of the search, buy, and rate commands is fairly self-explanatory, as they have analogs in other marketplaces.

As for the sell and publish commands, the best way to think of the distinction is to remember the difference between 'starting a web server' versus 'submitting your website to the Google index'. 21 sell is analogous to starting a web server, whereas 21 publish is analogous to submitting your website to a search index. We covered 21 sell in the previous section, and we will cover 21 publish in a subsequent section.

In this part of the tutorial, we're going to search for an endpoint in the 21 marketplace and use the satoshis from the previous section to make a purchase. But before we get into any of these commands, let's take a look at the web interface to the 21 marketplace itself at 21.co/mkt.

The 21 Marketplace (21.co/mkt)

Let's take a look:

Marketplace screenshot

In the marketplace screenshot above, two apps are shown: a part of speech tagger and a zip code database. Prior to taking this screenshot, we clicked on the zip code data app summary in order to expand its listing.

Each app has its title in bold, followed by the name of its publisher and a short description. On the right side is the price to use the app in U.S. dollars (estimated based on the current exchange rate) followed by the price in satoshis (the actual price you'll pay).

A star rating under the prices shows the average rating marketplace participants have given this app followed by the number of people who have rated it. This is the only field in the description that is not under the control of the person who published the app. We'll describe how to rate an app later in this tutorial.

In the expanded app description shown in the screenshot above for the zip code data app, there are three tabs. The first tab (opened) shows the usage information for the app, including the command to run to buy that app's API call from the 21 command line as well as its sample output (prefixed with comments so you don't actually try to run the output).

The second and third tabs (not shown) provide additional information about the app's uptime and its API. This information may be empty for apps that have not provided that additional information.

21 search: Find bitcoin-payable APIs

There are two ways for you to find useful endpoints in the 21 marketplac. The first is from the search bar on top of the marketplace home page. The second is from the 21 command line. For example, to search for apps that mention "zip" in their title or description, run the following command:

21 search zip

The output should look something like this:

Page 1/1
id    Details                                                               Creator    Price          Category    Rating
----  --------------------------------------------------------------------  ---------  -------------  ----------  ----------------
EJZ   Zip Code Data                                                         21dotco    2750 Satoshis  utilities   4.9 (30 ratings)
      Get state, city, latitude, longitude, and estimated population for a
      given zip code.

W9K   Weather21                                                             ss21serv   2500 Satoshis  utilities   5.0 (3 ratings)
      Get weather information.


Enter the id of the app for more info, n for next page, p for the previous page, q to stop search.:

If you enter the identifier (ID) for a particular app, more details will be shown. For example, if you type EJZ for more details about the zip app, you should see something similar to this:

App Name     : Zip Code Data
Description  : Get state, city, latitude, longitude, and estimated population for a given zip code.
Created By   : 21dotco
Price Range  : 2750 - 2750 Satoshis
Rating       : 4.9 (30 ratings)


Status       : Active
Availability : 100.00%


Docs URL     : https://21.co/mkt/EJZ
App URL      : https://apps.21.co/zipdata


Category     : utilities
Version      : 0.1
Last Update  : 2016-07-31 10:50:02 UTC+05:30


Quick Start

$ 21 buy "https://mkt.21.co/21dotco/zip_code_data/zipdata/collect?zip_code=94109" --maxprice 2750

# Output:
# {
#   "EstimatedPopulation": "38763",
#   "Decommisioned": "false",
#   "City": "SAN FRANCISCO",
#   "Long": "-122.42",
#   "Lat": "37.79",
#   "ZipcodeType": "STANDARD",
#   "Zipcode": "94109",
#   "State": "CA"
# }

The instructions at the bottom of the listing provide complete instructions for the search interface.

21 buy: Buy bitcoin-payable APIs

When you view the additional details of an app using either the detail listing on the website or the command line search interface, you'll be shown the quick buy instructions. You can use that command to purchase the endpoint. For example, we'll buy the zip code data endpoint using its default example:

21 buy "https://mkt.21.co/21dotco/zip_code_data/zipdata/collect?zip_code=94109" --maxprice 2750

The output returned should look like this:

{
    "City": "SAN FRANCISCO",
    "Decommisioned": "false",
    "EstimatedPopulation": "38763",
    "Lat": "37.79",
    "Long": "-122.42",
    "State": "CA",
    "Zipcode": "94109",
    "ZipcodeType": "STANDARD"
}
You spent: 2750 satoshis. Remaining 21.co balance: 61250 satoshis.

Note that you were able to buy this API directly for bitcoin without any API key or credit card signup. For more details, see here.

21 rate: Rate bitcoin-payable APIs

Once you've purchased an endpoint, you should consider rating it. Endpoints with good ratings tend to rank higher in the marketplace than endpoints with poor ratings, and we expect that people are a lot more willing to purchase from endpoints with high star ratings than endpoints with low star ratings.

To rate an app, you'll need to know its ID code, which is the same code you used to get more information about it in the 21 search command line interface. For example, to give a 5-star rating to the zip code app we just used, we would run the following command:

21 rate EJZ 5

Which would return the following result:

Giving a 5/5 rating to the app with id EJZ.

Network

The third way to understand 21 is as a network. The machines in the marketplace that are using 21 to buy and sell digital goods are (after all!) owned by humans, and facilitating commercial connections between them can be valuable as well. Towards this end, every 21 user who registers an account receives a profile page. If your 21 username is satoshi, then your profile page is 21.co/satoshi.

Example profile page

When you're logged in, you can change information on your profile page by clicking the Edit button in the top-right corner of your profile.

The screenshot above adds numbers near the various parts of the profile. Those fields are:

  1. Profile picture: by default this is a gold letter based on your name, but you can change it to a custom profile picture by clicking on the Edit button.

  2. Name: by default this is the name of your account, but you can set it to another name by clicking the Edit button.

  3. Account name: this is always your account name.

  4. Bio: by default, this is empty, but you can fill it in by clicking the Edit button.

  5. Social media links: by default, these buttons will appear in grey, but if you click the Edit button and provide additional information, the buttons will turn black and link to your Twitter, GitHub, and LinkedIn profiles.

  6. Edit & logout buttons: the edit button will allow you to change various information on your profile, and the logout button will exit the session and show you what your profile looks like to everyone else.

  7. Off-chain buffer: the bottom number is the exact number of satoshis you have in your 21.co buffer, which we call the off-chain buffer. The top number is the estimated value of those satoshis in U.S. dollars (USD). We don't track or display any satoshis stored in your on-chain wallet (where you control the private keys directly).

  8. Your apps: listed here are any apps that you have active on the marketplace, or a link to documentation for building your first app.

Now is a good time to update your public profile by clicking the Edit button. The edit screen allows you to update all of the fields on your profile, add a profile image, and also change or reset your password.

Logging in to your 21.co account

As you go through the following sections where you create, pay, and publish an app, you may want to periodically refresh your profile page to see it update.

Library

The fourth and final way to think of 21 is as a library. Specifically, the 21 Python 3 library (known as two1) allows you to quickly add bitcoin micropayments capability to any new or existing web service with one line of code. These machine-payable applications can then be published to the 21 marketplace, where other machines running 21 can buy them for bitcoin. If you're an experienced developer, full developer documentation is also available.

Create your first bitcoin-payable API

Let's learn how to use two1, which is the Python 3 library version of 21. To begin, we'll need to install the Flask website microframework:

sudo pip3 install flask

Now, here's a simple "hello, world" app that uses two1 to charge 5000 satoshis to return some text:

import flask
from two1.wallet import Wallet
from two1.bitserv.flask import Payment

app = flask.Flask(__name__)
payment = Payment(app, Wallet())


@app.route('/hello')
@payment.required(5000)
def hello():
    return 'Hello, world'

if __name__ == "__main__":
    app.run(host="::", port=5000)

Download this file

The key lines of code above are the ones that instantiate instances of the Wallet and Payment class. The Wallet looks for a wallet directory which is by default in .two1/wallet, from which it instantiates a full programmatic HD wallet. The Payment constructor in turn takes both a Flask app instance and a Wallet instance and builds a datastructure that can handle three kinds of micropayments for web-payable services.

Type that into a text file named hello-world.py and run the program using the following command:

python3 hello-world.py

If there are no problems, it will continue to run after you start it as it waits for incoming connections. We are going to test this code by buying from it using all three kinds of micropayments: off-chain buffers, on-chain bitcoin, and on-chain payment channels.

Test your API by buying off-chain

Let's test the hello-world.py server by buying from it using the first of the three payment modes that 21 supports, namely off-chain buffers. This is currently the default payment for 21 buy, so we'll test it first.

Because hello-world.py is running in your old terminal, you should open a new terminal. If you're using a 21 Bitcoin Computer or other remote server, you can do this by SSHing into a new terminal. Then check your current buffer by running the following command:

21 status

Now purchase the hello world endpoint using the following command:

21 buy http://[::1]:5000/hello

The output will look something like this (your 21.co buffer will likely be different):

Hello, world
You spent: 5000 satoshis. Remaining 21.co balance: 61250 satoshis.

Because you paid yourself using a free off-chain transfer, your actual buffer will not have changed. You can confirm this by running the status command again:

21 status

However, you will see the activity in your log:

21 log

You will see that you bought and sold from yourself, resulting in 0 net change to your buffer.

Test your API by buying on-chain

The second of the three payment methods that 21 supports are on-chain payments made using Bitcoin transactions that get added to the Bitcoin blockchain.

To use on-chain transactions there's a minimum valid payment size (currently 3000-5000 satoshis) to have your transaction included on the blockchain and you must pay a transaction fee to Bitcoin miners. Because of the fee, you will see your total balance go down when you make the following on-chain payment - even though you're paying yourself.

Let's repeat the instructions from the previous section with one modification to make the purchase on-chain. First print your current balance; pay attention to the on-chain balance:

21 status

Now purchase the hello world endpoint on-chain:

21 buy -p onchain http://[::1]:5000/hello

The output will look something like this (your 21.co buffer will likely be different):

Hello, world
You spent: 5000 satoshis. Remaining blockchain balance: 1037614 satoshis.

If you get an error indicating that you have too low a balance, you will need to get more satoshis (or wait for more people to buy from your 21 sell endpoints). You will then need to run 21 flush 20000 satoshis to move those satoshis to your on-chain balance, and finally you will need to wait about 5 to 20 minutes for the flush to complete.

Because you had to pay a transaction fee to miners for this transaction, you'll see that your on-chain balance has changed in status:

21 status

Test your API by buying with micropayment channels

The third of the three payment methods that 21 supports are Bitcoin micropayment channels. Channels are a type of on-chain transaction that are optimized for repeat transactions to the same service provider.

As motivation, the fee you paid for the previous on-chain transaction probably seemed quite high compared to the 5000 satoshi cost of the API you purchased. Fortunately, 21 allows you to amortize those fees over many API requests through something called micropayment channels.

How does this technology work? A good analogy is the idea of a bar tab. When you go to a bar, you typically put down a credit card to open a tab, enjoy your food and drinks, and then close out the tab at the end of the night. This means just two "transactions" (opening and closing the tab) even if there were many rounds of food and drink for your party. Reducing the transaction overhead is more convenient for both you and the busy bartender, as you don’t need to pull out your card and they don’t need to pay credit card fees for every pour of every drink.

Similarly, opening a micropayment channel is like opening a bar tab. In between when you open and close the channel, an unlimited number of payments of any value may be made, up to the amount you configure when you open the channel.

Let's repeat the instructions one more time with the modifications necessary to use a micropayment channel. First, print your current balance; again pay attention to your on-chain balance.

21 status

Now purchase the hello world endpoint with a micropayment channel:

21 buy -p channel http://[::1]:5000/hello
  • If you receive an error message about not having a large enough balance, that is because payment channels require at least 123,000 satoshis to open (100,000 for payments; 20,000 for transaction fees; 3,000 to refund to you no matter what).

  • If you receive the following prompt, choose y to open the channel.

Note: The default payment channel size is 100000 Satoshis.
In order to open this channel you’ll need to spend a small amount extra to cover transaction fees.
Read more at (/micropayments/)
Proceed? [Y/n]:

The output should look like this:

Hello, world

You spent: 5000 Satoshis. Remaining payment channels balance: 95000 Satoshis.

Now check your balance:

21 status

You should notice two changes:

  1. Your on-chain balance is 123,000 satoshis lower than it was because the micropayment channel amount was subtracted from this balance.

  2. You now have a payment channel balance listed. After buying the API above, it should be 95,000 satoshis.

It's not shown here, but when you close the payment channel, you'll receive back the 95,000 satoshis you haven't spent yet, the 5,000 satoshis you spent to your own API endpoint, and the 3,000 satoshis which are the guaranteed refund.

That required a fair bit of setup, but here is the key: now if you purchase the endpoint again, it will reuse the existing micropayment channel:

21 buy -p channel http://[::1]:5000/hello

And the output will look like this:

Hello, world
You spent: 5000 Satoshis. Remaining payment channels balance: 90000 Satoshis.

That's the payoff. You can now do an unlimited number of rapid bitcoin micropayments (well, up to the value of your deposit) for the cost of the open and close channel transactions.

Note that the payment channel you just opened will close automatically by default after about 5 days. If you want to close it sooner or want to learn more about 21's secure micropayment channels, you'll find more information in the following documents:

21 publish: Publish your API to the 21 Marketplace

Note: this section only applies to users of the 21 Bitcoin Computer, virtualized Docker, and Amazon EC2.

You just built the simple hello-world.py API with two1 and tested it with all three micropayment methods supported by 21. Now we will show you how to publish it to the 21 marketplace with 21 publish.

The first step is to create a manifest file. We provide detailed documentation to help you create manifest files, but you can use the file below for this simple hello world app. First open a file named manifest.yaml:

nano manifest.yaml

Then paste in the following content.

info:
  title: 'Hello, World!'
  description: 'Say hello to the world!'
  x-21-quick-buy: '21 buy "http://AUTO:5000/hello"'
  x-21-category: utilities
  x-21-app-image: "https://cdn.filepicker.io/api/file/x6J1kiKyT9WhjmbqBrAb"
  x-21-total-price:
    min: 3000
    max: 3000
  contact:
    ## TODO: Replace this information with your own
    name: Satoshi Nakamoto
    email: satoshi@example.com
## TODO: Replace this IP address with your host IP address and port
##       You can get your IP address by running the following command
## python3 -c 'from two1.commands.util import zerotier; print(zerotier.get_address("21mkt"))'
host: "10.244.108.173:5000"
schemes:
  - http
basePath: /

Download this complete file

Where the example content above says "TODO", you will want to update the corresponding line with the correct information.

Once you have added that information to the manifest, save the file and exit the text editor. Then restart the hello world app by re-running the same command from before:

python3 hello-world.py

Now go to your second open terminal and publish your app by running the following the following command:

21 publish submit manifest.yaml

If it's successful, the output will look like this:

You might need to enter your superuser password.
Publishing Hello, World! at
http://[fcce:a977:eef4:2ea3:fd86:0000:0000:0001]:5000/ to 21mkt.

You have successfully published Hello, World! to 21mkt. You should be
able to view the listing within a few minutes at
https://21.co/harding3/app/hello-world-

Users will be able to purchase it, using 21 buy, at
https://mkt.21.co/harding3/hello-world-

After you publish your app using the instructions above, wait about 15 seconds and then search for your app the same way we did in the 21 search section:

21 search hello

The output should look something like this, although there may be more hello world apps in the marketplace when you do this. You can find your particular app by looking at the username field:

Page 1/1
+------+-------------------------+-----------+---------------+------------+---------------+
| id   | Details                 | Creator   | Price         | Category   | Rating        |
|------+-------------------------+-----------+---------------+------------+---------------|
| lwz  | Hello, World!           | harding3  | 1000 Satoshis | utilities  | Not yet rated |
|      | Say hello to the world! |           |               |            |               |
|      |                         |           |               |            |               |
+------+-------------------------+-----------+---------------+------------+---------------+

Enter the id of the app for more info, n for next page, p for the previous page, q to stop search.:

You can also search using the web page. Now that your app is listed, you can either buy it from yourself or (more interestingly) find someone to buy from you. A good place to find folks willing to buy from you is our Slack Channel at slack.21.co.

The command to buy it should be in the quick buy section of the marketplace description since you provided your IP address or Zerotier IP address in the manifest file earlier.

To learn more about hosting your app on the marketplace, please read:

Next Steps

Whew! While this was a long article, if you got through it all you should have a good sense of what 21 is: it's an app, a marketplace, a network, and a library rolled into one.

The most interesting thing you can do with 21 is build, buy, sell, and publish your own machine-payable apps to the 21 Marketplace. For ideas on what to build, take a look at the following articles:

Then come to our Slack channel at slack.21.co to discuss with others of like mind!


How to send your Bitcoin to the Blockchain

Just as a reminder, you can send bitcoin mined or earned in your 21.co balance to the blockchain at any time by running 21 flush . A transaction will be created within 10 minutes, and you can view the transaction id with 21 log. Once the transaction has been confirmed, you can check the balance in your bitcoin wallet from the command line with wallet balance, and you can send bitcoin from your wallet to another address with wallet sendto $BITCOIN_ADDRESS --satoshis $SATOSHI_AMOUNT --use-unconfirmed. The --satoshis flag allows you to specify the amount in satoshis; without it the sendto amount is in BTC, but this behavior is deprecated and will be removed soon. The --use-unconfirmed flag ensures that you can send even if you have unconfirmed transactions in your wallet.


Ready to sell your endpoint? Go to slack.21.co

Ready to try out your bitcoin-payable server in the wild? Or simply want to browse and purchase from other bitcoin-enabled servers? Head over to the 21 Developer Community at slack.21.co to join the bitcoin machine-payable marketplace hosted on the 21 peer-to-peer network.