Nowadays, blockchain is often mentioned as one of the most disruptive technologies. Some argue that blockchains have potential to change almost every business and how they operate. Blockchain is not a completely new technology. However, it has gained super momentum in last couple of years. It is a big leap forward in terms of thinking about decentralized and distributed applications. This article does not discuss the fundamentals of this technology. There are many resources that describe the building blocks of a blockchain. In this article you will see how you can publish and use a smart contract running in an Azure Ethereum Blockchain.
While there are many different blockchain platforms, there are a few that stand out in terms of agility, usability and momentum. The Ethereum blockchain is one of them. Most Ethereum projects today rely on Ethereum as a public blockchain, which grants access to a larger audience of users, network nodes, currency, and markets. However, there are often reasons to prefer a private blockchain or consortium blockchain (among a group of trusted participants). While these private/consortium blockchains may not have any connection to the public blockchain, they still contribute to the overall Ethereum ecosystem by investing in Ethereum software development. Over time, this translates into software improvements, shared knowledge, and job opportunities.
Azure Blockchain
Microsoft Azure offers various options to host a blockchain platform. E.g. Microsoft Partners offer more than 30 other Blockchain solutions on Azure, such as Emercoin, STRATO, GoChain, Waves and many more. Published and maintained by Microsoft are the following options:
Azure Blockchain Workbench
The Azure Blockchain Workbench is the fastest way to get started with blockchain on Azure. This tool allows developers to deploy a blockchain ledger along with a set of relevant Azure services most often used to build a blockchain-based application.
DevTest Labs for Blockchain as a Service
DevTest Labs for Blockchain as a Service helps developers and testers to quickly create virtual machines in Azure to deploy and test their blockchain applications
Hyperledger Fabric Consortium
This solution deploys a Hyperledger Fabric single member network, consisting of a member node that runs the membership services, an orderer node that runs the communication services, and a set of peer nodes that execute transactions.
Ethereum Proof-of-Authority Consortium
This solution deploys a flexible Ethereum Proof-of-Authority (PoA) network, consisting of a set of highly-available Parity nodes with which an application or user can interact to submit transactions.
Ethereum Proof-of-Work Consortium
This solution deploys a flexible Ethereum network, consisting of a set of load-balanced transaction nodes with which an application or user can interact to submit transactions and a set of mining nodes to record transactions
We will be using an Ethereum Proof-of-Work Consortium blockchain to publish our smart contract.
You can set up the Ethereum Blockchain in Azure as follows.
If you not already have an Azure account, you can create one for free at https://azure.microsoft.com/en-us/free/. With your free account, you can get $200 of credits to use any Azure service for 30 days and over 25 services that will always be available for free. A blockchain network is not a free service, but $200 will get you started and give plenty of opportunity to try it out.
After the account creation, you need to create the Ethereum network to start with the blockchain. In the Azure portal, click on Create a resource and enter Ethereum Proof-of-Work Consortium in the search field. On next few screens enter all the required information and click on create. It can take between 5-45 minutes to provision, depending on the size and complexity of the network. Once complete, through the administrator web page, you can configure additional Ethereum accounts to get started with smart contract, and eventually application, development. The URL for the administrator web page is the first output of the deployment.
the release of this solution is a great opportunity to learn about the technology in an easy and configurable manner on Azure. For a complete walkthrough of the steps to create this network check out this page: https://docs.microsoft.com/en-us/azure/blockchain/templates/ethereum-deployment
Once your network is up-and-running, we can create and publish a smart contract.
Smart Contracts
A smart contract is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. The idea of smart contracts was first conceived in 1993 by Nick Szabo, a computer scientist and cryptographer. In a 1994 essay, Nick wrote “The general objectives of smart contract design are to satisfy common contractual conditions (such as payment terms, liens, confidentiality, and even enforcement), minimize exceptions both malicious and accidental, and minimize the need for trusted intermediaries. Related economic goals include lowering fraud loss, arbitration and enforcement costs, and other transaction costs. Some technologies that exist today can be considered as crude smart contracts, for example POS terminals and (credit) cards, EDI, and agoric allocation of public network bandwidth.”
Although smart contracts only really became possible with the creation of Bitcoin in 2009, it was Ethereum that embraced it completely. This made it possible to execute and store smart contracts within a distributed ledger. Ethereum’s platform was specifically designed for executing smart contracts, making digital transactions of any kind possible and seamless. In its current state, smart contracts are the building blocks of all blockchain technology. Smart contracts use the network of nodes to validate whether aspects of the agreement have been completed. They don’t need an intermediary like a lawyer to validate the existence of these aspects.
Contract accounts in Ethereum are able to pass messages between themselves as well as doing practically Turing complete computation. The contracts live on the blockchain in a Ethereum-specific binary format called Ethereum Virtual Machine (EVM) bytecode. The code of a smart contract is usually written in some high level language such as Solidity and then compiled into bytecode to be uploaded on the blockchain. To get more details on Solidity, please go through solidity documentation https://solidity.readthedocs.io/en/develop/.
Development tools
To create a solidity smart contract you can use Visual studio code with Solidity extension or Remix. You can download Solidity extension for Visual studio code from https://marketplace.visualstudio.com/items?itemName=ConsenSys.Solidity. You can get more details about Remix from this GitHub location: https://github.com/ethereum/remix. To setup a complete local development environment, Truffle is recommended: https://truffleframework.com/. Truffle is a testing framework and asset pipeline for Ethereum-based blockchains. The Truffe Framework website includes Ganache, which is a personal blockchain for Ethereum development. This makes it easy and quick to deploy contracts, develop applications, and run tests.
For the purpose of this article, we will be using Solidity and Remix to write the smart contract that can be published to our Ethereum network in Azure. Navigate to https://remix.ethereum.org and click on the (+) symbol in the top left corner to create a new file. Name the file to your liking, and enter the following code.
pragma solidity ^0.4;
contract Disposable {
/* Define variable owner of the type address */
address owner;
/* The constructor is executed at initialization and sets the owner of the contract */
constructor() public { owner = msg.sender; }
/* Function to remove this contract */
function kill() public { if (msg.sender == owner) selfdestruct(owner); }
}
contract Welcomer is Disposable {
/* Define variable greeting of the type string */
string greeting;
/* The optional states of the contract */
enum State { Hailed, Greeted }
State public state;
event StateChanged();
/* This runs when the contract is executed */
constructor() public {
state = State.Hailed;
}
function acceptGreeting(string _greeting) public
{
greeting = _greeting;
state = State.Greeted;
emit StateChanged();
}
/* Main function */
function sayit() public constant returns (string) {
return greeting;
}
}
You can use Remix to interact with the contract. First thing to do is compile it. In the compile tab on the right, click Start to compile. You should see the following message.
The contract is a simple one, just to demonstrate a few features of Solidity. As you can see, the language allows for inheritance. The syntax may resemble JavaScript, but it’s not the same and there are some caveats. For example, string concatenation is not natively supported. The only way to manipulate strings is to convert the array of characters in a string to bytes. Check out the links at the bottom of the article on ways to deal with this. Due to the distributed and asynchronous nature of blockchain, events are important. Events allow the convenient usage of the EVM logging facilities, which in turn can be used to “call” JavaScript callbacks in the user interface of a distributed app, or dapp, which listen for these events. A lot of smart contracts work as a state machine. This pattern splits up the functionality of a smart contract into a number of different “states”. At any given point in time, the contract is in one and only one state, during which only state-specific functionality is possible. The contract can transition between these states in a pre-defined way.
When you writing the code of your contract, you will undoubtedly see loads of examples on the web. There are resources, like https://openzeppelin.org/ that collects and distributes reusable smart contracts so you don’t have to figure everything our yourself. Also, at https://consensys.github.io/smart-contract-best-practices/ you can find a good collection of best practices. As Solidity is improved sample code may not work immediately, or you will see warnings that the syntax you use is deprecated. Either change your code, or use a pragma directive to specify the compiler version your code is good with. In fact source files should be annotated with a version pragma to reject being compiled with future compiler versions that might introduce incompatible changes.
Publishing and using the Smart Contract on Azure
Since you have already deployed the Ethereum consortium network on Azure, can go to the administrator page to get a view of your blockchain network and sanity check the deployment state. The URL of the admin page is the DNS name of the load balancer. To find it, select the resource group that was deployed. Then, select Overview, and click on the link immediately under Deployments that shows the number that succeeded. The following deployments should be visible.
Click on the deployment resource that starts with microsoft-azure-blockchain. In the Outputs-tab you will see the location of the various resources that have been created as part of this blockchain.
To deploy the smart contract we created earlier, we need to copy the Ethereum RPC Endpoint. Copy this address to your clipboard, and then go back to your Remix page. Under the Run tab in the top right corner, select Web3 Provider.
Paste the address of the Ethereum RPC Endpoint from Azure.
NOTE! There is a solid chance that you will hit an error stating that Remix could not connect. This is because the RPC endpoint address is on http instead of https. I have no idea why the deployment does not create SSL enabled addresses. If you get this error, change the Remix address to http as well. Be sure to save you smart contract code (locally) first, because you will get a default project setup when navigating away.
Once you are connected to your own Ethereum network on Azure, you can deploy the contract. Click on the Deploy button in Remix to deploy the contract. You should see the following.
You may get the message creation of Welcomer errored: authentication needed: password or unlock. If that’s the case, go to ADMIN-SITE of your Ethereum network and bootstrap a new address with Ether. I used 0x7F11cbEC9235FCbF43827eFa492E80488a0feBE1 as a random address (go to https://vanity-eth.tk/ to generate addresses). After that, deployment was successful.
Now you can interact with your contract through remix or in your own code.
If you click acceptGreeting, the following output should be visible.
You can click the other buttons to try the various functions within the contract.
Summary
We introduced the various blockchain solutions you can deploy and use in Azure. We then created an Ethereum blockchain and deployed a smart contract using Remix. All this can be done in less than an hour, showing you that it’s really easy to get started with your own consortium blockchain. The benefit of a consortium blockchain is that you don’t have to invest real money in buying Ether to work with the public Ethereum network. Obviously, hosting in Azure is not completely free. Nonetheless, you can get started for free and use the 200 dollar of credits to build and test your setup.
More resources
Working with string in solidity: http://coders-errand.com/working-with-strings-in-solidity/
Ethereum Smart Contract Security Best Practices: https://consensys.github.io/smart-contract-best-practices/
A Solidity Implementation of the State Machine Design Pattern: https://medium.com/tokenfoundry/a-solidity-implementation-of-the-state-machine-design-pattern-25de8b1dfbc5
Best Practices to Level Up Your Ethereum Smart Contracts: https://hackernoon.com/best-practices-to-level-up-your-ethereum-smart-contracts-944d5cea2cab
Ethereum proof-of-work consortium solution template: https://docs.microsoft.com/en-us/azure/blockchain/templates/ethereum-deployment