Running a Things Network Application on a Private Ethereum Blockchain
Who can ignore the hype of blockchain and crypto currencies this past year? While most of the interest was and still is financially driven, we as developers realized the importance of blockchain technology and decentralized applications. In order to familiarize ourselves a bit with Ethereum’s development stack, we decided to explore how to build a decentralized backend service for one of our IoT applications.
At Async, we build IoT solutions using LoRa™ technology and The Things Network (TTN). TTN is an open sourced LoRaWAN network that makes working with LoRaWAN easy. They provide a wide range of open sourced tools, good documentation, and most important of all, a vibrant and active community.
This guide requires an application with at least one device that is fully configured and running on TTN.
Installing geth and swarm
geth
is a multipurpose command line tool that runs a full Ethereum node. We’ll be using geth to create a new wallet, initialize our private chain with our genesis block, and mine our smart contract and transactions.
swarm
is a distributed storage platform and content distribution service built as a native layer to Ethereum.
We’ll be using swarm to upload/download uplink packets from our end nodes.
1. Create a directory for the source code
Please install Go language if you haven’t already.
mkdir -p $GOPATH/src/github.com/ethereum
2. Clone repository
cd $GOPATH/src/github.com/ethereum
git clone https://github.com/ethereum/go-ethereum
3. Install geth and swarm
cd go-ethereum
go install ./cmd/geth/
go install ./cmd/swarm/
4. Check if everything installed properly.
To go install
command creates the project binaries in the workspace’s bin directory (located at $GOPATH/bin).
cd $GOPATH/bin
./geth version && ./swarm version
Create data directory and account
1. Create a data directory
Designate a directory for the blockchains database and account keystore. I recommend adding this to your ~/.bashrc
, ~/.bash_profile,
or whatever your shell uses.
echo "export DATADIR=/path/to/myDataDir" >> ~/.bashrc
source ~/.bashrc
2. Create an account
geth --datadir $DATADIR account new
After you’ve entered your passphrase, you’ll receive the public wallet address of your new account. You must remember this passphrase to unlock your account in the future.
Clone sample project
git clone https://github.com/async-la/ttn-eth
The sample project is a clone of https://github.com/truffle-box/react-box and provides us with all the tools to complete the demo. The project uses Truffle, a development framework for Ethereum that allows us to easily compile, link and deploy smart contracts.
Creating Genesis Block
Every blockchain starts with the genesis block. The settings of that initial block and the rest of the blockchain are defined in a single JSON file. The genesis file located in the sample project looks like this.
NOTE: You’ll need to replace <ACCOUNT_ADDRESS> with the public wallet address from the account you just created.
Breakdown of fields:
chainId: An identifier for our private chain and is used in replay protection.
https://github.com/ethereum/eips/issues/155
difficulty: Difficulty level applied during the nonce
discovering of this block.¹ We’re using a low value for this example in order to mine blocks quicker.
gasLimit: A scalar value equal to the current chain-wide limit of Gas expenditure per block.¹
alloc: Allows defining a list of pre-filled wallets.¹
Remember to use the wallet address of the account created earlier.
geth --datadir $DATADIR init genesis.json
Starting Geth and Swarm
Now that we’ve initialized our private chain with our genesis block, we can start our geth and swarm instances.
1. Starting Geth
geth --datadir $DATADIR --rpc --rpccorsdomain '*' console
In the development console, unlock your wallet and start mining.
> personal.unlockAccount(eth.coinbase)
> miner.start()
Note: By default your wallet will be unlocked for 300 seconds(5 min).
We can set the duration to 15 minutes with the following.
personal.unlockAccount(eth.coinbase, "<PASSPHRASE>", 900)
2. Starting Swarm
swarm --bzzaccount <WALLET ADDRESS> --datadir $DATADIR --ens-api '' -corsdomain '*'
NOTE: CORS domain is set to a wildcard for DEMO purposes only!
Writing our Smart Contract
“Smart contracts are account holding objects on the Ethereum blockchain. They contain code functions and can interact with other contracts, make decisions, store data, and send ether to others. Contracts are defined by their creators, but their execution, and by extension the services they offer, is provided by the Ethereum network itself.” ²
Our smart contract will serve as a generic backend for our TTN application. The contract contains a combination of getter and setter methods which are shown in the image below.
We’ll split these methods between a backend and frontend client. The back-end client will use the setter methods to register new devices and keep track of device uplink packets. The front-end client will use the getter methods to build a simple UI to display the content stored in our smart contract.
Note: Getter methods DO NOT have any transaction or execution cost unless they are being called from another smart contract.
Compiling Smart Contract
Contracts are located in your project’s contracts/
directory.
Contracts need to be compiled on initial deployment and after any changes.
truffle compile
Migrating Smart Contract
Migrations help us deploy contracts to the Ethereum network and are responsible for staging our deployment tasks. Truffle provides a special Migration contract that keeps a history of previously run migrations.
truffle migrate
Starting Our Backend Service
We’ll be creating a small backend service that will serve as the communication layer between our TTN application and our smart contract. For this, we use TTN Node.JS SDK and web3.
Update the following lines in server.js
https://github.com/async-la/ttn-eth/blob/master/server.js#L4-L6
node server.js
Our backend service:
- Sets local instance of geth client as the provider web3
- Create an instance to our contract
- Initialize TTN application and data clients
- Register new devices in our contract
- Upload device uplink packets to Swarm and store resulting hash
Starting Front End App
Time to bring everything together with a small front end application that’ll display the state of our smart contract and demonstrate how uplink packets are fetched from swarm.
npm start
Wrapping up
Phew, we made it! Here’s a look at all the services running.
Please feel free to reach out with questions by posting a comment below or message me directly on TTN’s slack group. You can also take a look at the README document of the sample project to see the list of commands to get everything setup.
Stay tuned for more articles articles surrounding IoT and Blockchain technology. Thanks!
Links:
Troubleshooting:
- Check that the genesis block is pre-filled with the correct wallet address.
- Double check that you’ve unlocked your account when migrating new contracts or running the backend server.
- Make sure you’ve ran
miner.start()
after initializing your geth client.
Async builds high performance, reliable, and cost-effective applications by combining technical expertise and deep knowledge of industry trends.
For more information on development services, visit asy.nc
—