Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Technical Course
Blockchain & Smart contracts powered by RSK
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.
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 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
Subcurrency Example 45
Hands-on-case 47
Voting 47
Possible Improvements 50
Creating tokens 50
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
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.
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.
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). In 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
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.
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.
Seen the previous concepts of cryptography, it is time to go deeper into some blockchain
concepts.
Transaction components
Hence, the transaction is sent to the closest node on the bitcoin network.
It expects to be added to the blockchain by a miner.
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
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
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)
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.
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.
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.
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
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?
In the following table we listed a summary of each of the Consensus techniques analyzed. 9
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
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
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.
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
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.
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.
Use cases
The followings are examples of common use cases for Smart Contracts:
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
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
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 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.
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.
.
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.
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
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 thirdparty 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 crosstransfer, 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
crosschain 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 multisig 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:
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, postlock period must also exist as MAD
disincentive. The following diagram depicts a drivechain:
Drivechain Diagram
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
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.
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.
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
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.
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.
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).
contract Purchase {
address public seller;
Events
Events are convenience interfaces with the EVM logging facilities.
contract SimpleAuction {
event HighestBidIncreased(address bidder, uint amount); // 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).
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).
contract Purchase {
enum State { Created, Locked, Inactive } // Enum
}
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
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;
}
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.
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.
if (!projects[addr].initialized) {
throw;
}
projects[addr].funds += msg.value;
if (projects[addr].funds > winningFunds) {
winningAddress = addr;
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;
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:
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:
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
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.
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
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:
contract MyToken {
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, 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
}
For more details about the process, you can access to https://ethereum.org/token
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
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.
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 also follow the steps below with this video.
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.
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 ] }
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.
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');
npm install
node sync3nodes.js
As you can see the three nodes have the same blocknumber, so there are synced correctly.
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.
module.exports = {
networks : {
development : {
gas : 2500000,
from : "0xcd2a3d9f938e13cd947ec05abc5fe734df8dd826",
host : "localhost",
port : 4444,
network_id : "*" // Match any network id
}
}
};
Now just migrate the current contract we've been working so far:
truffle migrate
store.get();
store.set(123).then(console.log);
{ tx: '0x3809925e7927c4a7a135e2ba4009a66f39942e3182fc313c1bdcde5f3149005a',
receipt:
{ transactionHash: '0x3809925e7927c4a7a135e2ba4009a66f39942e3182fc313c1bdcde5f3149005a',
transactionIndex: 0,
blockHash: '0xa2f204cc944ae19c30f53e2813f65b66f2af8d27d6200584dac9c1b7b446feaf',
blockNumber: 1023,
cumulativeGasUsed: 41605,
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.
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.
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").