Welcome to microraiden’s documentation!

What is µRaiden?

µRaiden (read: Micro Raiden) is a payment channel framework for frequent, fast and free ERC20 token based micropayments between two parties. It comes as a set of open source libraries, documentation, and code examples for multiple use cases, ready to implement on the Ethereum mainnet. Whereas its big brother, the Raiden Network, aims to allow for multihop transfers via a network of bidirectional payment channels, µRaiden already enables to make micropayments through unidirectional payment channels.

Try out the demos

We have deployed some demo applications that make extensive use of µRaiden in your browser. Although you need some testnet-Ether and MetaMask, it’s a very easy starting point to try out µRaiden. Just follow the instructions on https://demo.micro.raiden.network/

Next steps

If you want to start playing with microraiden, a good starting point is to check out the Tutorials section. Best you start with the developer setup and try our Blockchain Tutorial afterwards.

Documentation Content

Introduction

A quick classification

µRaiden is not part of the Raiden Network. However, it was built using the same state channel idea and implements it in a less general fashion focusing on the concrete application of micropayments for paywalled content.

The main differences between the Raiden Network and µRaiden are:

  • µRaiden is a many-to-one unidirectional state channel protocol.

In comparison, the Raiden Network is a many-to-many bidirectional solutio and implies a more complex design of channel networks. This allows the Raiden Network to efficiently send transfers without being forced to pay for opening new channels with people who are already in the network.

  • µRaiden off-chain transactions do not cost anything as they are only exchanged between sender and receiver

The Raiden Network has a more complicated incentive-based off-chain transport of transaction information, from one user to another (following the channel network path used to connect the sender and the receiver).

Sender / Receiver

Since µRaiden enables easy micropayments from one party to another, the application is structured in 2 logically separated parts:

  • the Sender or Client side of a payment
  • the Receiver or Proxy-Server side of a payment

The Sender is the one who initially deposits Ether in the µRaiden payment channel. From this point on he signs so called balance proofs with his private key. A balance-proof functions as a valid micropayment, once the Receiver gets hold of it and keeps it on his disk.

The µRaiden application has different implementations for different scenarios for the Sender side:

  • a JavaScript client that runs in the Senders browser whenever the Sender visits the Receivers webpage
  • a Python client that runs on the Senders machine and makes http requests to the Receivers Proxy-Server instance

A typical use case for the JavaScript client would be a content provider, who wants to receive micropayments for accessing paywalled content. The content provider is the Receiver in this scenario and he would integrate µRaidens Proxy-Server for example in his flask or Django backend. At the same time, the content provider would serve an implementation of µRaidens JavaScript Client from his webpage. All the consumer of the paywalled content now needs is an Ethereum account that is backed with some RDN and that is web3 accessible ( for example with MetaMask). The JavaScript client will run in the consumers browser and once it needs to sign a microtransaction the MetaMask plugin will pop up and ask for confirmation.

The Python client would get mainly used in Machine-to-Machine (M2M) applications or more customized applications without the use of a browser. In this scenario, the Sender has to actively install the client application and connect it to his standard blockchain-interface (like geth or parity).The client will then send out http-requests to a known Receiver that is running a Proxy-Server application. Price information on the requested resource will be sent from the Receiver to the Sender in a custom http-Header. Vice versa, once the Sender has processed his business-logic (like evaluating the price), he will repeat the http-request with a matching balance proof embedded in the custom http-Header. This balance proof signature represents the actual micropayment and should be followed up by the Receiver with the delivery of the requested resource.

Off-chain transactions

A visual description of the process can be found here.

The heart of the system lies in its sender -> receiver off-chain transactions. They offer a secure way to keep track of the last verified channel balance. The channel balance is calculated each time the sender pays for a resource. He is prompted to sign a so-called balance proof, i.e., a message that provably confirms the total amount of transfered tokens. This balance proof is then sent to the receiver’s server. If the balance proof checks out after comparing it with the last received balance and verifying the sender’s signature, the receiver replaces the old balance value with the new one.

Smart Contract

To be exact, there is a third party involved in µRaiden:

  • the Enforcing or Smart Contract part

This is the part where the trustless nature of the Ethereum blockchain comes into play. The contract acts as the intermediary, that locks up the initial deposit from the Sender and enforces a possible payout of the funds based on the signed balance proofs, that the Sender sent out to the Receiver without the use of a blockchain.

Once the Receiver has a balance proof, it’s easy for the Receiver to prove to the contract that the Sender owes him some tokens. With the balance proof, the contract now can reconstruct the public key of the Sender and knows with certainty that the Sender must have agreed to the updated balance.

This means that there are only 2 transactions that have to happen on the blockchain: - the initial opening of the channel with the prepaid amount the sender eventually wants to spent during the channels lifetime - the final closing of the channel, where the senders initial deposit is paid out to the receiver and sender, based on the agreed on off chain balances

If the channel runs low on funds before it is closed, the sender can increase the transferable amount of the channel with a topup transaction on-chain.

After a channel is closed, it can’t be used anymore. If the business-relationship between the same sender and receiver should revive again, a new channel has to be opened.

µRaiden uses its own token for payments which is both ERC20 and ERC223 compliant.

Closing and settling channels

A visual description of the process can be found here.

When a sender wants to close a channel, a final balance proof is prepared and sent to the receiver for a closing signature. In the happy case, the receiver signs and sends the balance proof and his signature to the smart contract managing the channels. The channel is promptly closed and the receiver debt is settled. If there are surplus tokens left, they are returned to the sender.

In the case of an uncooperative receiver (that refuses to provide his closing signature), a sender can send his balance proof to the contract and trigger a challenge period. The channel is marked as closed, but the receiver can still close and settle the debt if he wants. If the challenge period has passed and the channel has not been closed, the sender can call the contract’s settle method to quickly settle the debt and remove the channel from the contract’s memory.

What happens if the sender attempts to cheat and sends a balance proof with a smaller balance? The receiver server will notice the error and automatically send a request to the channel manager contract during the challenge period to close the channel with his latest stored balance proof.

There are incentives for having a collaborative channel closing. On-chain transaction gas cost is significantly smaller when the receiver sends a single transaction with the last balance proof and his signature, to settle the debt. Also, gas cost is acceptable when the sender sends the balance proof along with the receiver’s closing signature. Worst case scenario is the receiver closing the channel during the challenge period. Therefore, trustworthy sender-receiver relations are stimulated.

Specifications

HTTP Headers

Response Headers
200 OK
Headers Type Description
RDN-Gateway-Path bytes Path root of the channel management app
RDN-Receiver-Address address Address of the Merchant
RDN-Contract-Address address Address of RaidenMicroTransferChannels contract
RDN-Token-Address address Address of the Token contract
RDN-Price uint Resource price
RDN-Sender-Address address Address of the Client
RDN-Sender-Balance uint Balance of the Channel
402 Payment Required
Headers Type Description
RDN-Gateway-Path bytes Path root of the channel management app
RDN-Receiver-Address address Address of the Merchant
RDN-Contract-Address address Address of RaidenMicroTransferChannels contract
RDN-Token-Address address Address of the Token contract
RDN-Price uint Resource price
RDN-Sender-Address address Address of the Client
RDN-Sender-Balance uint Balance of the Channel
RDN-Balance-Signature bytes Optional. Last saved balance proof from the sender.
    + one of the following:
RDN-Insufficient-Conf irmations uint Failure - not enough confirmations after the channel creation. Client should wait and retry.
RDN-Nonexisting-Channel string Failure - channel does not exist or was closed.
RDN-Invalid-Balance- Proof uint Failure - Balance must not be greater than deposit or The balance must not decrease.
RDN-Invalid-Amount uint Failure - wrong payment value
409
  • ValueError
502
  • Ethereum node is not responding
  • Channel manager ETH balance is below limit
Request Headers
Headers Type Description
RDN-Contract-Address address Address of MicroTransferChannels contract
RDN-Receiver-Address address Address of the Merchant
RDN-Sender-Address address Address of the Client
RDN-Payment uint Amount of the payment
RDN-Sender-Balance uint Balance of the Channel
RDN-Balance-Signature bytes Signature from the Sender, signing the balance (post payment)
RDN-Open-Block uint Opening block number of the channel required for unique identification

Off-Chain sequence

(not-so-standard sequence diagram) For a better overview, also check out how the smart contract does a balance-proof validation.

REST API

µRaiden exposes a Restful API to provide insight into a channel state, balances, and it allows proxy operator to close and settle the channels.

Proxy endpoints
Getting the status of the proxy

/api/1/stats

Return proxy status: balances, open channels, contract ABI etc.

  • deposit_sum - sum of all open channel deposits
  • open_channels - count of all open channels
  • pending_channels - count of all closed, but not yet settled channels
  • balance_sum - sum of all spent, but not yet settled funds
  • unique_senders - count of all unique addresses that have channels open
  • liquid_balance - amount of tokens that are settled and available to the receiver
  • token_address - token contract address
  • contract_address - channel manager contract address
  • receiver_address - server’s ethereum address
  • manager_abi - ABI of the channel manager contract
  • token_abi - ABI of the token contract
Example Request

GET /api/1/stats

Example Response

200 OK and

{
  "deposit_sum": "268",
  "open_channels": "33",
  "pending_channels": "15",
  "balance_sum": "12",
  "unique_senders": "6",
  "liquid_balance": "334",
  "token_address" : "0x8227a53130c90d32e0294cdde576411379138ba8",
  "contract_address": "0x69f8b894d89fb7c4f6f082f4eb84b2b2c3311605",
  "receiver_address": "0xe67104491127e419064335ea5bf714622a209660",
  "manager_abi": "{ ... }",
  "token_abi": "{ ... }",
}
Channel endpoints
Getting all open channels

/api/1/channels/

Return a list of all open channels.

Example Request

GET /api/1/channels

Example Response

200 OK and

[
{
    "sender_address" : "0x5601ea8445a5d96eeebf89a67c4199fbb7a43fbb",
    "open_block"  : "3241462",
    "balance"     : "0",
    "deposit"     : "10",
},
{
    "sender_address" : "0x5176305093fff279697d3fc9b6bc09574303edb4",
    "open_block"  : "32654234",
    "balance"     : "0",
    "deposit"     : "25",
},
]
Getting all open channels for a given sender

/api/1/channels/<sender_address>

Return a list of all open channels for the sender specified in the second argument of the URL.

Example Request

GET /api/1/channels/0x5601ea8445a5d96eeebf89a67c4199fbb7a43fbb

Example Response

200 OK and

[
{
    "sender_address" : "0x5601ea8445a5d96eeebf89a67c4199fbb7a43fbb",
    "open_block"  : "3241462",
    "balance"     : "0",
    "deposit"     : "10",
    "state"       : "open",
},
]
Getting a single channel info

/api/1/channels/<sender_address>/<open_block>

Return an info about the channel, identified by sender and open block id.

Example Request

GET /api/1/channels/0x5601ea8445a5d96eeebf89a67c4199fbb7a43fbb/3241462

Example Response

200 OK and

{
    "sender_address" : "0x5601ea8445a5d96eeebf89a67c4199fbb7a43fbb",
    "open_block"  : "3241462",
    "balance"     : "0",
    "deposit"     : "10",
    "state"       : "open",
}
Cooperatively closing a channel

/api/1/channels/<sender_address>/<open_block>

Return a receiver’s signature that can be used to settle the channel immediately (by calling contract’s cooperativeClose() function).

Example Request

DELETE /api/1/channels/0x5601ea8445a5d96eeebf89a67c4199fbb7a43fbb/3241642

with payload balance - last balance of the channel

{
    "balance": 13000,
}
Example Response

200 OK and

{
    "close_signature" : "0xb30809f9a32e4f5012a3e7a7275e4f0f96eaff49f7a34747507abc3147a0975c31cf9f9aa318d1f9675d6e39f062a565213bcef4baa820f0332616f0c38324fe01",
}
Possible Responses
HTTP Code Condition
200 OK For a successful coop-close
500 Server Error Internal Raiden node error
400 Bad request Invalid address, signature, or channel doesn’t exist.

Applications

Different possible applications of uRaiden.

Proxy-Server (python)

  • a Python server that runs on the Receivers machine
Installation

It is required that you have python’s pip installed. You probably already have this dependency, but if not, please visit the official pip documentation and install pip before you proceed.

Using virtualenv

It is recommended to use a virtual environment to separate your global python application from the environment (all the dependency-packages) µRaiden likes to run in. This will fetch the latest release of µRaiden directly from the Python package index and install it:

virtualenv -p python3 env
. env/bin/activate
pip install microraiden
editable development installation

When you want to develop on the µRaiden codebase, it is best to install it in pip’s editable mode. This way, you can edit the source code directly and never worry about re-installing µRaiden - the linked application always reflects the changes you made.

To install µRaiden for development, simply run:

virtualenv -p python3 env
. env/bin/activate
git clone git@github.com:raiden-network/microraiden.git
cd microraiden

make pip-install-dev

If you don’t like our make script install, you can also run the commands manually like so:

Using a global pip3 installation

This method is not recommended, as it can interfere with your global python installation. If you absolutely must, it still works though:

sudo pip3 install microraiden
Execution

There are several examples that demonstrate how to serve custom content. To try them, run one of the following commands from the microraiden directory:

python3 -m microraiden.examples.demo_proxy --private-key <private_key_file> start

or

python3 -m microraiden.examples.wikipaydia --private-key <private_key_file> --private-key-password-file <password_file> start

By default, the web server listens on 0.0.0.0:5000. The private key file should be in the JSON format produced by Geth/Parity and must be readable and writable only by the owner to be accepted (-rw-------). A --private-key-password-file option can be specified, containing the password for the private key in the first line of the file. If it’s not provided, the password will be prompted interactively. An Ethereum node RPC interface is expected to respond on http://localhost:8545. Alternatively, you can use Infura infrastructure as a RPC provider.

Command line options

When invoking microraiden from the commandline, you have several options:

Python API

Here you can find the API of some of the important classes and methods of the Proxy Server. This documentation is autogenerated from the docstrings and type-hints in the source code. If you have further questions look in the source-code directly.

Components overview
Channel manager
Proxy

M2M-Client (python)

Installation

Since the Python client is bundled together with the Proxy-Server in one module, the installation process is the same for both.

Have a look at the Proxy Server installation.

Usage

The µRaiden client can be used as a standalone library, to make machine-to-machine payments easily available. After installation, import the following class:

from microraiden import Client

client = Client('<hex-encoded private key>')

Alternatively you can specify a path to a JSON private key, optionally specifying a file containing the password. If it’s not provided, it’ll be prompted interactively.

client = Client(key_path='<path to private key file>', key_password_file='<path to password file>')

This client object allows interaction with the blockchain and offline-signing of transactions and Raiden balance proofs.

An example lifecycle of a Client object could look like this:

from microraiden import Client

receiver = '0xb6b79519c91edbb5a0fc95f190741ad0c4b1bb4d'
privkey = '0x55e58f57ec2177ea681ee461c6d2740060fd03109036e7e6b26dcf0d16a28169'

# 'with' statement to cleanly release the client's file lock in the end.
with Client(privkey) as client:

    channel = client.get_suitable_channel(receiver, 10)
    channel.create_transfer(3)
    channel.create_transfer(4)

    print(
        'Current balance proof:\n'
        'From: {}\n'
        'To: {}\n'
        'Channel opened at block: #{}\n'  # used to uniquely identify this channel
        'Balance: {}\n'                   # total: 7
        'Signature: {}\n'                 # valid signature for a balance of 7 on this channel
        .format(
            channel.sender, channel.receiver, channel.block, channel.balance, channel.balance_sig
        )
    )

    channel.topup(5)                      # total deposit: 15

    channel.create_transfer(5)            # total balance: 12

    channel.close()

    # Wait for settlement period to end.

    channel.settle()

    # Instead of requesting a close and waiting for the settlement period to end, you can also perform
    # a cooperative close, provided that you have a receiver-signed balance proof that matches your
    # current channel balance.

    channel.close_cooperatively(closing_sig)

The values required for a valid balance proof required by the receiver end are printed above. Make sure to let them know.

Components overview
Python API

Here you can find the API of some of the important classes and methods of the Client. This documentation is autogenerated from the docstrings and type-hints in the source code. If you have further questions look in the source-code directly.

Web-Client (JavaScript)

For a quick overview on how to use the Javascript client library please refer to the README

API documentation

The autodocumented API reference currently also resides in our GitHub.

Smart Contract

Smart Contracts, Unittests and Infrastructure for RaidenPaymentChannel

Installation

The Smart Contracts can be installed separately from the other components.

Prerequisites
  • Python 3.6
  • pip
Setup
pip install -r requirements.txt

Deployment

Chain setup for testing

Note - you can change RPC/IPC chain connection, timeout parameters etc. in project.json

privtest
  1. Start the geth-node from the commandline:
geth --ipcpath="~/Library/Ethereum/privtest/geth.ipc" \
     --datadir="~/Library/Ethereum/privtest" \
     --dev \
     ---rpc --rpccorsdomain '\*' --rpcport 8545 \
     --rpcapi eth,net,web3,personal \
     --unlock 0xf590ee24CbFB67d1ca212e21294f967130909A5a \
     --password ~/password.txt

# geth console
# you have to mine yourself: miner.start()
geth attach ipc:/Users/loredana/Library/Ethereum/privtest/geth.ipc
kovan
  1. Get some testnet-Ether at the kovan-faucet
  2. Modify the project.json to change the default account
  3. Start the Parity node from the commandline:
parity --geth \
       --chain kovan \
       --force-ui --reseal-min-period 0 \
       --jsonrpc-cors http://localhost \
       --jsonrpc-apis web3,eth,net,parity,traces,rpc,personal \
       --unlock 0x5601Ea8445A5d96EEeBF89A67C4199FbB7a43Fbb \
       --password ~/password.txt \
       --author 0x5601Ea8445A5d96EEeBF89A67C4199FbB7a43Fbb
ropsten
  1. Get some testnet-Ether at the ropsten-faucet
  2. Modify the project.json to change the default account
  3. Start the geth node from the commandline:
geth --testnet \
     --rpc --rpcport 8545 \
     --unlock 0xbB5AEb01acF5b75bc36eC01f5137Dd2728FbE983 \
     --password ~/password.txt
rinkeby
  1. Get some testnet-Ether at the rinkeby-faucet
  2. Modify the /contracts/project.json to change the default account
Fast deployment

There are some scripts to provide you with convenient ways to setup a quick deployment.

# Fast deploy on kovan | ropsten | rinkeby | tester | privtest

# Following two calls are equivalent
python -m deploy.deploy_testnet  # --owner is web.eth.accounts[0]
python -m deploy.deploy_testnet \
  --chain kovan \
  --owner 0x5601Ea8445A5d96EEeBF89A67C4199FbB7a43Fbb \
  --challenge-period 500 \
  --token-name CustomToken --token-symbol TKN \
  --supply 10000000 --token-decimals 18

# Provide a custom deployed token
python -m deploy.deploy_testnet --token-address TOKEN_ADDRESS

Usage

  • from root/contracts:
# compilation
populus compile

# tests
pytest
pytest -p no:warnings -s
pytest tests/test_uraiden.py -p no:warnings -s

# Recommended for speed:
# you have to comment lines in tests/conftest.py to use this
pip install pytest-xdist==1.17.1
pytest -p no:warnings -s -n NUM_OF_CPUs

API

Generated docs

There is an Auto-Generated-API, that is compiled with soldocs.

Prerequisites

pip install soldocs
populus compile
soldocs --input build/contracts.json --output docs/contract/RaidenMicroTransferChannels.md --contracts RaidenMicroTransferChannels
Opening a transfer channel
ERC20 compatible
# approve token transfers to the contract from the Sender's behalf
Token.approve(contract, deposit)

Contract.createChannel(receiver_address, deposit)

Gas cost (testing): 120090

_images/ChannelOpen_20.png
Topping up a channel

Adding tokens to an already opened channel.

ERC223 compatible (recommended)

Sender sends tokens to the Contract, with a payload for calling topUp.

Token.transfer(_to, _value, _data)

Gas cost (testing): 54885

  • _to = Contract.address
  • _value = deposit value (number of tokens)
  • _data contains the Sender and Receiver addresses encoded in 20 bytes + the open_block_number in 4 bytes
  • in python
_data = sender_address[2:] + receiver_address[2:] + hex(open_block_number)[2:].zfill(8)
_data = bytes.fromhex(_data)
_images/ChannelTopUp_223.png
ERC20 compatible
#approve token transfers to the contract from the Sender's behalf
Token.approve(contract, added_deposit)

# open_block_number = block number at which the channel was opened
Contract.topUp(receiver_address, open_block_number, added_deposit)

Gas cost (testing): 85414

_images/ChannelTopUp_20.png
Generating and validating a balance proof

(to be updated post EIP712)

# Sender has to provide a balance proof to the Receiver when making a micropayment
# The contract implements some helper functions for that

# Balance message
bytes32 balance_message_hash = keccak256(
    keccak256(
        'string message_id',
        'address receiver',
        'uint32 block_created',
        'uint192 balance',
        'address contract'
    ),
    keccak256(
        'Sender balance proof signature',
        _receiver_address,
        _open_block_number,
        _balance,
        address(this)
    )
);

# balance_message_hash is signed by the Sender with MetaMask
balance_msg_sig

# Data is sent to the Receiver (receiver, open_block_number, balance, balance_msg_sig)
Generating and validating a closing agreement
from eth_utils import encode_hex

# Sender has to provide a balance proof to the Contract and
# a closing agreement proof from Receiver (closing_sig)
# closing_sig is created in the same way as balance_msg_sig, but it is signed by the Receiver

# Closing signature message
bytes32 balance_message_hash = keccak256(
    keccak256(
        'string message_id',
        'address sender',
        'uint32 block_created',
        'uint192 balance',
        'address contract'
    ),
    keccak256(
        'Receiver closing signature',
        _sender_address,
        _open_block_number,
        _balance,
        address(this)
    )
);

# balance_message_hash is signed by the Sender with MetaMask
balance_msg_sig

# balance_msg_sig is signed by the Receiver inside the microraiden code
closing_sig

# Send to the Contract (example of collaborative closing, transaction sent by Sender)
Contract.transact({ "from": Sender }).cooperativeClose(
    _receiver_address,
    _open_block_number,
    _balance,
    _balance_msg_sig,
    _closing_sig
)
Balance proof / closing agreement signature verification:
sender_address = Contract.call().extractBalanceProofSignature(receiver_address, open_block_number, balance, balance_msg_sig)

receiver_address = Contract.call().extractClosingSignature(sender_address, open_block_number, balance, closing_sig)
Closing a channel
# 1. Receiver calls Contract with the sender's signed balance message = instant close & settle
# 2. Client calls Contract with receiver's closing signature = instant close & settle
# Gas cost (testing): 71182
Contract.cooperativeClose(receiver_address, open_block_number, balance, balance_msg_sig, closing_sig)

# 3. Client calls Contract without receiver's closing signature = challenge period starts, channel is not settled yet
# Gas cost (testing): 53876
Contract.uncooperativeClose(receiver_address, open_block_number, balance)

# 3.a. During the challenge period, 1. can happen.

# 3.b. Client calls Contract after settlement period ends
# Gas cost (testing): 40896
Contract.settle(receiver_address, open_block_number)
_images/ChannelCycle.png

Tutorials

Development setup

Requirements

It is required that you have python’s pip, python3.5 and git installed. You can visit the official pip documentation and install pip before you proceed.

Using virtualenv

It is recommended to use a virtual environment to separate your global python application from the environment (all the dependency-packages) µRaiden likes to run in:

   python3 -m venv env
   . env/bin/activate

A short check of the location of your python version should show the :code:`./env/bin/python` binary.
which python

To switch back to your usual python executable, simply deactivate the venv:

deativate

There are more sophisticated tools to keep track of your virtualenvs and python installations. For example, check out pyenv in combination with pyenv-virtualenv.

µRaiden installation for development

When you want to develop on the µRaiden codebase, it is best to install it in pip’s editable mode. This way, you can edit the source code directly and never worry about re-installing µRaiden - the linked application always reflects the changes you made. To install µRaiden for development, download the repository and run our simplified install script with:

git clone git@github.com:raiden-network/microraiden.git
cd microraiden
make pip-install-dev

Blockchain setup

In order to follow our tutorials or develop your own µRaiden applications, there are some additional requirements to be fullfilled. If you want to develop applications that function as the Receiver you have to connect to the Ethereum blockchain through one of the Ethereum node applications. There are others, but we focus on geth, the Go implementation.

Running geth

The following components have to be installed in order to run the tutorials:

Geth must be up and running, listening on RPC 8545 and completely synced with Ropsten Optional: To create an account, get Ropsten ETH (RETH) and export the private key, MetaMask must be installed and connected to Ropsten Optional: To use the echo_client, you have to acquire TKN. On the main page (https://github.com/raiden-network/microraiden) the Token addresses are listed, for Ropsten it can be found here Setup a Ropsten-synced Geth

The quick start requires that your Geth client is synced to the Ropsten testnet. Geth should answer RPC calls on http://localhost:8545 and have the APIs eth, net, web3 and personal accessible.

Note: as of Geth version 1.8.0, these parameters are required to start Geth in the correct mode:

geth --testnet --syncmode "fast" \
     --rpc --rpcapi eth,net,web3,personal \
     --cache=1024 \
     --rpcport 8545 --rpcaddr 127.0.0.1 \
     --rpccorsdomain "*"
Funded Ropsten account with MetaMask

Note: You don’t have to follow these steps if you have an account on Ropsten already preloaded with Ropsten Ether and know how to export the private key of the preloaded account.

After successful installation of MetaMask, just follow the steps mentioned in the screenshots to create a new account, get Ropsten Ether at a faucet and export the private key of this new, Ether preloaded account. We will use the private key for js-Client applications in the Tutorials. Your MetaMask account will represent the Sender of a microtransaction.

Buy TKN on Ropsten

To be able to use the echo client, you have to get the “TKN” Token configured for the RaidenMicroTransferChannels on Ropsten.

With our demo app

The easiest way to get some TKN on the Ropsten-network is to use our JavaScript application that we host with our µRaiden live-demos.

Altough this is part of a specific demo-application, you can just use the upper part of the dialogue and forget about the lower half.

  1. Choose the browser with your Ropsten-ETH loaded MetaMask account activated
  2. visit e.g. the fortune cookie demo here
  3. Click on Buy to exchange your RopstenETH (RETH) for TKN (in 50 TKN increments)

A dialogue will pop up in MetaMask that asks for your confirmation of the generated transaction.

  1. Accept the transaction

To check wether the exchange of TKN was sucessful, you can add TKN as a custom token to MetaMask.

  1. Under the Tokens tab, choose Add token and fill in the TKN address again:
0xFF24D15afb9Eb080c089053be99881dd18aa1090
  1. Once the transaction was succesful, you should see your TKN balance under the Tokens tab
With MyEtherWallet

If you want to have a little bit more control over the exchange of token, you can also use MyEtherWallet to interact with the Smart-Contract directly:

  1. Choose the browser with your Ropsten-ETH loaded MetaMask account activated
  2. Go to https://www.myetherwallet.com/ and go through their advice on phishing-precautions.
  3. Select the Ropsten Network in the tab in the upper right
  4. click on the Contracts tab and fill in the contract address:
0xFF24D15afb9Eb080c089053be99881dd18aa1090
  1. fill in the ABI field with the data you get here:
  1. Choose the mint function and use MetaMask to access your wallet
  1. put in an amount of RopstenETH (RETH) you want to exchange for TKN (0.1 RETH will get you 50 TKN)

A dialogue will pop up in MetaMask that asks for your confirmation of the generated transaction.

  1. Accept the transaction

To check wether the exchange of TKN was sucessful, you can add TKN as a custom token to MetaMask.

  1. Under the Tokens tab, choose Add token and fill in the TKN address again:
0xFF24D15afb9Eb080c089053be99881dd18aa1090
  1. Once the transaction was succesful, you should see your TKN balance under the Tokens tab

Now you’re good to go! Check out the other Tutorials and get started with microraiden!

Your first microtransaction

In order to get you started, we created an example application for you, that receives micropayments and some parameter over a http-request - and simply echos this parameter when the micropayment was valid. Please follow the microraiden installation instructions and the instructions to set up geth.

Starting the µRaiden Receiver

From the root directory of microraiden, start:

python microraiden/examples/echo_server.py --private-key microraiden/examples/pk_tut.txt

Note: the file pk_tut.txt should contain your private key as exported in the Blockchain Setup guide by MetaMask.

Starting the µRaiden Sender

To actually start the request for resource /hello, we will fire up the µRaiden client with the prefunded account.

While the Receiver is still running (in another terminal window for example), execute this command from the µRaiden root folder:

python microraiden/examples/echo_client.py --private-key microraiden/examples/pk_tut.txt --resource /echofix/hello

After some seconds, you should get the output

INFO:root:Got the resource /echofix/hello type=text/html; charset=utf-8:
hello
This means:
  • a channel has been created
  • a deposit of 50 aTKN has been escrowed
  • a micropayment of 1 aTKN has been transferred to the receiver
  • the receiver returned the requested resource (the “hello” parameter in this simple case) for this payment

Congratulations, you just performed your first micropayment!

Paywall tutorial

Before starting, please follow the microraiden installation instructions and the instructions to set up geth.

Introduction

In this tutorial we will create a simple paywalled server that will echo a requested path paramter, payable with a custom token. You can find example code for this tutorial in microraiden/examples/echo_server.py.

Requirements

Please refer to README.md to install all required dependencies. You will also need a Chrome browser with the MetaMask plugin.

Setting up the proxy
Initialization
For initialization you will have to supply the following parameters:
  • The private key of the account receiving the payments (to extract it from a keystore file you can use MyEtherWallet’s “View Wallet Info” functionality).
  • A file in which the proxy stores off-chain balance proofs. Set this to a path writable by the user that starts the server.
from microraiden.make_helpers import make_paywalled_proxy
app = make_paywalled_proxy(private_key, state_file_name)

microraiden.make_helpers.make_paywalled_proxy() is a helper that handles the setup of the channel manager and returns a microraiden.proxy.paywalled_proxy.PaywalledProxy instance. Microraiden also includes other helpers that parse common commandline options. We are not using them in this example - for a quick overview how to use them, refer to i.e. microraiden.examples.demo_proxy.__main__()

The channel manager will start syncing with the blockchain immediately.

Resource types

Now we will create a custom resource class that simply echoes a path-parameter of the user’s request for a fixed price. The workflow is the same as with the Flask-restful: Subclass microraiden.proxy.resources.Expensive and implement the HTTP methods you want to expose.

from microraiden.proxy.resources import Expensive

class StaticPriceResource(Expensive):
    def get(self, url: str, param: str):
            log.info('Resource requested: {} with param "{}"'.format(request.url, param))
            return param

We add one static resource to our PaywalledProxy instance. The url argument will comply with standard flask routing rules.

app.add_paywalled_resource(
    cls=StaticPriceResource,
    url="/echofix/<string:param>",
    price=5
)

The resource will then be available for example at the URI /echofix/foo. Only after a payment of 5 tokens, the proxy will send the foo parameter back to the user and will set the Content-Type header appropriately. Without payment, the server responds with 402 Payment Required.

A probably more useful paywalled resource is a URL. This is useful to fetch content from a remote CDN:

from microraiden.proxy.content import PaywalledProxyUrl

app.add_paywalled_resource(
    cls=PaywalledProxyUrl,
    url="cdn\/.*",
    resource_class_kwargs={"domain": 'http://cdn.myhost.com:8000/resource42'}
)

Note, that the kwargs for the constructor of the resource-class (here our PaywalledProxyUrl) have to be passed as a dict with the resource_class_kwargs argument. In this case, the domain kwarg is the remote URL specifying where to fetch the content from.

Setting a price for the resource dynamically

We can also construct the Resource in a way that the price will be dynamically calculated, e.g. based on the requests parameters.

class DynamicPriceResource(Expensive):
    def get(self, url: str, param: str):
            log.info('Resource requested: {} with param "{}"'.format(request.url, param))
            return param

    def price(self):
            return len(request.view_args['param'])


app.add_paywalled_resource(
    cls=DynamicPriceResource,
    url="/echodyn/<string:param>",
)

Here, the price to be paid is the length of the requested string. A request of the /echodyn/foo resource, would therefore require a payment of 3 tokens.

Starting/stopping the proxy

You start proxy by calling run() method. This call is non-blocking – the proxy is started as a WSGI greenlet. Use join() to sync with the task. This will block until proxy has stopped. To terminate the server, call stop() from another greenlet.

app.run(debug=True)
app.join()
Accessing the content
Browser

To access the content with your browser, navigate to the URL of the resource you’d like to get. You’ll be faced with a paywall – a site requesting you to pay for the resource. To do so, you first have to open a new channel. If you have the MetaMask extension installed, you can set the amount to be deposited to the channel. After confirming the deposit, you can navigate and payments will be done automatically.

Side notes
Proxy state file

Off-chain transactions are stored in a sqlite database. You should do regular backups of this file – it contains balance signatures of the client, and if you lose them, you will have no way of proving that the client is settling the channel using less funds than he has actually paid to the proxy.

Indices and tables