Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Setting Up A TomoChain

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

BLOCKCHAIN 101:

Session 2 of 5: Setting Up a
Development Environment
1. Recap
2. General Requirements
3. Building a Development Environment
4. Smart Contract Workflow
5. Installing a Simple Web3 Frontend with Web2Py
6. Building a Blockchain Certification System

Developed by Certified by

Introduction to Blockchain & Tomochain


Recap
● Blockchain is a series of distributed, immutable, and public records.

● Ethereum is interesting because we can store and execute


programs (‘smart contracts’) on a blockchain.

● TomoChain is exciting for developers because we can do that faster


and cheaper, opening up new applications.

● Solidity is the language used to write these applications -- while


similar to C it has some unique quirks and challenges.

Introduction to Blockchain & Tomochain


General Requirements
1. Create a TOMO wallet by installing the App, selecting advanced, and changing the network to
TestNet
2. If running Windows enable Windows subsystem for Linux and install from Windows Store.
○ Developing natively in Windows is possible, but the Linux command line is more powerful,
better documented, and easier to use.
○ 3 easy ways to install
3. Install Truffle
○ Truffle is a tool to compile and deploy smart contracts. It is flexible enough to deploy to
blockchains other than Ethereum (such as TomoChain)
○ As with most powerful software tools, it has no graphical user interface.
4. Install Truffle-HDWallet-provider
○ This tool lets us configure our connection to TomoChain and sign transactions
5. Update NodeJS
○ NodeJS is required by Truffle. Having the wrong version causes strange bugs
6. Configure to use Tomochain instead of ethereum
○ Define the method to connect to Tomo TestNet and MainNet, including our mnemonic or
private keys
Introduction to Blockchain & Tomochain
Installing Linux on Windows 10
How to Instal Linux on Windows 10:

● Install Linux using Microsoft


Store
● You can install your preferred
Linux Distribution

Introduction to Blockchain & Tomochain


Setting Up and Using Linux
If running MacOS, an older version of
Windows, or another operating
system, VirtualBox can be used to run
Linux inside your operating system
like a program.

In MacOs you can install the required


tools natively with HomeBrew.

Introduction to Blockchain & Tomochain


Faster Alternative Install
Sign up for a free tier Google Compute instance running Debian or Ubuntu Linux. You can sign in
with a web browser.

This has sufficient computing power for our purposes, costs nothing, and saves your work in the
cloud too. All you need is an internet connection -- this is the fastest way to get started.. We start by
logging in and increasing our swap size since the free server is small (check with free -m):

sudo fallocate -l 1G /swapfile //create a 1GB swapfile

sudo chmod 600 /swapfile //make accessible only to root

sudo mkswap /swapfile //mark the file to be used as swap space

sudo swapon /swapfile //Activate the swap

echo "/swapfile none swap sw 0 0" | sudo tee -a /etc/fstab //Optional: make ths persistent

Introduction to Blockchain & Tomochain


Creating a TomoChain TestNet Wallet
● Download the app on play store

● Create a new wallet save your


mnemonic. Press the menu button,
select advanced, and change your
network to Testnet.

● You can get more TestNet TOMO here if


needed:
https://faucet.testnet.tomochain.com/

(or there’s a button in the app)

Introduction to Blockchain & Tomochain


Installing and Updating NodeJS

Run the following command

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

Logout and back in (or reboot), then nvm install node

npm install -g npm@latest

node -v

npm - v

Introduction to Blockchain & Tomochain


Installing Truffle and hd_wallet

Run the following command:

npm install -g truffle

npm install truffle-hdwallet-provider

Enter your home directory, create a folder for your project, and enter it

cd ~

mkdir testingtomo && cd testingtomo

truffle init

Note the new directories as well as truffle-config.js

Introduction to Blockchain & Tomochain


Configuring for TomoChain
Replace the content of truffle-config.js as
specified here:

● https://medium.com/tomochain/how-to-
build-a-dapp-on-tomochain-85532a1192e
7

Remember to enter the mnemonic phrase we


saved earlier.

Now Truffle is configured to connect to


Tomochain and we can deploy smart
contracts.

Introduction to Blockchain & Tomochain


General Workflow
Write your smart contract out in Remix:
https://remix.ethereum.org/

When it compiles without errors, copy it to a .sol file


under /project/contracts

In /project, run truffle compile

Enter /project/migrations and create a file


2_deploy_contracts.js containing:

var Contractname = artifacts.require("Contractname");


module.exports = function(deployer) {
deployer.deploy(Contractname);
};

Introduction to Blockchain & Tomochain


General Workflow (con’t)
Now we deploy to Testnet , and keep the destination contract address. Be sure you have enough TOMO to
do this!

run truffle deploy --network tomotestnet

Congratulations, you have a smart contract on the Testnet.

Finally, get the ABI from /build/contracts/name.json -- be sure just to get the section in and including [ ]
brackets. Any web application you write will need this to interact with your smart contract.

Introduction to Blockchain & Tomochain


Simple Web3 Frontends
Web3 is a tool that lets your web server interact with a blockchain.

● Web applications can then use that data to ‘do something useful’ for our users.

Web2Py is a simple Python framework that we can use to build simple web applications. More advanced
options include Flask (Python), Node.js, React.js, and Angular.js

● Web3 is available as a library for both JavaScript and Python. The Javascript library is probably more
popular, but the Python language itself is more popular -- we’ll use Python today since it’s easier to
read.
● Both libraries work the same way in any case.

Introduction to Blockchain & Tomochain


Installing Python3 and Web3
First, we need a HTTPS certificate. If you are running locally you don’t need this, but otherwise HTTPS is
forced on an admin login we’ll need later:

openssl genrsa -out server.key 2048

openssl req -new -key server.key -out server.csr

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Remember where you put server.key and server.crt!

Introduction to Blockchain & Tomochain


Installing Python3 and Web3
Now we need a python3 environment:

sudo apt-get install build-essential autoconf libtool pkg-config python-opengl python-imaging python-pyrex
python-pyside.qtopengl idle-python2.7 qt4-dev-tools qt4-designer libqtgui4 libqtcore4 libqt4-xml libqt4-test libqt4-script
libqt4-network libqt4-dbus python-qt4 python-qt4-gl libgle3 python-dev

sudo apt-get install python3-setuptools

sudo easy_install3 pip

sudo apt-get install python3-dev

sudo pip3 install web3

Introduction to Blockchain & Tomochain


Installing web2py
Get the source code:

wget https://mdipierro.pythonanywhere.com/examples/static/web2py_src.zip

sudo apt-get install unzip && unzip web2py_src.zip

Make sure port 8000 is open to tcp under network-->VPC Network-->Firewall rules

Finally:

python3 web2py.py -a 'password' -c server.crt -k server.key -i 0.0.0.0 -p 8000

Now we navigate to https://<ip address>:8000

Introduction to Blockchain & Tomochain


A Crash Course in Web2Py
Our focus is mainly on smart contracts, but a short lesson on Web frontend basics will be useful in
understanding how smart contracts interact with websites.

Web2Py and many web application frameworks work on the model-controller-view system.

Model: Defines how the data is handled and stored

Controller: Defines how data is processed

View: Defines how the data from the model is displayed

Today we will write a small application that interacts with a smart contract that issues educational
certification on TomoChain. We’ll worry about the smart contract itself tomorrow -- for now let's just worry
about sending and receiving data from the blockchain.

Introduction to Blockchain & Tomochain


A Simple Model: db.py
In our Model, we import a few modules we need and define our database structure:

from gluon.contrib.appconfig import AppConfig


from gluon.tools import Auth
import hashlib
import web3
import binascii
from gluon.tools import Service
service = Service()

db.define_table('students',Field('address', type='string', length=255, default=None,


required=True, notnull=False, unique=False),
Field('Name', type='string', length=255, default=None,
required=True, notnull=False, unique=False),
Field('gradelist', type='string', length=500, default=None,
required=False, notnull=False, unique=False))
links = [lambda row: A('Certify',_href=URL("call/run/tsend",args=[row.address, row.Name, row.gradelist]))]

Introduction to Blockchain & Tomochain


Control: default.py
First, some setup:

from web3 import Web3, HTTPProvider, IPCProvider, WebsocketProvider


import time
import datetime
import json

with open('/home/sean/web2py/web2py/applications/Certify/controllers/Certify.json') as f:
abi = json.load(f)

w3 = Web3(HTTPProvider('https://testnet.tomochain.com'))
contract_address = '0x0B2B9FB74aD129f0D296AC72CE43166caA044383'
contract = w3.eth.contract(address = contract_address, abi = abi)

Introduction to Blockchain & Tomochain


Control: Building a Transaction
Next we define a function to store exam results on Tomochain. It stores the Tomo address, name, and grades
of students. We start with some definitions, then we build a transaction that contains the data.

setStudent is a specific function of the smart contract -- we’ll see how that works tomorrow.

def store_results(address, Name, gradelist):


wallet_private_key = '4a27b6c6401357e426a21a09d6d9e989a6d633e38142811d85da8e6b21590fa2'
wallet_address = '0x29aF7320c45953014FB4445c28beEFb40E0899a3'
wallet_address = Web3.toChecksumAddress(wallet_address)
nonce = w3.eth.getTransactionCount(wallet_address)

txn_dict = contract.functions.setStudent(address, Name, gradelist).buildTransaction({


'chainId': 89,
'gas': 140000,
'gasPrice': w3.toWei('40', 'gwei'),
'nonce': nonce,
})

Introduction to Blockchain & Tomochain


Control: Signing and Sending
Once the transaction that does what we want is created, we execute it by signing and sending it. The smart
contract in question will only add student data if it is signed by the contract owner.

signed_txn = w3.eth.account.signTransaction(txn_dict, private_key=wallet_private_key)

result = w3.eth.sendRawTransaction(signed_txn.rawTransaction)
tx_receipt = w3.eth.getTransactionReceipt(result)
count = 0

while tx_receipt is None and (count < 30):


time.sleep(10)
tx_receipt = w3.eth.getTransactionReceipt(result)
return(tx_receipt)

if tx_receipt is None:
tx_receipt = "Failed"
return(tx_receipt)

Introduction to Blockchain & Tomochain


Control: Checking Certification
This one is easier -- our smart contract in question has a function that returns student if you provide the
Tomo address:

def check_certification(address):
tx_receipt = contract.functions.getStudent(address).call()
return(tx_receipt)

Introduction to Blockchain & Tomochain


A Note on Services
If we call these functions with services, we’ll have an easier time testing them in a minute!

@service.run
def tsend(address,Name,gradelist):
address = str(address)
Name = str(Name)
tx_receipt = store_results(address, Name, gradelist)
return tx_receipt

def call():
session.forget()
return service()

@service.run
def tcheck(address):
address = str(address)
tx_receipt = check_certification(address)
return tx_receipt

def call():
session.forget()
return service()

Introduction to Blockchain & Tomochain


Control: Organizing Data
Web2Py provides a tool called a ‘Smartgrid’. It will automatically provide a user interface where we can create, read, update, and
delete data (CRUD):

def index():
response.view = 'generic.html' # use a generic view
grid = SQLFORM.smartgrid(db.students, deletable=True, editable=True, user_signature=False, links=links)
return dict(grid=grid)

Pay careful attention to user_signature=False -- this disables all login-based access control to the database.
Probably you won’t want that behavior for a live application :)

Introduction to Blockchain & Tomochain


Let's Give it a Try
● Remember -- code is 100x more likely to fail in front of a live audience!

● Remember, at the end of the class tomorrow there will be a short quiz!

● Also: We’ll airdrop you some Tomo if you attend our hackathon April 20-21st

Introduction to Blockchain & Tomochain


Join Our Upcoming Events

April 6-7, 2019:


Tomochain Dapp Development Workshop

April 20-21, 2019:


Tomochain Hackathon 2019

Developed by Certified by
Introduction to Blockchain & Tomochain

You might also like