Está en la página 1de 66

Smart contracts powered by Bitcoin

Technical Course
Blockchain & Smart contracts powered by RSK

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

RSK EDUCATE TERMS AND CONDITIONS

We at RSK believe that blockchain technologies are an enabler for a better, more inclusive
financial system that will improve the life of millions. In order to reach this goal we need the
technology to become massively adopted. Education plays a key role on this objective.

RSK Labs Ltd. has produced a Technical Course Manual to help Educational Institutions set
up courses to introduce their students to Bitcoin, Blockchain and the RSK Platform. The
Technical Course Manual offers a wide range of topics specially designed to cover the
principal aspects of these new technologies, using information and material from RSK Labs
Ltd. own production and from other different specialized sources which are detailed in the
manual.

The Technical Course Manual has been created by RSK Labs Ltd. using different sources
which are expressly quoted in the materials. Please note that the Technical Course Manual
and its material may be modified or translated. In such cases, RSK Labs Ltd. will have to be
credited as the original provider of the Technical Course Manual with reference to the
respective sources, and it shall be stated clearly that changes have been made to the
original Technical Course Manual and that RSK Labs Ltd. has not participated neither
authorized such modified or translated version of the course and as a result does not
guarantee the correctness of such version.

The Technical Course Manual and any of its chapters, as well as any modification or
translation thereof, shall be used by the educational Institutions with the sole objective of
setting up courses and explaining its students about the matters mentioned hereby. The
Technical Course Manual shall not be sold or commercialized by the educational Institutions
without the express consent of RSK Labs Ltd. It can however be freely distributed to
students, trainers or any other party interested in learning about the subject, with the sole
need to include this note.

The effective reception or the first use of the Technical Course Manual by the educational
Institution shall be considered an acceptance of these terms and conditions.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Technical Course
Index
MODULE 1: Bitcoin & Blockchain 5
Bitcoin Fundamentals 5
How does it works? 6
Cryptography 7
What is a Hash? 7
How do public/private keys work? 8
What is a Merkle (or hash) tree? 4 9
Mining and blocks 10
What is bitcoin mining? 11
What’s about the ‘Proof of Work’ (POW) problem? 11
Blocks 12
So, what is a blockchain? 13
What is the double-spend problem? 14
The most prominent consensus mechanisms 15
Proof-of-Work (PoW) 15
Proof-of-Stake (PoS) 15
Delegated proof of stake (DPoS) 16
Leader-Based Consensus (LBC) 16
Round Robin (RR) 16
Federated Consensus (FC) / Federated Byzantine Agreement (FBA) 16
PBFT (Practical Byzantine Fault Tolerance) 17
Proof-of-Activity 17
Proof-of-Burn 17
Proof-of-Capacity 18
Proof-of-Elapsed time 18
Distributed Concurrence (N2N - Corda) 18
Public, private and consortium blockchains 20
Public blockchain 21
Private blockchain 21
Consortium blockchain 21

MODULE 2: Smart Contracts 23


What’s a Smart Contract 23
Traditional Contracts 23
Innovation 23
Advantages of Smart Contracts over traditional solutions 24
Use cases 24
DApps 25
Definition of a DApp 25
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

Nomenclature and its importance 26


Classification of DApps 26
Current Status 27
Example of DApp 28
What is Ethereum? 29
The DAO 29

MODULE 3: RSK 30
What’s RSK? 30
RSK Pillars 30
Goals 30
Can Bitcoin run smart-contract script? 31
How does it work? 31
2-way peg 31
Sidechain 32
Drivechain 33
RSK 2Way-Peg Method 33
Merge Mining 36

MODULE 4: Programming smart contracts 37


SOLIDITY 37
Introduction 37
Overview 37
Accounts 37
Transactions 38
Installing Solidity & Building from source 38
Using web3.js and RSK DApps 38
Structure of a Contract 39
State Variables 39
Functions 39
Function Modifiers 39
Events 40
Structs Types 40
Enum Types 40
Smart contract sample 41
Construct 41
Deploy the Contract in the blockchain 42
Killing a Contract 42
A more realistic example 43
Step by step example 43

Subcurrency Example 45
Hands-on-case 47

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Voting 47
Possible Improvements 50
Creating tokens 50

MODULE 5: Working on RSK 54


Getting started with an RSK Node 54
Compile and Run a RSK Node Locally 54
Connecting a RSK node to the Testnet 54
Utilities for the Ginger Testnet 54
Truffle & TestRPC 54
TestRPC 55
Running TestRPC 55
Starting Truffle 55
Init a new Truffle project 55
Verifying Truffle configuration 56
Testing Truffle project 56
Playing Around 56
Running Tests 56
Creating our first Smart Contract 56
Truffle Console 56
Connecting Truffle to RSK node 56
Configure Truffle to connect to RSK Node 56
Check our account 57
Using a faucet to get some Bitcoins 57
Checking node for running correctly 58
Checking whose mined blocks 59
Publishing a contract 60
Checking Truffle configuration 60
Interacting with the contract 61
2-Way Peg Instructions for users (Testnet) 62
Requirements 62
Sending money from BTC to RSK 62
Sending money from RSK to BTC 64

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

MODULE 1: Bitcoin & Blockchain


Bitcoin Fundamentals
Bitcoin is a cryptocurrency and an electronic payment system invented by an unidentified
programmer, or group of programmers, under the name of Satoshi Nakamoto. Nakamoto
introduced bitcoin on 31 October 2008 to a cryptography mailing list by publishing the White
Paper “​Bitcoin: A Peer-to-Peer Electronic Cash System​”1, and released as open-source
software in 2009.
The system is peer-to-peer, and transactions take place between users directly, without an
intermediary. These transactions are verified by network ​nodes and recorded in a public
distributed ledger called the ​blockchain​, which uses bitcoin as its unit of account. Since the
system works without a central repository or single administrator, bitcoin is called the first
decentralized digital currency. Bitcoin is the largest of its kind in terms of total market value. 2
Bitcoins are created as a reward in a competition in which users offer their computing power
to verify and record bitcoin transactions into the blockchain. This activity is referred to as
mining​ and successful miners are rewarded with transaction fees and newly created bitcoins.
You can take a use the ​following video with a more technical explanation of what is Bitcoin
and how does it work.

Technically, Bitcoin consists of:

● A decentralized peer-to-peer network (the ​Bitcoin protocol​)


● A public transaction ledger (the ​blockchain​)
● A set of rules for independent transaction validation and currency issuance
(​consensus rules​)
● A mechanism for reaching global decentralized consensus on the valid blockchain
(​Proof-of-Work ​algorithm)

1
"Bitcoin: A Peer-to-Peer Electronic Cash System." ​https://bitcoin.org/bitcoin.pdf​. Accessed 5 May.
2017.
2
"CoinMarketCap." ​https://coinmarketcap.com/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

One of the most interesting thing is that ​blockchain ​promises disruptive


changes, because empowers the '​Internet of Value​' that represents a world where money is
exchanged at the speed in which information moves today. Transactions would occur in
real-time and across global networks, solving the problem of international payments systems
that are not interoperable. And what is more: as it does not need intermediaries, the concept
goes further and in turn favors the ​social inclusion.​

In this module we will talk about the technology of blockchains, which as mentioned is a
ledger composed of blocks containing transactions between peers, incorporated into the
chain through a process called 'mining' that requires a lot of computing power and involves
concepts of cryptography. We will also look at some of the best known consensus
mechanisms that are used in the blockchains ecosystem.

How does it works?


Let’s explain the usual process of sending bitcoins on the blockchain, with a high level
example. Keep in mind the new concepts that appear briefly explained in the example (in
bold), which will be deepened in this module.

1. Nick opens his bitcoin wallet. This implies that Nick is indirectly creating his own
bitcoin address. ​He’s supposed to get some bitcoins.
2. Nick wants to transfer bitcoins to Rose. So, he scans or copy Rose’s bitcoin address.
3. Nick fills the amount of bitcoins he wants to transfer and the fee he is going to pay for
this ​transaction​. So, a transaction is the ​basic operation in the Bitcoin System and it
includes ​inputs, outputs​ and the a​ mount ​of bitcoin that will be transferred.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

4. Before sending the new transaction to the blockchain, the wallet


signs it using Nick’s ​private key​.
5. Now, the transaction is sent to the closest node on the bitcoin network. Then it is
propagated into the network and verifies (​basic checks: eg. there are enough bitcoins
on the origin wallet, structure, etc.). After it successfully passes verification it goes
and sits inside the “Mempool” (short for Memory Pool) and patiently awaits until a
miner picks it up to include it in the next ​block​ to ​be mined​.
6. It’s ​mining time ​and miners pick up the transactions (first those who pays more
transaction fee) and group them into blocks trying to solve the ​Proof Of Work (or
POW - a consensus algorithm)​ and calculate a certain ​hash function.
7. The miner who get it propagates the new block to the network.
8. The nodes verify the result and propagate the block.
9. Now Rose sees the first ​confirmation​.
10. New confirmations appear with each new block that is created and ​linked​.

So, first of all, let’s explain some cryptographic terms that are used in blockchains. Then,
let’s look in depth all the concepts we have included in the example above.

Cryptography
There are several cryptographic technologies that make up the essence of Bitcoin.
In this submodule is explained:
- What is a Hash function?
- How do public/private keys work?
- What is a Merklee (or hash) tree?

What is a Hash?
Cryptographic hash functions are mathematical operations run on digital data. ​In Bitcoin, all
the operations use ​SHA256​ as the underlying ​cryptographic hash function​.
SHA (Secure Hash Algorithm)3 is​ a set of cryptographic hash functions designed by the
United States National Security Agency (NSA).
To put it in simple term, a Hash function is like a black box​, where you input any kind of
digital information of any size, and the result (output) is an alphanumeric string (e.g.:
0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855​). I​n the case
of SHA-256 the output is 32 bytes.
This function has 2 characteristics:
1) Unequivocal: the hash (output) is like the fingerprint of the input data. From a human
fingerprint you can´t create the human. So from the hash of a digital input, you can´t
create the original digital input.
2) Collision Resistant: nobody should be able to find two different input values that
result in the same hash output. In other words, for any different input, there will be
different outputs always. This allows to use this function to check ​Data Integrity by

3
"SHA-2 - Wikipedia." ​https://en.wikipedia.org/wiki/SHA-2​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

comparing the computed "hash" (the output from execution of the


algorithm) to a known and expected hash value, a person ​can determine the data's
integrity. For example, computing the hash of a downloaded file and comparing the
result to a previously published hash result can show whether the download has
been modified or tampered with.

Learn more about Hash function in ​this video.

But why is hash so important in blockchain?


That’s because is part of the mining process and miners responsibility: the miners pick some
transactions up, and using them as part of the input, they try to calculate a hash function to
provide a new block to the chain.

How do public/private keys work?


Now that we have the basics, let's find out how to create a Bitcoin Address.
1. The first step is to have a reliable source of randomness and get a random number
(256-bit)

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

2. Next, you need to apply a SHA256 to that number and you will
get the private key (k). [Unequivocal Process]
3. By applying elliptic curves (a cryptographic technique) we obtain the public key (K),
as explained above.
4. Then, SHA 256 and RIPEMD160 (a different hash function) is applied and we finally
get the Bitcoin Address. [Unequivocal Process]
5. You can show the address in many different format. The most common is with a QR
Code.

Process to generate a bitcoin public address from a random number.

You can find a more detailed process ​here.

What is a Merkle (or hash) tree? 4​


In cryptography and computer science, a hash tree or Merkle tree is a ​tree in which every
non-leaf node is labelled with the ​hash of the labels or values (in case of leaves) of its child
nodes. Hash trees allow efficient and secure verification of the contents of large data
structures. Hash trees are a generalization of ​hash lists​ and ​hash chains​.
Demonstrating that a leaf node is a part of the given hash tree requires processing an
amount of data proportional to the ​logarithm of the number of nodes of the tree;​[1] this
contrasts with hash lists, where the amount is proportional to the number of nodes. ​You can
find more details view reading the patent.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Image 1: An example of a binary hash tree. Hashes 0-0 and 0-1 are the hash values of data
blocks L1 and L2, respectively, and hash 0 is the hash of the concatenation of hashes 0-0
and 0-1.

And why is merkle (or hash) tree so important in blockchain?


The Merkle tree allows verifying that a transaction exists in the block without having the
entire block, by following its Merkle branch.

Seen the previous concepts of cryptography, it is time to go deeper into some blockchain
concepts.

Mining and blocks


As shown in the example, each bitcoin sending operation requires an address from, an
address to, and the amount to be sent. Also, an additional value is included that will be
destined to the miner that includes this operation in a block. These components create a
new ​transaction​, and it needs to be sent to the system.

Transaction components

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Hence, the transaction is sent to the closest node on the bitcoin network.
It expects to be added to the blockchain by a ​miner​.

What is bitcoin mining?


Mining is a record-keeping service. Miners keep the blockchain consistent, complete, and
unalterable by repeatedly verifying and collecting newly broadcast transactions into a new
group of transactions called ​block​.
The process implies:

1. Bundle pending transactions in a block (miners usually choose those with high fee)
2. Verify if transaction are all valid
3. Select the header of the most recent block in the blockchain and insert it into new
block, as a hash. So, each new block contains the hash of the previous block, which
links them, thus giving the blockchain its name
4. Solve the Proof of Work problem
5. When the solution is found, the new block is added to the local blockchain and
propagated to the network

The blocks are linked by their hashes

What’s about the ‘Proof of Work’ (POW) problem?


In order to be accepted by the rest of the network, a new block must contain a so-called
proof-of-work​. The proof-of-work requires miners to find a number called a ​nonce​, such
that when the block content is ​hashed ​along with the nonce, the result is numerically
smaller than the network's difficulty target. This proof is easy for any node in the network
to verify, but extremely time-consuming to generate, as for a secure cryptographic hash,
miners must try many different nonce values (usually the sequence of tested values is 0,
1, 2, 3,...) before meeting the difficulty target.
Every 2016 blocks (approximately 14 days), the difficulty target is adjusted based on the
network's recent performance, with the aim of keeping the average time between new
blocks at ten minutes. In this way the system automatically adapts to the total amount of
mining power on the network.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Honest generators only build onto a block (by referencing it in blocks they
create) if it is the latest block in the longest valid chain. "Length" is calculated as total
combined difficulty of that chain, not number of blocks, though this distinction is only
important in the context of a few potential attacks. A chain is valid if all of the blocks and
transactions within it are valid, and only if it starts with the ​genesis block (that’s the first
block in blockchain)​.
Each block is guaranteed to come after the previous block chronologically because the
previous block's hash would otherwise not be known. And each block is also computationally
impractical to modify once it has been in the chain for a while because every block after it
would also have to be regenerated. These properties are what make ​double-spending of
bitcoins very difficult (we’ll see this problem later).
For any block on the chain, there is only one path to the genesis block. Coming from the
genesis block, however, there can be forks. One-block forks are created from time to time
when two blocks are created by different miners just a few seconds apart. When that
happens, generating nodes build onto whichever one of the blocks they received first.
Whichever block ends up being included in the next block becomes part of the main chain
because that chain is longer. More serious forks have occurred after fixing bugs that
required backward-incompatible changes.
Blocks in shorter chains (or invalid chains) are not used for anything. When the bitcoin client
switches to another, longer chain, all valid transactions of the blocks inside the shorter chain
are re-added to the pool of queued transactions and will be included in another block. The
reward for the blocks on the shorter chain will not be present in the longest chain, so they
will be practically lost, which is why a network-enforced 100-block maturation time for
generations exists.
These blocks on the shorter chains are often called "​orphan​" blocks. This is because the
generation transactions do not have a parent block in the longest chain, so these generation
transactions show up as orphan in the listtransactions RPC call. Several pools have
misinterpreted these messages and started calling their blocks "orphans". In reality, these
blocks have a parent block, and might even have children.
Because a block can only reference one previous block, it is impossible for two forked chains
to merge.

Blocks
Structurally each block has a ​header ​and ​content​.
Header ​contains these fields:
Field4 Description

Version A version number to track software/protocol upgrades

Previous A reference to the hash of the previous (parent) block in the


Block Hash chain

Merkle Root A hash of the root of the merkle tree of this block’s transactions

4
"GitHub - bitcoinbook/bitcoinbook: Mastering Bitcoin - Unlocking digital ...."
https://github.com/bitcoinbook/bitcoinbook​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

Timestamp The approximate creation time of this block (seconds from Unix
Epoch)

Difficulty The proof-of-work algorithm difficulty target for this block


Target

Nonce A counter used for the proof-of-work algorithm

Block Header fields description

Content ​is composed of the transactions chosen for the block.


The following is an example of how you can view a block from a ​blockchain explorer​:

A block from RSK Testnet explorer

So, what is a blockchain?


A blockchain is a digital ledger that keeps a record of all ​transactions ​taking place on a
peer-to-peer network.
A ​blockchain is a set of blocks ​containing information that are connected between each
other using ​cryptographic techniques​. ​The information is ​unalterable and is ​shared for
all nodes ​participating in a system based on the Bitcoin protocol. A full copy of a
currency's blockchain contains every ​transaction ​ever executed in the currency. With this
information, one can find out how much value belonged to each ​address at any point in
history.

It’s a good idea to watch this video about ​blockchain.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

There are some other topics related to the blockchains that we will see below.
Earlier, ​the problem of double spending was mentioned, and it was said that it is solved in
Bitcoin. Also, it’s necessary to talk about ​consensus algorithms​, the ones which allow
connected machines to work together as a group that can even survive if some of its
members fail.

What is the double-spend problem?


Double-spending is the result of successfully spending some money more than once. Bitcoin
protects against double spending by verifying each transaction added to the ​blockchain to
ensure that the inputs for the transaction had not previously already been spent.
Other electronic systems prevent double-spending by having a master authoritative source
that follows business rules for authorizing each transaction. Bitcoin uses a decentralized
system, where a consensus among nodes following the same protocol is substituted for a
central authority.
Bitcoin has some exposure to fraudulent double-spending when a transaction is first made,
with less and less risk as a transaction gains ​confirmations​.

You can find high level ​explanation in this video


And here you can find an ​interesting conversation about what happen if bitcoins are spent
simultaneously

The most prominent consensus mechanisms


Certainly, building consensus is not a new concept. Consensus has been around for as long
as human beings have lived together. In its most basic form, it’s just a way for a diverse
group to make decisions without con ict. According to Edward Shils’ “The Concept of
Consensus,” three things are needed for a consensus:
– The common acceptance of laws, rules, and norms
– The common acceptance of institutions that apply these laws and rules

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

– A sense of identity or unity, so group members accept that they’re


equal in respect to the consensus.

Consensus began as a concept for societies, but it’s now an important part of computer
science too. In the last 30 years, consensus mechanisms in the computer world have gone
from an abstract idea to the backbone of distributed ledger technology.

In distributed ledgers, a consensus mechanism is the way in which a majority (or, in some
mechanisms, all) of network members agree on the value of a piece of data or a proposed
transaction, which then updates the ledger. In other words, a consensus mechanism is a set
of rules and procedures that maintains a coherent set of facts among the participating
nodes.
Consensus algorithms allow connected machines to work together as a group that can even
survive if some of its members fail. This tolerance of failure is another big advantage of
blockchains and distributed ledgers, which have a kind of redundancy built in.

Consensus protocols or consensus platforms lie at the core of distributed ledger


technologies. There is a great diversity of algorithms for building consensus based on
requirements like performance, scalability, consistency, data capacity, governance, security,
and failure redundancy.

Now let´s dive into the different consensus Techniques being developed on the blockchain
ecosystem:

Proof-of-Work (PoW)
In proof of work, miners compete to add the next block (a set of transactions) in the chain by
racing to solve a extremely difficult cryptographic puzzle. The first to solve the puzzle, wins
the lottery. As a reward for his or her efforts, in Bitcoin, the miner receives 12.5 newly minted
bitcoins – and a small transaction fee (as May 2017). An important amount of energy is
consumed by all the miners.

Proof-of-Stake (PoS)
In this type of consensus algorithm5, instead of investing in expensive computer equipment
in a race to mine blocks, a 'validator' invests in the coins of the system.
Note the term validator. That's because no coin creation (mining) exists in proof of stake.
Instead, all the coins exist from day one, and validators (also called stakeholders, because
they hold a stake in the system) are paid strictly in transaction fees.
In proof of stake, your chance of being picked to create the next block depends on the
fraction of coins in the system you own (or set aside for staking). A validator with 300 coins
will be three times as likely to be chosen as someone with 100 coins.
Once a validator creates a block, that block still needs to be committed to the blockchain.
Different proof-of-stake systems vary in how they handle this. In Tendermint, for example,

5
"A (Short) Guide to Blockchain Consensus Protocols - CoinDesk." 4 Mar. 2017,
http://www.coindesk.com/short-guide-blockchain-consensus-protocols/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

every node in the system has to sign off on a block until a majority vote is
reached, while in other systems, a random group of signers is chosen.

Delegated proof of stake (DPoS)


Tries to combine proof-of-stake and proof-of-work characteristics. Uses a decentralized
voting process through what are known as witnesses as a way to mitigate against potential
network centralization. It has flexibility of the blockchain parameters, e.g., fees, number of
witnesses, block interval, block rewards, etc. are all configurable by the committee, which is
a separate group of elected stakeholders from the witnesses, which do not receive any
rewards, but the ability to manipulate the global blockchain parameters by vote and applied
in a maintenance window.

Leader-Based Consensus (LBC)


The nodes temporarily elect one node to be a leader. The leader is then responsible for
validating transactions. Juno allows every message to be encrypted in whatever method the
user prefers.

Round Robin (RR)


Used in private blockchain where mining is restricted to a set of identifiable entities. So
Round Robin resolves the dilemma posed by private blockchains, in which one participant
can monopolize the mining process. The solution lies in a constraint on the number of blocks
which may be created by the same miner within a given window. This enforces a round​ robin
schedule, in which the permitted miners must create blocks in rotation in order to generate a
valid blockchain.

Federated Consensus (FC) / Federated Byzantine Agreement (FBA)6


Federated Consensus achieves robustness through quorum slices—individual trust
decisions made by each node that together determine system-level quorums. Slices bind the
system together much the way individual networks’ peering and transit decisions now unify
the Internet. FC has modest computing and financial requirements compared to
decentralized PoW and PoS.
You can find more information on how it works on Stellar here​.

PBFT (Practical Byzantine Fault Tolerance)


Each node maintains an internal state (ongoing specific information or status). When a node
receives a message, they use the message in conjunction with their internal state to run a
computation or operation. This computation in turn tells that individual node what to think
about the message in question. Then, after reaching his individual decision about the new
message, that node shares that decision with all the other nodes in the system. A consensus
decision is determined based on the total decisions submitted by all nodes.7

6
"The Stellar Consensus Protocol: A Federated Model for Internet-level ...."
https://www.stellar.org/papers/stellar-consensus-protocol.pdf​.
7
"practical byzantine fault tolerance algorithm (PBFT ... - Its blockchain." 15 Feb. 2017,
http://itsblockchain.com/2017/02/15/practical-byzantine-fault-tolerance-algorithm-pbft-consensus/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

Among other considerations, this method of establishing consensus


requires less effort than other methods. However, it comes at the cost of anonymity on the
system.
There are some other variations of the PBFT like these one:
● Derived PBFT (Hyperledger)
● RBFT - Redundant Byzantine Fault Tolerance - (Evernym)
● SBFT - Simplified Byzantine Fault Tolerance - (Chain)

Proof-of-Activity
Proof of activity8 is a hybrid approach that combines both proof of work and proof of stake.
In proof of activity, mining kicks off in a traditional proof-of-work fashion, with miners racing
to solve a cryptographic puzzle. Depending on the implementation, blocks mined do not
contain any transactions (they are more like templates), so the winning block will only
contain a header and the miner's reward address.
At this point, the system switches to proof of stake. Based on information in the header, a
random group of validators is chosen to sign the new block. The more coins in the system a
validator owns, the more likely he or she is to be chosen. The template becomes a
full-fledged block as soon as all of the validators sign it.
If some of the selected validators are not available to complete the block, then the next
winning block is selected, a new group of validators is chosen, and so on, until a block
receives the correct amount of signatures. Fees are split between the miner and the
validators who signed off on the block.
Criticisms of proof of activity are the same as for both proof of work (too much energy is
required to mine blocks) and proof of stake (there is nothing to deter a validator from double
signing).

Proof-of-Burn
With proof of burn, instead of pouring money into expensive computer equipment, you 'burn'
coins by sending them to an address where they are irretrievable. By committing your coins
to never-never land, you earn a lifetime privilege to mine on the system based on a random
selection process.
Depending on how proof of burn is implemented, miners may burn the native currency or the
currency of an alternative chain, like bitcoin. The more coins you burn, the better chance you
have of being selected to mine the next block.
Over time, your stake in the system decays, so eventually you will want to burn more coins
to increase your odds of being selected in the lottery. (This mimics bitcoin's mining process,
where you have to continually invest in more modern computing equipment to maintain
hashing power.)
While proof of burn is an interesting alternative to proof of work, the protocol still wastes
resources needlessly. Another criticism is that mining power simply goes to those who are
willing to burn more money.
The only coin that uses proof of burn is slimcoin, a cryptocurrency based on peercoin. It
uses a combination of proof of work, proof of stake and proof of burn

8
"A (Short) Guide to Blockchain Consensus Protocols - CoinDesk." 4 Mar. 2017,
http://www.coindesk.com/short-guide-blockchain-consensus-protocols/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

Proof-of-Capacity
Here you 'pay' with hard drive space. The more hard drive space you have, the better your
chance of mining the next block and earning the block reward.
Prior to mining in a proof-of-capacity system, the algorithm generates large data sets known
as 'plots', which you store on your hard drive. The more plots you have, the better your
chance of finding the next block in the chain.
By investing in terabytes of hard drive space, you buy yourself a better chance to create
duplicate blocks and fork the system. But with proof of capacity, we still have the problem of
nothing at stake to deter bad actors.
Variations of proof of capacity include proof of storage and ​proof of space​. Burstcoin is the
only cryptocurrency to use a form of proof of capacity.

Proof-of-Elapsed time
Chipmaker  Intel  has  come  up  with  its  own alternative consensus protocol called ​proof of 
elapsed  time​.  This  system  works  similarly  to  proof  of  work,  but  consumes  far  less 
electricity.
Further, instead of having participants solve a cryptographic puzzle, the algorithm uses a
trusted execution environment (TEE) – such as SGX – to ensure blocks get produced in a
random lottery fashion, but without the required work.
Intel’s approach is based on a guaranteed wait time provided through the TEE. According to
Intel, the proof-of-elapsed-time algorithm scales to thousands of nodes and will run efficiently
on any Intel processor that supports SGX.
The one problem with this protocol is it requires you to put your trust in Intel – and isn’t
putting trust in third parties what we were trying to get away from with public blockchains?

Distributed Concurrence (N2N - Corda)


A set of rules that all participants have agreed to, an environment in which everyone has
access to the same data. Each hash is then recorded so that it can’t be disputed.

In the following table we listed a summary of each of the Consensus techniques analyzed. 9

# Consensus Short Concept Implementation


Algorithm Name name

1 Proof-of-Work PoW Maintain their blockchains with a Bitcoin,


decentralized peer-to-peer Ethereum,
cryptographic protocol. They Colored Coins,
don’t have any central authority, Proprietary
but they do assume that “honest” Metacoins,
nodes control at least a majority Factom,
of the system’s computer power. Coinprism,

9
"A (Short) Guide to Blockchain Consensus Protocols - CoinDesk." 4 Mar. 2017,
http://www.coindesk.com/short-guide-blockchain-consensus-protocols/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

They’re public or permission-less Litecoin, DAG


systems: The nodes don’t need (Directed Acyclic
to know who the other nodes are. Graphs).
Mining successfully depends on
actually doing the computational
work.

2 Proof-of-Stake PoS Mining requires the participant to Ethereum


“put up a stake,” a participant (Casper - Early
can mine new coins (or enter 2018), Peercoin,
new transactions) in accordance Blackcoin and
with how many coins they NXT
already have.

3 Delegated proof DPoS Tries to combine proof-of-stake Graphene,


of stake and proof-of-work characteristics. Steem,
Uses a decentralized voting BitShares,
process through what are known
as witnesses as a way to
mitigate against potential
network centralization.
It has flexibility of the blockchain
parameters (configurable by the
committee)

4 Leader-based LBC The nodes temporarily elect one BigChainDB,


consensus node to be a leader. The leader Juno (JPMC),
is then responsible for validating Tangaroa
transactions. Juno allows every
message to be encrypted in
whatever method the user
prefers.

5 Round Robin RR Private Blockchain. A set of MultiChain,


miners rotates in order to mine Tendermint,
the blocks in a certain period of
time.

6 Federated FC / FBA Robustness through individual Ripple, Stellar


Consensus / trust decisions made by each
Federated node that together determine
Byzantine system-level quorums
Agreement

7 Practical PBFT Internal computational process Fabric


Byzantine Fault with the node state and the (Hyperledger -
Tolerance message. Each nodes results Derived PBFT),
are compared and a consensus Evernym
is made based on all the nodes (Redundant
results. BFT), Chain
(Simplified BFT)

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

8 Proof-of-Actvity PoA Was created as an alternative Decred


incentive structure for bitcoin.
Proof of activity is a hybrid
approach that combines both
proof of work and proof of stake.

9 Proof-of-Burn PoB By committing your coins to the Slimcoin


system, you earn a lifetime
privilege to mine on the system
based on a random selection
process.

10 Proof-of-Capacity PoC The more hard drive space you Burstcoin


have, the better your chance of
mining the next block and
earning the block reward.

11 Proof-of-Elapsed PoET Is a lottery protocol that builds on Sawtooth Lake


Time (by Intel) trusted execution environments Project
provided by Intel’s SGX to (Hyperledger)
address the needs of large
populations of participants.

12 Distributed N2N A set of rules that all participants Corda (R3)


Concurrence - have agreed to, an environment
Node to Node in which everyone has access to
the same data. Each hash is
then recorded so that it can’t be
disputed.
Table of 12 the main Consensus techniques

Public, private and consortium blockchains


A private or a consortium blockchain platform, as opposed to the public platform that Bitcoin
uses, will allow them to retain control and privacy while still cutting down their costs and
transaction speeds.
In fact, this private system will have lower costs and faster speeds than a public blockchain
platform can offer.
Blockchain purists aren’t impressed. A private platform effectively kills their favorite part of
this nascent technology: decentralization.
They see the advent of private blockchain systems as little more than a sneaky attempt by
big banks to retain their control of financial markets.
In a way, they’re correct.
Let’s take a deeper look at what these might be.

Public blockchain
A Blockchain was designed to securely cut out the middleman in any exchange of asset
scenario. It does this by setting up a block of peer-to-peer transactions. Each transaction is

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

verified and synced with every node affiliated with the blockchain before
it is written to the system.
Until this has occurred, the next transaction cannot move forward. Anyone with a computer
and internet connection can set up as a node that is then synced with the entire blockchain
history.
While this redundancy makes public blockchain extremely secure, it also makes it slow and
wasteful.
The benefit is every transaction is public and users can maintain anonymity.
A public blockchain is most appropriate when a network needs to be decentralized.
It is also great if full transparency of the ledger or individual anonymity are desired benefits.
Costs are higher and speeds are slower than on a private chain, but still faster and less
expensive than the accounting systems and methods used today.
Security is key to their users, a decentralized network is at the heart of the project and their
competitors in the finance industry are still significantly more expensive and slower than a
public blockchain network despite its slowness when compared to a private blockchain.

Private blockchain
Private blockchain lets the middleman back in, to a certain extent.
The company writes and verifies each transaction. This allows for much greater efficiency
and transactions on a private blockchain will be completed significantly faster. Though it
does not offer the same decentralized security as its public counterpart, trusting a business
to run a blockchain is no more dangerous than trusting it to run a company without
blockchain.
The company can also choose who has read access to their blockchain’s transactions,
allowing for greater privacy than a public blockchain.
A private blockchain is appropriate to more traditional business and governance models, but
that isn’t a bad thing. Just because it is unlikely to revolutionize our world, doesn’t mean it
can’t play a role in making the world better.
Competition is key to developing the most useful products.

Consortium blockchain
Consortium blockchain is partly private. There has been some confusion about how this
differs from a fully private system.
Instead of allowing any person with an internet connection to participate in the verification of
transactions process or allowing only one company to have full control, a few selected nodes
are predetermined.
A consortium platform provides many of the same benefits affiliated with private
blockchain — efficiency and transaction privacy, for example — without consolidating
power with only one company.
You can think of it as trusting a council of elders. The council members are generally known
entities and they can decide who has read access to the blockchain ledger.
Consortium blockchain platforms have many of the same advantages of a private
blockchain, but operate under the leadership of a group instead of a single entity.
This platform would be great for organizational collaboration.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

The possibilities are endless.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

MODULE 2: Smart Contracts


What’s a Smart Contract
While there is no universally accepted definition, most people involved with the blockchain
would expect at least the following three elements in order to consider something to be a
smart contract:
1. The transaction must involve more than the mere transfer of a virtual currency from
one person to another (i.e., a payment transfer),
2. The transaction involves two or more parties (as every contract must), and
3. The implementation of the contract requires no direct human involvement after the
smart contract has been made a part of the blockchain. It’s this last element that
makes these contracts “smart,” and therefore, merits a more detailed discussion.

Traditional Contracts
But before taking a deep dive into the self-implementation of smart contracts, let’s first
explore the current state of traditional contracts in order to understand why smart contracts
are a significant improvement.

As every first year law student knows, a contract is an agreement between two or more
parties where one party agrees to do (or refrain from doing) something in exchange for
something else (that something else could be the payment of money, the performance of
services or the delivery of goods) — there will be an in-depth discussion of offer, acceptance
and consideration (since most of layers have suffered through first year Contracts in law
school). Sophisticated parties go through great lengths to draft (or pay attorneys to draft)
comprehensive contracts that meticulously describe what each party must do (or refrain from
doing), how each action must be done, the current state of an asset, contingencies that will
occur if certain conditions are not met, and so on — you get the point.

Innovation

So what makes smart contracts so innovative?

Well, the simple answer is that smart contracts are not very different from traditional
contracts, except that they are coded and digitally recorded on the blockchain. And this last
quality gives smart contracts a host of significant advantages over traditional contracts —
smart contracts are ​trustless, autonomous, and self-sufficient.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Traditional and Coded (Smart)

As mentioned above, parties strive to draft traditional contracts in a manner that reduces risk
for themselves, but ultimately, an element of risk is almost inevitable in the traditional
contract setting. Parties must trust that the other does in fact have what they claim they
have, that they can indeed do what they say they can do, or, if all else fails, that the local
judicial system will interpret the contract in their favor.

Smart contracts, however, reduce these risks as a result of the following characteristics:

(i) smart contracts are coded and computer code ultimately boils down to 1’s and 0’s —
there are no gray areas or ambiguities,

(ii) the current state of things (whether this thing is a home or your bitcoin wallet) digitally tied
to the blockchain is verifiable (hence, no need to meticulously explain what is you think you
are getting), and

(iii) smart contracts are self-executing, which means that the contract cannot be reneged, no
one can decide not to perform a certain task (at least one that is linked to the blockchain),
and there are less human hands (and hence human corruption) that influence performance
throughout the contract’s term.

Smart contracts aren’t reinventing contractual relationships, but ​they are making their
formation and performance more efficient, cost-effective, and transparent.

Advantages of Smart Contracts over traditional solutions


Smart contracts are computer protocols that facilitate, verify, or enforce the negotiation or
performance of a contract, or that make a contractual clause unnecessary. Smart contracts
often emulate the logic of contractual clauses. Proponents of smart contracts claim that
many kinds of contractual clauses may thus be made partially or fully self-executing,
self-enforcing, or both. Smart contracts aim to provide security superior to traditional contract
law and to ​reduce other transaction costs associated with contracting.

Use cases
The followings are examples of common use cases for Smart Contracts:

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

● Digital Identity: ​smart contracts can allow individuals to own and


control their digital identity containing data, reputation and digital assets. It permits
individuals to decide what data to disclose to counterparties, providing enterprises
the opportunity to seamlessly know their customers. Counterparties will not have to
hold sensitive data to verify transactions. This reduces liability while facilitating
frictionless know-your-customer requirements. It also increases compliance,
resiliency and interoperability.
● Trade finance: smart contracts can streamline international transfers of goods via
fast Letter of Credit and trade payment initiation, while enabling a greater liquidity of
financial assets. They can also improve financing efficiencies for buyers, suppliers
and institutions.
● Supply chain​: smart contracts can provide real-time visibility for every step in a
supply chain. Internet of Things devices can record each step as a product moves
from a factory floor to the store shelves. They facilitate granular-level inventory
tracking, benefitting supply chain financing, insurance and risk. Such enhanced
tracing and verification reduce the risk of theft and fraud. The identities of supply
chain players have to be attested over time, including companies, institutions,
individuals, sensors, facilities and products.
● Clinical trials: smart contracts can improve clinical trials through increased
cross-institutional visibility. Privacy-preserving computation improves data sharing
between institutions while automating patient data. They can streamline processes
for trials, improve access to cross-institution data, and can increase confidence in
patient privacy. Authentication, authorization and identity remain open issues for
smart contracts executed on blockchain-enabled networks.
● Land title recording: smart contracts that facilitate property transfers can deter
fraud, improve transaction transparency and efficiency, and strengthen confidence in
identity. They also reduce auditing costs. Common protocols need to be developed
for electronic record filing.

DApps
A new model for building successful and massively scalable applications is emerging. Bitcoin
led the way with its open-source, peer-to-peer nature, cryptographically-stored records
(blockchain), and limited number of tokens that power the use of its features.
DApps connect users and providers directly.
One example is to use this design for a decentralized Twitter that’s resistant to censorship.
Once you publish a message to the blockchain, it can’t be erased, not even by the company
that created the microblogging system.

Definition of a DApp

For an application to be considered a DApp (pronounced Dee-App, similar to Email) it should


meet the following criteria:
1. The application must be completely ​open-source​, it must operate autonomously, and
with no entity controlling the majority of its tokens. The application may adapt its

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

protocol in response to proposed improvements and market


feedback but all changes must be decided by consensus of its users.
2. The application's data and records of operation must be cryptographically stored in a
public, decentralized ​blockchain​ in order to avoid any central points of failure.
3. The application must use a cryptographic token (bitcoin or a token native to its
system) which is necessary for access to the application and any contribution of
value from (miners / farmers) should be rewarded in the application’s tokens.
4. The application must generate tokens according to a standard cryptographic
algorithm acting as a proof of the value nodes are contributing to the application
(Bitcoin uses the Proof of Work Algorithm).

Nomenclature and its importance

Decentralized applications were initially described as Decentralized Autonomous


Corporations, DAC, in an article written by Daniel Larimer, of Invictus Innovations. This
papers avoids the term corporation for two reasons.

First, because it carries with it unnecessary preconceptions. For instance, a corporation is


established in a jurisdiction, it has shares, a CEO, employees, etc. DApps, like Bitcoin, have
none of these characteristics. In addition, the narrative is very important for the way DApps
are perceived by various nations and jurisdictions. The same way that governments struggle
to learn and regulate Bitcoin because the concept of currency is associated with it,
governments might be compelled to regulate an open-source computer program that is a
decentralized application.

Second, because traditional corporations may engage in several techniques to raise capital
(like selling shares of its stock and pay dividends or borrowing against its stock and pay
interest) that a DApp does not need. The concept of a DApp is so powerful and elegant,
because it does not include these traditional corporate techniques. The ownership of the
DApp’s tokens is all that is required for the holder to use the system. It’s that simple. The
value of the tokens is determined by how much people value the application. All the
incentives, all the monetization, all the ways to raise support are built into this beautifully
simple structure. DApps are not required to recreate the functions that used to be necessary
in centralized corporations in order to balance the power of shareholders and offer returns
for investors and employees.

Classification of DApps

There are several characteristics according to which decentralized applications can be


classified. For the purposes of this paper10, DApps were classified based on whether they
have their own blockchain or they use the blockchain of another DApp. Based on this
criterion, there are three types of DApps.

10
"DecentralizedApplications/README.md at master ... - GitHub."
https://github.com/DavidJohnstonCEO/DecentralizedApplications/blob/master/README.md​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

Type I decentralized applications have their own block chain. Bitcoin is


the most famous example of a type I decentralized application but Litecoin and other
“alt-coins” are of the same type.

Type II decentralized applications use the blockchain of a type I decentralized application.


Type II decentralized applications are protocols and have tokens that are necessary for their
function. The Omni Protocol is an example of a type II decentralized application.

Type III decentralized applications use the protocol of a type II decentralized application.
Type III decentralized applications are protocols and have tokens that are necessary for their
function.

For example the SAFE Network that uses the Omni Protocol to issue ‘safecoins’ that can be
used to acquire distributed file storage is an example of a type III decentralized application.
A useful analogy for a type I DApp is a computer operating system (like Windows, Mac OS
X, Linux, Android, iOS) for a type II DApp a general purpose software program (like a word
processor, a spreadsheet software, a file synchronization system such as Dropbox) and for
type III DApp, a specialized software solution (like a mail-merge tool that uses a word
processor, an expense report macro that uses a spreadsheet, or a blogging platform that
uses Dropbox.) Using this analogy, it may be expected that due to network effects and the
ecosystem surrounding each decentralized application, there will be a few type I DApps,
more type II DApps and even more type III DApps.

You can see DApp Type II and III examples using Ethereum in ​the State of the DApps​.
For more details about how DApps work, Mechanism, Tokens, etc. ​read the full
Decentralized Application paper in Github

DApps can also be classified into 3 types according to their purpose: apps that manage
money, apps where money is involved (but also requires another piece), and apps in the
“other” category, which includes voting and governance systems. For more information, you
can read this.

Current Status
Fred Ehrsam published an article11 with a simple insight of how the blockchain ecosystem is
evolving in order to create a 100% DApp. This means that the objective is that all the
technology stack should be over DApp.
Next you can find a table of his research and the current status in 2017:

11
"The dApp Developer Stack: The Blockchain Industry Barometer." 30 Apr. 2017,
https://medium.com/@FEhrsam/the-dapp-developer-stack-the-blockchain-industry-barometer-8d55ec
1c7d4​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

Using a 0–2 scale (0=not started, 1=in progress, 2=ready), the stack was 20% complete in
2014 and is 70% complete in 2017

Example of DApp
Example of a “protected” wallet DApp:
1) A smartphone wallet application is the front-end that communicates with a wallet
smart-contract stored on the blockchain. The wallet/smart-contract stores BTC and
USD.
2) The wallet/smart-contract restricts payments up to 1000 USD/day, but allows more if
payment is authorized by a close relative.
3) The contract interacts with a 3rd smart-contract that sends/receives SMS to/from
close relative.
4) Also the contract interacts with a 3rd party Oracle contract informs the current
BTC/USD rate.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

What is Ethereum?
Ethereum is an open-source, public, blockchain-based ​distributed computing platform
featuring smart contract (scripting) functionality, which facilitates online contractual
agreements. It provides a decentralized ​Turing-complete ​virtual machine​, the Ethereum
Virtual Machine (EVM), which can execute scripts using an international network of public
nodes. Ethereum also provides a cryptocurrency token called "ether", which can be
transferred between accounts and used to compensate participant nodes for computations
performed. Gas, an internal transaction pricing mechanism, is used to prevent spam and
allocate resources on the network.
Ethereum was proposed in late 2013 by Vitalik Buterin, a cryptocurrency researcher and
programmer. Development was funded by an online crowdsale during July–August 2014.
The system went live on 30 July 2015, with 11.9 million coins "premined" for the crowdsale.

The DAO
The DAO was a digital ​decentralized autonomous organization and a form of
investor-directed ​venture capital fund​.
The DAO had an objective to provide a new decentralized business model for organizing
both ​commercial and ​non-profit enterprises. ​It was instantiated on the ​Ethereum
blockchain​, and had no conventional management structure or board of directors The
code​ of the DAO is ​open-source​.
The DAO was ​stateless​, and not tied to any particular ​nation state​. As a result, many
questions of how ​government regulators would deal with a stateless fund were yet to be
dealt with.
The DAO was ​crowdfunded via a token sale in May 2016. It set the record for the largest
crowdfunding campaign in history.
.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

MODULE 3: RSK
What’s RSK?
RSK is the First Open Source Smart contract
platform powered by the bitcoin network that also
rewards the Bitcoin miners via merge-mining,
allowing them to actively participate in the Smart
Contract revolution. RSK goal is to add value and
functionality to the Bitcoin ecosystem by enabling
smart-contracts, near instant payments and
higher-scalability.

RSK Lab is a startup founded in 2015 with the objective to develop the RSK open source
platform and related products. RSK Lab Development offices are located in Buenos Aires,
Argentina.

RSK Pillars
The RSK platform is a decentralized Bitcoin sidechain. RSK technical vision of the Internet of
Value comprises multiple protocol layers, each layer solving a different need for the transfer
of value, together forming a coherent yet flexible protocol stack.

The 4 Pillars of RSK are:


1. Full compatibility with leading smart contract platforms
2. Bitcoin used as fuel to run the smart contracts (through the Bitcoin-RSK Bridge)
3. Security ensured by Bitcoin Network Merge-mining
4. Global Federation

Goals
The RSK´s goals are:
1. Add smart contracts to Bitcoin
2. Create a democratic decentralized network
3. Increase Bitcoin use-cases and therefore add to Bitcoin network effect
4. Enable the financial institutions to develop blockchain applications compliant with
regulation
5. Incentivize Bitcoin & Ethereum communities to participate
6. High incentives for Bitcoin miners to join
7. Create an open governance model to improve and standardize the platform
8. Use the Bitcoin token (no pre-mining, no minting new tokens)
9. Low transaction fees, high transaction volume, foster financial inclusion
10. Scale far more than Bitcoin

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Can Bitcoin run smart-contract script?


Bitcoin was built to solve a very specific problem, that is creating a way to record
transactions to facilitate peer-to-peer transfer of value. For this reason, Bitcoin has its own
problems so run smart-contracts, as follow:
• Bitcoin is Non-Turing complete (no “goto” nor recursion)
• Very low available resources to run smart contracts (small stack, limited steps)
• No persistent memory
• Very limited context inspection
• Most useful opcodes are disabled

How does it work?


RSK Blockchain is a blockchain that let´s anyone to run smart-contract using Bitcoin as a
liability. The only way to do this is by connecting the Bitcoin Blockchain and the RSK
Blockchain by using a technique called “Hybrid Drivechain Bitcoin-RSK Bridge”. (​more
details here​)
In currency terms, the RSK currency is called SmartBTC (SBTC). In order to avoid SBTC
price changes, there is a fixed 1 to 1 correlation between a BTC and a SBTC.
The miners are able to mine both currencies in a process called merge-mining (​more details
here​) and the incentive for the miners is the 80% of the fees. The other 17.5% goes to RSK
Labs, 1% to the federation, 1% to RSK Full Nodes and 0.5% to Bitcoin Full Nodes.

RSK Basic Diagram

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

2-way peg
A 2-​way peg (2WP) protocol is a protocol that allows transfers of a cryptocurrency from a
main blockchain to a second blockchain and vice ​versa requiring low third​party trust.
In order to understand the approach chosen by RSK let's review some basic concepts.

Sidechain
The sidechain method is a symmetric 2WP based on each chain understanding how the
other chain creates consensus to lock or unlock coins for cross​transfer, and exchange short
proofs of last transaction control for locking/unlocking. To easily explain this concept first
suppose that the secondary chain has “settlement finality” and the consensus is reached
when a fixed number of parties (the consensus group) sign the block containing the
cross​chain transfer transaction (e.g. by using a Byzantine fault tolerant consensus). In this
example clearly the mainchain can be provided the signed block as the payload of a main
chain transaction, together with an SPV proof, and that’s enough for the main chain to
unlock the equivalent amount bitcoins and send them to where the payload specifies. The
difference from this approach and a multi​sig of notaries receiving the funds for custody is
that the consensus group need not to be aware of the 2WP: by signing each block the
secondary blockchain consensus group members are providing enough proof for the main
chain to unlock the funds. The secondary chain consensus group has full power to unlock
the funds in the main chain and send them to whatever address they want (by creating an
alternate signed branch, for example). If the secondary consensus method is proof-​of-​work,
then an SPV proof containing confirmation headers must must be used, and the primary
blockchain requires more complex protocol to prevent being presented a fake SPV proof by
choosing the proof with higher accumulated work from all candidates presented. The setup
of a sidechain is depicted here:

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Sidechain diagram

Drivechain
A drivechain is a 2WP with no proof of control and provided with internal custody. In a
nutshell, a drivechain gives custody of the locked btc to the Bitcoins miners, and allows
Bitcoin miners to vote when to unlock bitcoins and where to send them. The miners vote
using the bitcoin blockchain, and votes are cast in some part of the block (e.g. the coinbase).
If the proportion of miners who participate in voting is under 50%, then the remaining ones
can easily cheat by voting whatever transfer that let them steal the bitcoins. If the miners can
vote quickly to unlock the locked coins and spend them, they can cash out (in other
cryptocurrency or in fiat) before the community reacts and finds out the majority of Bitcoin
miners are dishonest. Therefore, as in a sidechain, post​lock period must also exist as MAD
disincentive. The following diagram depicts a drivechain:

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Drivechain Diagram

RSK 2Way-Peg Method


In case of RSK, where openness and acceptance by the Bitcoin community is crucial,
following choices are preferred:
● A ​sidechain​ in the RSK side
● A hybrid drivechain + federation in the Bitcoin side combining miners and federation
votes.

Refer to the following diagram for more details.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Diagram: A hybrid drivechain and a federation (allowing federation votes)

The sidechain proposal in the Bitcoin side has higher probability to be contended by the
community or core developers than of a drivechain, as the complexity of the sidechain
implementation is significantly higher than of the drivechain. In the case of Rootstock, we
must opt for the simplest solution both conceptually and technically in order to maximizes the
chances of acceptance. RSK Labs also aim to provide a smooth upgrade path to a fully
decentralized solution, so Rootstock plans to start with a federation composed by renowned
Bitcoin parties having secoin bonds, and plans to add miner’s votes (a drivechain) when

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

available. Using federation votes in the drivechain the system can


automatically decrease the number of votes required by the federation and increase the
number of votes required by the miners as the amount of merge ​miner engagement
increases in relation to the amount of bitcoin mining, until no federation votes are required.
Once the merge​ mining gets almost full miner acceptance (such as 95%), the federation role
in voting can be disabled, and only the drivechain remains. The following diagram shows
which votes would be required in an hybrid model to unlock the btc at different stages of
merge ​mining engagement:

In the following chart, you can find another way to have a general picture on how the
systems works. We can see the Bridge between Bitcoin and RSK Blockchains. On top of
RSK blockchain, industry specific solutions or smart-contracts could be created for each use
case.

General picture on how RSK works

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Merge Mining12
Merged mining allows a miner to mine for more than one blockchain at the same time. The
benefit is that every hash the miner does contributes to the total hash rate of both
currencies, and as a result they are all more secure.
Starting with a high-level explanation: The miner (or mining controller in the case of pooled
mining) actually builds a block for both hash chains (eg: Bitcoin and RSK) in such a way that
the same hash calculation secures both blocks. Work units based on this block are then
assigned to miners.

There are the three possible scenarios:13


1. The merged miner finds a solution where the difficulty is too low to provide a valid hash
and proof of work for either chain. -> In this case, nothing happens and the merged miner
inserts a new nonce value and rehashes.
2. The merged miner finds a solution where the proof of work has been achieved for the
secondary chain (eg: RSK), but not for the parent chain (eg: Bitcoin). -> The miner has found
a solution for the secondary chain and propagates its solution throughout that network.
3. The merged miner finds a solution for that is greater than the difficulty requirements for
both the parent and the secondary blockchains. -> Solutions have been found for both of the
chains and so a all the required information for confirmations is propagated to dedicated
miners of both networks.

12
"hashpower - How does merged mining work? - Bitcoin Stack Exchange." 31 Aug. 2011,
https://bitcoin.stackexchange.com/questions/273/how-does-merged-mining-work​.
13
"What is merged mining – Bitcoin & Namecoin – Litecoin & Dogecoin ...." 25 Oct. 2016,
https://www.cryptocompare.com/mining/guides/what-is-merged-mining-bitcoin-namecoin-litecoin-doge
coin/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

MODULE 4: Programming smart contracts


SOLIDITY
Solidity is an object-oriented programming language (similar to JavaScript) for writing smart
contracts. It is used to implement smart contracts on various blockchain platforms. It was
developed by Gavin Wood, Christian Reitweissner, Alex Beregszaszi, Yoichi Hirai and
several former Ethereum core contributors to enable writing smart contracts on blockchain
platforms such as Ethereum.
Solidity is currently used as the primary language on Ethereum as well as on other private
blockchains running on platforms, such as RSK, ​Monax and its ​Hyperledger Burrow
blockchain, (which uses Tendermint for consensus)
Solidity is compiled to ​bytecode that is executable on the EVM. With Solidity, developers are
able to write applications that implement self-enforcing business logic embodied in smart
contracts, leaving a non-repudiable and authoritative record of transactions. ​Writing smart
contracts in smart contract specific languages such as Solidity is referred to as easy
(ostensibly for those who already have programming skills).

It is designed around the ​ECMAScript syntax to make it familiar for existing web developers;
unlike ECMAScript it has static typing and variadic return types. Complex member variables
for contracts including arbitrarily hierarchical mappings and structs were supported.
Contracts support ​inheritance​, including ​multiple inheritance with ​C3 linearization​. An
application binary interface (ABI) facilitating multiple ​type-safe functions within a single
contract was also introduced. A documentation system for specifying a user-centric
description of the ramifications of a method-call was also included in the proposal, known as
"Natural Language Specification".

Introduction
You can start using ​Solidity in your browser​, with no need to download or compile anything.
This application only supports compilation - if you want to run the code or inject it into the
blockchain, you have to use a client like ​AlethZero​.

Overview
The RSK Virtual Machine (compatible with EVM -Ethereum) is the runtime environment for
smart contracts in RSK. It is not only sandboxed but actually completely isolated, which
means that code running inside the RSK VM has no access to network, filesystem or other
processes. Smart contracts even have limited access to other smart contracts.

Accounts
There are two kinds of accounts in RSK which share the same address space: External
accounts that are controlled by public-private key pairs (i.e. humans) and contract accounts
which are controlled by the code stored together with the account.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

The address of an external account is determined from the public key


while the address of a contract is determined at the time the contract is created (it is derived
from the creator address and the number of transactions sent from that address, the
so-called “nonce”).
Regardless of whether or not the account stores code, the two types are treated equally by
the RSK VM.
Every account has a persistent key-value store mapping 256-bit words to 256-bit words
called storage.
Furthermore, every account has a balance in SBTC (Smart BTC) which can be modified by
sending transactions that include SBTC.

Transactions
A transaction is a message that is sent from one account to another account (which might be
the same or the special zero-account, see below). It can include binary data (its payload)
and SBTC.
If the target account contains code, that code is executed and the payload is provided as
input data.
If the target account is the zero-account (the account with the address 0), the transaction
creates a ​new contract. As already mentioned, the address of that contract is not the zero
address but an address derived from the sender and its number of transactions sent (the
“nonce”). The payload of such a contract creation transaction is taken to be RSK VM
bytecode and executed. The output of this execution is permanently stored as the code of
the contract. This means that in order to create a contract, you do not send the actual code
of the contract, but in fact ​code that returns that code.

Installing Solidity & Building from source


All you have to know about ​installing Solidity​ and ​building from source​.
F
web3 contains the eth object - web3.eth (that was first used for Ethereum blockchain
interactions and can be used for RSK interaction too) and the shh object - web3.shh (for
Whisper interaction). Over time we'll introduce other objects for each of the other web3
protocols. Working ​examples can be found here​.
If you want to look at some more sophisticated examples using web3.js check out these
useful app patterns​.
You can ​follow the Getting started with Web3.js guide​.

Structure of a Contract14
Contracts in Solidity are similar to classes in object-oriented languages. Each contract can
contain declarations of ​State Variables​, ​Functions​, ​Function Modifiers​, ​Events​, ​Structs Types
and ​Enum Types​. Furthermore, contracts can inherit from other contracts.

14
"Structure of a Contract — Solidity 0.4.12 documentation - Read the Docs."
http://solidity.readthedocs.io/en/develop/structure-of-a-contract.html​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

State Variables
State variables are values which are permanently stored in contract storage.
pragma​ solidity ​^​0.4​.​0​;

contract​ SimpleStorage {
​uint​ storedData; ​// State variable
​// ...
}

See the ​Types section for valid state variable types and ​Visibility and Getters for possible
choices for visibility.

Functions
Functions are the executable units of code within a contract.
pragma​ solidity ​^​0.4​.​0​;

contract​ SimpleAuction {
​function​ bid() ​payable​ { ​// Function
​// ...
}
}

Function Calls can happen internally or externally and have different levels of visibility
(​Visibility and Getters​) towards other contracts.

Function Modifiers
Function modifiers can be used to amend the semantics of functions in a declarative way
(see ​Function Modifiers​ in contracts section).

pragma​ solidity ​^​0.4​.​11​;

contract​ Purchase {
​address​ ​public​ seller;

​modifier​ onlySeller() { ​// Modifier


require(​msg​.sender ​==​ seller);
_;
}

​function​ abort() onlySeller { ​// Modifier usage


​// ...
}
}

Events
Events are convenience interfaces with the EVM logging facilities.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

pragma solidity ^0.4.0;

contract SimpleAuction {
event HighestBidIncreased(address bidder, uint amount); // Event

function bid() payable {


// ...
HighestBidIncreased(msg.sender, msg.value); // Triggering event
}
}

See ​Events in contracts section for information on how events are declared and can be used
from within a dapp.
You can also take a look to the post ​Technical View to Events and Logs in Ethereum

Structs Types
Structs are custom defined types that can group several variables (see ​Structs in types
section).

pragma solidity ^0.4.0;

contract Ballot {
struct Voter { // Struct
uint weight;
bool voted;
address delegate;
uint vote;
}
}

Enum Types
Enums can be used to create custom types with a finite set of values (see ​Enums in types
section).

pragma​ solidity ​^​0.4​.​0​;

contract​ Purchase {
​enum​ State { Created, Locked, Inactive } ​// Enum
}

Smart contract sample


Now, let’s see a simple contract15

pragma ​solidity ^0.4.4;


contract ​StoreSomeData {
// the current state of the contract is represented

15
"Creating Smart Contracts in RSK · rsksmart/rskj Wiki · GitHub."
https://github.com/rsksmart/rskj/wiki/Creating-Smart-Contracts-in-RSK​. Accessed 19 Jun. 2017.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

// for the value of all it's data members in a given time


uint ​storedData;

// allows to set a value


function set(uint i) {
storedData = i;
}
// returns the current value
function get() constant returns (uint) {
return storedData;
}
}

In this example there are some interesting details:


● The storeData field is of type uint and by default it's private, so you can't access to it
from the outside. In the other side if you don't add the private modifier all methods will
be accessible from the outside.
● The set function receives a uint parameter and assigns it's value to storeData, note
that this function doesn't return any value.
● The get function uses the returns keyword because it returns the storeData value,
also includes the type unit additionally you can assign a name to the return value,
something like that return (uint stored).
● Last but not least the get function uses the constant modifier, it indicates that the
function does not modify the state of the contract (since it is a getter) more details
here
An important concept, if we do something that changes the contract (and the blockchain)
status, that will costs us Gas and also will require a transaction.

Construct
pragma solidity ^0.4.4;
contract CreatorAddress {
// stores the address of the contract creator
address creator;
// contract constructos, it's executed once when the contracts is put into a
transaction
function CreatorAddress(){
creator = msg.sender;
}

function getAddress() constant returns (address creatorAdress) {


return creator;
}
}

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Deploy the Contract in the blockchain


var creatorAddress = null;
CreatorAddress.deployed().then(function(instance){ creatorAddress = instance;});
creatorAddress.getAddress();
0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826

We stored the address that puts the contract into a transaction and then we can retrieve it.

Killing a Contract
If we create a contract then we don't want it to be used anymore we can suicide the contract
and additionally get the unused funds back, considere the next example:
pragma solidity ^0.4.4;
contract CreatorAddress {
// stores the address of the contract creator
address creator;
// contract constructos, it's executed once when the contracts is put into a
transaction
function CreatorAddress(){
creator = msg.sender;
}
function getAddress() constant returns (address creatorAdress) {
return creator;
}
function kill(){
if (msg.sender == creator)
suicide(creator); // kills this contract and sends remaining funds back to
creator
}
}
Note that the kill function can be called in order to suicide this contract, we added a
validation to only allow the creator to kill the contract.

Tip: you can learn more about Solidity ​here​.


A more realistic example
One basic but interesting use of Smart Contracts is storing data forever without the
possibility of changing, imagine this scenario: I want to register something I created, let's say
an image, I can use some software application to get the SHA256 hash of the image, then
store this value into a Smart Contract so this hash will last forever without the change to be
changed by somebody else, in case someone try to copy mi work I can demonstrate that I
have the original image and the hash was registered some time ago before this other person
copied it, cool. But, how can we implement that?

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

pragma solidity ^0.4.4;


contract StoreHash {
// stores the address of the contract creator
address creator;
bytes32 storedHash;
// the contract's creator sends the hash and it's stored forever
function StoreHash(bytes32 hash){
creator = msg.sender;
storedHash = hash;
}
function getHash() constant returns (bytes32) {
return storedHash;
}
function kill(){
if (msg.sender == creator)
suicide(creator);
}
}

Quite simple, we stored a 32 bytes hash while constructing the contract (during the publish
process) and then it cannot be modified, just queried.
Every transaction must specify a quantity of "gas" that it is willing to consume (called
startgas), and the fee that it is willing to pay per unit gas (gasprice). At the start of execution,
startgas x gasprice SBTC are removed from the transaction sender's account.

Step by step example


pragma solidity ^0.4.6;
contract WinnerTakesAll {
uint minimumEntryFee;
uint public deadlineProjects;
uint public deadlineCampaign;
uint public winningFunds;
address public winningAddress;
struct Project {
address addr;
string name;
string url;
uint funds;
bool initialized;
}
mapping (address => Project) projects;
address[] public projectAddresses;
uint public numberOfProjects;
event ProjectSubmitted(address addr, string name, string url, bool initialized);

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

event ProjectSupported(address addr, uint amount);


event PayedOutTo(address addr, uint winningFunds);
function WinnerTakesAll(uint _minimumEntryFee, uint _durationProjects, uint
_durationCampaign) public {
if (_durationCampaign <= _durationProjects) {
throw;
}
minimumEntryFee = _minimumEntryFee;
deadlineProjects = now + _durationProjects* 1 seconds;
deadlineCampaign = now + _durationCampaign * 1 seconds;
winningAddress = msg.sender;
winningFunds = 0;
}
function submitProject(string name, string url) payable public returns (bool success) {
if (msg.value < minimumEntryFee) {
throw;
}
if (now > deadlineProjects) {
throw;
}
if (!projects[msg.sender].initialized) {
projects[msg.sender] = Project(msg.sender, name, url, 0, true);
projectAddresses.push(msg.sender);
numberOfProjects = projectAddresses.length;
ProjectSubmitted(msg.sender, name, url, projects[msg.sender].initialized);
return true;
}
return false;
}

function supportProject(address addr) payable public returns (bool success) {


if (msg.value <= 0) {
throw;
}
if (now > deadlineCampaign || now <= deadlineProjects) {
throw;
}

if (!projects[addr].initialized) {
throw;
}
projects[addr].funds += msg.value;
if (projects[addr].funds > winningFunds) {
winningAddress = addr;

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

winningFunds = projects[addr].funds;
}
ProjectSupported(addr, msg.value);
return true;
}
function getProjectInfo(address addr) public constant returns (string name, string url,
uint funds) {
var project = projects[addr];

if (!project.initialized) {
throw;
}
return (project.name, project.url, project.funds);
}
function finish() {
if (now >= deadlineCampaign) {
PayedOutTo(winningAddress, winningFunds);
selfdestruct(winningAddress);
}
}
}

Subcurrency Example
The following contract will implement the simplest form of a cryptocurrency. It is possible to
generate coins out of thin air, but only the person that created the contract will be able to do
that (it is trivial to implement a different issuance scheme). Furthermore, anyone can send
coins to each other without any need for registering with username and password - all you
need is an Ethereum keypair.
pragma solidity ^0.4.0;

contract Coin {
// The keyword "public" makes those variables
// readable from outside.
address public minter;
mapping (address => uint) public balances;

// Events allow light clients to react on


// changes efficiently.
event Sent(address from, address to, uint amount);

// This is the constructor whose code is


// run only when the contract is created.
function Coin() {
minter = msg.sender;
}

function mint(address receiver, uint amount) {

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

if (msg.sender != minter) return;


balances[receiver] += amount;
}

function send(address receiver, uint amount) {


if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Sent(msg.sender, receiver, amount);
}
}

This contract introduces some new concepts, let us go through them one by one.
The line address public minter; declares a state variable of type address that is publicly
accessible. The address type is a 160-bit value that does not allow any arithmetic
operations. It is suitable for storing addresses of contracts or keypairs belonging to external
persons. The keyword public automatically generates a function that allows you to access
the current value of the state variable. Without this keyword, other contracts have no way to
access the variable. The function will look something like this:

function minter() returns (address) { return minter; }

Of course, adding a function exactly like that will not work because we would have a function
and a state variable with the same name, but hopefully, you get the idea - the compiler
figures that out for you.
The next line, mapping (address => uint) public balances; also creates a public state
variable, but it is a more complex datatype. The type maps addresses to unsigned integers.
Mappings can be seen as ​hash tables which are virtually initialized such that every possible
key exists and is mapped to a value whose byte-representation is all zeros. This analogy
does not go too far, though, as it is neither possible to obtain a list of all keys of a mapping,
nor a list of all values. So either keep in mind (or better, keep a list or use a more advanced
data type) what you added to the mapping or use it in a context where this is not needed,
like this one. The getter function created by the public keyword is a bit more complex in this
case. It roughly looks like the following:

function balances(address _account) returns (uint) {


return balances[_account];
}

As you see, you can use this function to easily query the balance of a single account.
The line event Sent(address from, address to, uint amount); declares a so-called “event”
which is fired in the last line of the function send. User interfaces (as well as server
applications of course) can listen for those events being fired on the blockchain without
much cost. As soon as it is fired, the listener will also receive the arguments from, to and
amount, which makes it easy to track transactions. In order to listen for this event, you would
use

Coin.Sent().watch({}, '', function(error, result) {


if (!error) {

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

console.log("Coin transfer: " + result.args.amount +


" coins were sent from " + result.args.from +
" to " + result.args.to + ".");
console.log("Balances now:\n" +
"Sender: " + Coin.balances.call(result.args.from) +
"Receiver: " + Coin.balances.call(result.args.to));
}
})

Note how the automatically generated function balances is called from the user interface.
The special function Coin is the constructor which is run during creation of the contract and
cannot be called afterwards. It permanently stores the address of the person creating the
contract: msg (together with tx and block) is a magic global variable that contains some
properties which allow access to the blockchain. msg.sender is always the address where
the current (external) function call came from.

Finally, the functions that will actually end up with the contract and can be called by users
and contracts alike are mint and send. If mint is called by anyone except the account that
created the contract, nothing will happen. On the other hand, send can be used by anyone
(who already has some of these coins) to send coins to anyone else. Note that if you use
this contract to send coins to an address, you will not see anything when you look at that
address on a blockchain explorer, because the fact that you sent coins and the changed
balances are only stored in the data storage of this particular coin contract. By the use of
events it is relatively easy to create a “blockchain explorer” that tracks transactions and
balances of your new coin.

Hands-on-case
Voting16
The following contract is quite complex, but showcases a lot of Solidity’s features. It
implements a voting contract. Of course, the main problems of electronic voting is how to
assign voting rights to the correct persons and how to prevent manipulation. We will not
solve all problems here, but at least we will show how delegated voting can be done so that
vote counting is automatic and completely transparent at the same time.
The idea is to create one contract per ballot, providing a short name for each option. Then
the creator of the contract who serves as chairperson will give the right to vote to each
address individually.
The persons behind the addresses can then choose to either vote themselves or to delegate
their vote to a person they trust.
At the end of the voting time, winningProposal() will return the proposal with the largest
number of votes.

pragma solidity ^0.4.11;

16
"Solidity by Example — Solidity 0.4.12 documentation - Read the Docs."
http://solidity.readthedocs.io/en/develop/solidity-by-example.html​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

/// @title Voting with delegation.


contract Ballot {
// This declares a new complex type which will
// be used for variables later.
// It will represent a single voter.
struct Voter {
uint weight; // weight is accumulated by delegation
bool voted; // if true, that person already voted
address delegate; // person delegated to
uint vote; // index of the voted proposal
}

// This is a type for a single proposal.


struct Proposal {
bytes32 name; // short name (up to 32 bytes)
uint voteCount; // number of accumulated votes
}

address public chairperson;

// This declares a state variable that


// stores a `Voter` struct for each possible address.
mapping(address => Voter) public voters;

// A dynamically-sized array of `Proposal` structs.


Proposal[] public proposals;

/// Create a new ballot to choose one of `proposalNames`.


function Ballot(bytes32[] proposalNames) {
chairperson = msg.sender;
voters[chairperson].weight = 1;

// For each of the provided proposal names,


// create a new proposal object and add it
// to the end of the array.
for (uint i = 0; i < proposalNames.length; i++) {
// `Proposal({...})` creates a temporary
// Proposal object and `proposals.push(...)`
// appends it to the end of `proposals`.
proposals.push(Proposal({
name: proposalNames[i],
voteCount: 0
}));
}
}

// Give `voter` the right to vote on this ballot.


// May only be called by `chairperson`.
function giveRightToVote(address voter) {
// If the argument of `require` evaluates to `false`,
// it terminates and reverts all changes to
// the state and to Ether balances. It is often
// a good idea to use this if functions are
// called incorrectly. But watch out, this

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

// will currently also consume all provided gas


// (this is planned to change in the future).
require((msg.sender == chairperson) && !voters[voter].voted);
voters[voter].weight = 1;
}

/// Delegate your vote to the voter `to`.


function delegate(address to) {
// assigns reference
Voter sender = voters[msg.sender];
require(!sender.voted);

// Self-delegation is not allowed.


require(to != msg.sender);

// Forward the delegation as long as


// `to` also delegated.
// In general, such loops are very dangerous,
// because if they run too long, they might
// need more gas than is available in a block.
// In this case, the delegation will not be executed,
// but in other situations, such loops might
// cause a contract to get "stuck" completely.
while (voters[to].delegate != address(0)) {
to = voters[to].delegate;

// We found a loop in the delegation, not allowed.


require(to != msg.sender);
}

// Since `sender` is a reference, this


// modifies `voters[msg.sender].voted`
sender.voted = true;
sender.delegate = to;
Voter delegate = voters[to];
if (delegate.voted) {
// If the delegate already voted,
// directly add to the number of votes
proposals[delegate.vote].voteCount += sender.weight;
} else {
// If the delegate did not vote yet,
// add to her weight.
delegate.weight += sender.weight;
}
}

/// Give your vote (including votes delegated to you)


/// to proposal `proposals[proposal].name`.
function vote(uint proposal) {
Voter sender = voters[msg.sender];
require(!sender.voted);
sender.voted = true;
sender.vote = proposal;

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

// If `proposal` is out of the range of the array,


// this will throw automatically and revert all
// changes.
proposals[proposal].voteCount += sender.weight;
}

/// @dev Computes the winning proposal taking all


/// previous votes into account.
function winningProposal() constant
returns (uint winningProposal)
{
uint winningVoteCount = 0;
for (uint p = 0; p < proposals.length; p++) {
if (proposals[p].voteCount > winningVoteCount) {
winningVoteCount = proposals[p].voteCount;
winningProposal = p;
}
}
}

// Calls winningProposal() function to get the index


// of the winner contained in the proposals array and then
// returns the name of the winner
function winnerName() constant
returns (bytes32 winnerName)
{
winnerName = proposals[winningProposal()].name;
}
}

Possible Improvements
Currently, many transactions are needed to assign the rights to vote to all participants. Can
you think of a better way?

Creating tokens
We are going to create a digital token. Tokens in the ethereum/RSK ecosystem can
represent any fungible tradable good: coins, loyalty points, gold certificates, IOUs, in game
items, etc. Since all tokens implement some basic features in a standard way, this also
means that your token will be instantly compatible with the ethereum wallet and any other
client or contract that uses the same standards.

If you just want to copy paste the code, then use this:

pragma solidity ^0.4.8;


contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address
_token, bytes _extraData); }

contract MyToken {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

string public symbol;


uint8 public decimals;
uint256 public totalSupply;

/* This creates an array with all balances */


mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;

/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);

​/* This notifies clients about the amount burnt */


event Burn(address indexed from, uint256 value);

/* Initializes contract with initial supply tokens to the creator of the contract */
function MyToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply; // Give the creator all initial
tokens
totalSupply = initialSupply; // Update total supply
name = tokenName; // Set the name for display
purposes
symbol = tokenSymbol; // Set the symbol for display
purposes
decimals = decimalUnits; // Amount of decimals for
display purposes
}

/* Send coins */
function transfer(address _to, uint256 _value) {
if (_to == 0x0) throw; // Prevent transfer to 0x0
address. Use burn() instead
if (balanceOf[msg.sender] < _value) throw; // Check if the sender has
enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the
recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening
that this transfer took place
}

/* Allow another contract to spend some tokens in your behalf */


function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}

/* Approve and then communicate the approved contract in a single tx */

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

function approveAndCall(address _spender, uint256 _value, bytes


_extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}

/* A contract attempts to get the coins */


function transferFrom(address _from, address _to, uint256 _value) returns (bool
success) {
if (_to == 0x0) throw; // Prevent transfer to 0x0
address. Use burn() instead
if (balanceOf[_from] < _value) throw; // Check if the sender has
enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the
recipient
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}

function burn(uint256 _value) returns (bool success) {


if (balanceOf[msg.sender] < _value) throw; // Check if the sender has
enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}

function burnFrom(address _from, uint256 _value) returns (bool success) {


if (balanceOf[_from] < _value) throw; // Check if the sender has
enough
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(_from, _value);
return true;
}
}

For more details about the process, you can access to ​https://ethereum.org/token

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

MODULE 5: Working on RSK


Getting started with an RSK Node
To have the latest version of the documentation, we recommend you visit RSK’s wiki.

Compile and Run a RSK Node Locally17


Please follow the instruction in ​RSK's wiki​.

Connecting a RSK node to the Testnet18


There are 3 ways to install and run the RSK node:
● Using RskJ ubuntu package
● Using RskJ fatjar​ (or compiling it yourself).
● Using rsk docker container

Utilities for the Ginger Testnet


● You can find the stats of the network in ​https://stats.rsk.co
● A blockchain explorer can be found in ​https://explorer.rsk.co
● Smart BTC to use in the testnet can be easily asked in the faucet ​https://faucet.rsk.co

Truffle & TestRPC


Truffle19 is a world class development environment, testing framework and asset pipeline for
smart contracts, aiming to make life as an smart contract developer easier. With Truffle, you
get:
● Built-in smart contract compilation, linking, deployment and binary management.
● Automated contract testing for rapid development.
● Scriptable, extensible deployment & migrations framework.
● Network management for deploying to any number of public & private networks.
● Package management with EthPM & NPM, using the ​ERC190​ standard.
● Interactive console for direct contract communication.
● Configurable build pipeline with support for tight integration.
● External script runner that executes scripts within a Truffle environment.

It is compatible with RSK Smart and it can be downloaded from ​here​.

Read about configuring Truffle & TestRPC on Windows​. Also ​you can configure Visual
Studio Code for Blockchain Development​.

17
"Compile and run a RSK node locally · rsksmart/rskj Wiki · GitHub."
https://github.com/rsksmart/rskj/wiki/Compile-and-run-a-RSK-node-locally​.
18
"Install RskJ and join the RSK Ginger Testnet · rsksmart/rskj Wiki · GitHub."
https://github.com/rsksmart/rskj/wiki/Install-RskJ-and-join-the-RSK-Ginger-Testnet​.
19
"Documentation - Truffle Framework." ​http://truffleframework.com/docs/​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

TestRPC
TestRPC is an in-memory blockchain that provides a fast alternative to test your contracts,
since you don't have to wait for mining or get Gas to publish your contracts in real network.
Download it ​here​.
It is a normally a good idea to first develop your smart contracts against TestRPC, then
deploy and test them against a local RSK network and finally publish them to the Testnet.

Running TestRPC
Once TestRPC is installed in your local environment you can call it just typing:

testrpc

As you can see as soon we run testrpc the can see a list of available account that are
already created and ready to use, and also que port where TestRPC is running, the default
port is 8545
We can interact with TestRPC using the RPC protocol or Web3, a list of the implemented
methods can be found ​here
We will connect Truffle to TestRPC in the next steps.

Starting Truffle
We will use some basic truffle command during this introduction
truffle init
truffle compile
truffle test
truffle migrate

Init a new Truffle project


truffle init

This command will create a new Truffle project, basically a set of sample files organized in
folders ready to use, it also includes unit tests.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Verifying Truffle configuration


We've mentioned early that Truffle can interact with any software that implements the RPC
protocol, now we want to connect it to TestRPC, the only thing we have to configure is the
port (since we are running both in our local environment) there's a file in the project root
directory called truffle.js that look like this:

module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
}
}
};

check the port property this must match TestRPC port, in most cases it is 8545. Now we are
ready to test out project.

You can find the following information on RSK’s Wikis:

● Testing Truffle project


● Playing Around
● Running Tests
● Creating our first Smart Contract
● Truffle Console

You can also follow the steps below with this ​video​.

Connecting Truffle to RSK node20

Configure Truffle to connect to RSK Node


We've talked before about Truffle configuration and truffle.js, it's time to modify this
configuration file so Truffle to interact with our RSK node. Open the file and change the
default port to 4444 (this is the RSK node default port)

module.exports = {
networks: {
development: {
host: "localhost",
port: 4444,
network_id: "*" // Match any network id

20
"Testing RSK Smart Contracts using Truffle · rsksmart/rskj Wiki · GitHub."
https://github.com/rsksmart/rskj/wiki/Testing-RSK-Smart-Contracts-using-Truffle​.
RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart
Smart contracts powered by Bitcoin

}
}
};

Go to the command line and call Truffle console by typing ​truffle console​, we first will verify
some things before publishing contracts in the RSK node.
We are now connected to RSK node, let's try something easy, get the last block number
web3.eth.blockNumber
70

If everything is ok, you will get a number as response (70 in this case) this is the real last
block number in the RSK Smart testnet. We know the number but more important we know
that Truffle is configured correctly and is interacting with our local node through RPC.

Check our account


So far we didn't care too much about Gas or Bitcoins or anything like that, because in
TestRPC we alway had a new account with a big balance, now we are a new client in the
RSK Network depending if you we are working in a local network or over the Testnet we may
not have a positive balance, but let's find this out.

var myAccount = web3.eth.coinbase;


myAccount;
'0x28fdc38c327f4a3bbdf9501fd3a01ac7228c7af7'

The command web3.eth.coinbase gives us the address of our current account, now let's get
the balance

web3.eth.getBalance(myAccount);
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }

you can also get the balance in Ether

web3.eth.toWei(web3.eth.getBalance(myAccount), 'ether');
000000000.0

If you don't have funds (you're in the Testnet for instance) you can get Bitcoins in two ways
● Mine some blocks
● Get from a faucet
Of course we could mine some blocks but it may take some time, so let's go to the easy way.

Using a faucet to get some Bitcoins


There's a special URL intended to give you free Bitcoins to spend in the Testnet. Copy your
account address and go to:
http://faucet.rsk.co/

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Enter your address and redeem free Bitcoins

After a moment you should have some free credit to start publishing contracts:

web3.eth.toWei(web3.eth.getBalance(myAccount), 'ether');
web3.eth.toWei(web3.eth.getBalance(web3.eth.coinbase), 'ether');

Checking node for running correctly

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

We have another tool to verify if the miners are running property,


it's located at utilities/rpc-test , go to the directory and type

npm install

node sync3nodes.js

As you can see the three nodes have the same blocknumber, so there are synced correctly.

Checking whose mined blocks


And there's another tool to check mined blocks and miners.
node .\analyzebc.js localhost:4444 400-450
last two numbers (400-450) are the range of blocks to be scanned.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

Publishing a contract
Let’s repeat the same steps we did when we deployed in TestRPC but now in a real
network, at this point Truffle is connected to one of the nodes. We can also use ​Explorer app
to check the status of our network.
If everything looks fine so far we can try to publish a simple contract right now, go to truffle
console and type again, but we first need to check Truffle configuration.

Checking Truffle configuration


By default the miner1 default account does not have funds, we need to specify the account
to be used by Truffle when deploying contracts, open the truffle.js and set gas and from
values, for gas you just need to set the value to something meanful, like 2500000 in from
you need to specify your account address, the easier way to get this value is using the
Explorer app

module.exports = {
networks : {
development : {
gas : 2500000,
from : "0xcd2a3d9f938e13cd947ec05abc5fe734df8dd826",
host : "localhost",
port : 4444,
network_id : "*" // Match any network id
}

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

}
};

Now just migrate the current contract we've been working so far:
truffle migrate

Congratulations, you've deployed your first contract into a RSK network!

Interacting with the contract


The most important information about the contract is the address, you can see the address
in the youContractName.json within the build/contracts directory
And of course, we can interact with our contract and change it's state just like we did before:

var store = null;


StoreSomeData.deployed().then(function(instance){store = instance;});

with the instance reference just call it:

store.get();

and change the state:

store.set(123).then(console.log);

{ tx: '0x3809925e7927c4a7a135e2ba4009a66f39942e3182fc313c1bdcde5f3149005a',
receipt:
{ transactionHash: '0x3809925e7927c4a7a135e2ba4009a66f39942e3182fc313c1bdcde5f3149005a',
transactionIndex: 0,
blockHash: '0xa2f204cc944ae19c30f53e2813f65b66f2af8d27d6200584dac9c1b7b446feaf',
blockNumber: 1023,
cumulativeGasUsed: 41605,

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

gasUsed: 41605,
contractAddress: null,
logs: [],
from: '0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826',
to: '0x83c5541a6c8d2dbad642f385d8d06ca9b6c731ee',
root: '0x7433494a8ef15f786cdd93b83d4468582f83442c5d366b0e52b372bf19b98a16' },
logs: [] }

After some time (because a new block must be created and the confirmed) we can query
again.

store.get();

We can also look at the same details using the ​Explorer tool​.

The articles below give more information about Solidity and Smart Contracts:
● https://medium.com/zeppelin-blog/the-hitchhikers-guide-to-smart-contracts-in-ether
eum-848f08001f05
● http://candidtim.github.io/ethereum/2016/03/24/ethereum-quick-start.html
● https://ethereum.gitbooks.io/frontier-guide/content/writing_contract.html

In this section you are going to learn how to convert Testnet Bitcoins to RSK's Ginger Tesnet
Smart Bitcoins and viceversa. The process is popularly known as the 2-Way peg.

2-Way Peg Instructions for users (Testnet)


In this section you are going to learn how to convert Testnet Bitcoins to RSK's Ginger Tesnet
Smart Bitcoins and viceversa. The process is popularly known as the 2-Way peg.

Requirements
● You will need ​bitcoin-qt​ or ​bitcoind​ installed.
● You will need RPC access to an RSK node
● You will need ​web3​ to interact with the node.

Sending money from BTC to RSK


1. Start bitcoin-qt or bitcoind on Bitcoin Testnet, e.g.:
○ Bitcoin-Qt:
$ <path_to_bitcoin-qt>/bitcoin-qt --testnet -server -rpcuser=<yourUser>
-rpcpassword=<yourPassword>
○ Bitcoind:
$ <path_to_bitcoind>/bitcoind --testnet -server -rpcuser=<yourUser>
-rpcpassword=<yourPassword>

2. Wait for the Bitcoin blockchain to be up-to-date.


3. Make sure you have some Testnet BTCs to spend.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

4. Send a transaction (tx) from bitcoind/bitcoin-qt to the federation


address.
Federation address is: ​2NBPystfboREksK6hMCZesfH444zB3BkUUm
Minimum value is: ​0.01 BTC
○ Bitcoin-Qt: press "Send" button and follow the instructions on screen
○ Bitcoind: execute the following command:
$ curl --user <yourUser>:<yourPassword> --data-binary '{"jsonrpc": "1.0",
"id":"curltest", "method": "<sendtoaddress>", "params":
["2NBPystfboREksK6hMCZesfH444zB3BkUUm", <valueToSend> ] }' -H 'content-type:
text/plain;' http://<bitcoinIpAddress>:18332

5. Get the bitcoin tx hash.


○ Bitcoin-qt:
a. Go to the "Transactions" pane, right click on the tx and click the menu
option “Copy transaction id”.
b. You will get something similar to this:
01a3fb66c7b227e762b5ff429ed5936da0dd4efe9a70ea82337816974213e1
da. Paste this id in a text document or similar, you will need this in the next
step.
c. In case the id ends with -000, remove this trail and keep the rest of the id.
○ Bitcoind: you will get the tx hash when you execute the -"sendtoaddress"-
method in the previous step.
6. Get the BTC address that sent the BTC.
a. Open a web browser and go to: ​https://www.blocktrail.com/tBTC or to any
other Bitcoin Testnet block explorer.
b. Search for the tx id obtained in the previous step.
c. The address that sent the BTC corresponds to the first input address in the tx.
For instance, in ​this transaction the first input address is
mtZ81BSxSUr2BBhLhXGVwMQSVapgUEEuTn. The first input should spend
a P2PKH (pay to public key hash) output, i.e. the most common output in
bitcoin (Addresses in Testnet start with "m" or "n").
d. Copy the address.
7. Get the private key of the address that sent the BTC. Execute the following command
in a terminal:
$ curl --user <yourUser>:<yourPassword> --data-binary '{"jsonrpc": "1.0",
"id":"curltest", "method": "dumpprivkey", "params": ["<btcAddressThatSentTheBtc>"]
}' -H 'content-type: text/plain;' http://<bitcoinIpAddress>:18332
You will get something like to this:
cNbFnUdfYFMzZRd2QtcmnErMuEJuraxk784fTbSPyd5xWzt1AxyV​.
8. Convert the private key to RSK format. Use the following util: ​https://utils.rsk.co
9. Add the private key to your RSK node (optional). Use the private key you got in the
previous step. Execute the following two methods:
$ curl -X POST --data
'{"jsonrpc":"2.0","method":"personal_importRawKey","params":["<RSKConvertedPrivateKe
y>", "<passPhraseToEncryptPrivKey>"],"id":71}' http://<RSKNode>:<RSKNodePort>

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

$ curl -X POST --data


'{"jsonrpc":"2.0","method":"personal_unlockAccount","params":["<RSKAddressAsReturned
ByImportRawKey>", "<passPhraseJustUsedToEncryptPrivKey>", ""],"id":71}'
http://<RSKNode>:<RSKNodePort>

(RPC personal module should be enabled on the RSK node)

10. Get your RSK account address. Your RSK account address was shown to you when
you used ​https://utils.rsk.co​ and when you added the private key to the RSK node.

11. Please note that if your node is configured with the database reset setting in true
(check your RSK node configuration file), you will have add your private key to your
node every time your node is restarted.

12. Check that funds have arrived in RSK- You have to wait for 10 BTC Testnet
confirmations, and afterwards around 5 minutes until funds arrive in your RSK
account. Execute the following command in the RSK command console:
> web3.eth.getBalance("<RSKAccountAddress>");
(RSK account address must start with "0x").

Sending money from RSK to BTC


Check if your bitcoind/bitcoin-qt already has your private key.
Note: if you have transferred funds from BTC to RSK, and you are now using the same RSK
account address that received the funds to transfer back to BTC, then the BTC funds will be
received at the original BTC address that sent the funds to RSK.
If this is your case, and you have not deleted your bitcoind/bitcoin-qt database, you don’t
need to obtain your private key nor add it to bitcoind/bitcoin-qt since it is already there, and
you can skip steps until step #5.
To continue with the process, please access the the Github directory with all the latest
updates.

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart


Smart contracts powered by Bitcoin

RSK Labs, Inc. • rsk.co • educate@rsk.co • @RSKsmart

También podría gustarte