Solidity and the Ethereum Virtual Machine

Welcome to the first decentralized global computational machine.

Over the past couple weeks I have been reading the Homestead release notes, the Solidity Documentation, watching youtube videos about Ethereum; really just an all out effort on trying to understand what this protocol is and why it is a technological successor to Bitcoin. In trying to explain it to others(or even write about it on here) I come to the notion that it is:

A global cryptographic, decentralized, immutable, permissionless world computer.

And in relation to the protocols of that which it is built on.

Internet = Communications

Bitcoin = Money

Ethereum = Computation

Without the Internet Bitcoin could have never existed and without Bitcoin, Ethereum could have never existed.

Now that’s a bold claim but I’m willing to make in that I truly believe that the predecessor technology has enabled this new paradigm in decentralized computing.

Bitcoin has and will continue to enable an unimaginable number of new and disruptive applications which will impact a number of verticals. I use my Shift card every day, wake up and check the price with an eye half open, and I anticipate my full attention will be back as we approach The Halvening. But right now, I want to learn how to write Smart Contracts in the Solidity programming language. I want to know how these contracts are compiled onto the Ethereum Virtual Machine (EVM). And how this is powering the next generation of peer-to-peer technology.

Installation and Setup

Download the latest Ethereum Wallet

Install Mix IDE, the IDE for authoring Smart Contracts using the High Level Language Solidity.

Program Solidity contracts on Visual Studio

You can also use the Online Compiler

The Ethereum Computer

The EVM is stack-based execution environment that uses Smart Contracts (similar to object-oriented classes) and HTML, CSS, and JavaScript to create dApps. When you are running a decentralized application (dApp), every instruction is executed on every node of the network. This means the operands for the instructions are taken from the stack, and it is also where the results are added. This is the low level assembly code of the EVM and the resulting flow-control functions that can be found in the Ethereum Yellow Paper. Items are pushed to the Stack and can be manipulated using POP (remove top item from the stack), SWAP (Swap item order on the stack / Limit of 16 elements), and DUP (copy and order new item on top of the stack).

Memory and Calldata

The stack also extends Memory and Calldata to be used in during program execution. Memory is an expandable byte-array used to store data during program execution. It can be accessed using the MSTORE and MLOAD instructions. Calldata is a byte-array, just like memory, but it is read-only. It contains the data from the transaction that triggered the code execution in the Contract.

Storage

Storage is a map used for fields in contracts. A contract can neither write nor read any storage other that its own. Essentially it is permanently storing the state variables within the contract.

Elements of the Ethereum Smart Contract

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
  • Enum Types

with Parameters of:

  • The gas-price I want to pay (gasPrice).
  • The maximum amount of gas that may be spent (gas).
  • The amount of ether I want to transfer (value).
  • My account address (from).
  • The target account address (to).
  • The nonce (nonce).
  • The transaction data (data).

A smart contract’s code resides in a Contract Account. It is unalterable once deployed.

Accounts in Ethereum

There are two kinds of accounts on the Ethereum network: Externally Owned Accounts (Public-Private Key) and Contract Accounts.

Externally Owned Account (EOAs): an account controlled by a private key, and if you own the private key associated with the EOA you have the ability to send ether and messages from it.

  • Can have an Ether balance.
  • Can send transactions.
  • Are controlled by private keys.
  • Has no code.

Contract Accounts (CA): an account that has its own code, and is controlled by code.

  • Can have an Ether balance.
  • Can send transactions.
  • Can send messages.
  • Contracts are controlled by their contract code.
  • Only send transactions in response to other transactions that they have received. Therefore, all action on the Ethereum blockchain is set in motion by transactions fired from Externally Owned Accounts.
  • Every time a contract account receives a transaction its code activates, allowing it to read and write to internal storage and send other transactions/messages or create contracts.

EOA0 —-Transaction–> CA1 = Activate Code in CA1

CA1 —– Messages —> CA2, CA3, CA4= Perform functions in CA2, CA3, CA4

EOA1 —– Transaction —-> EOA2 = Send Ether EOA2

Ether

Ether, the currency used in Ethereum, is exchanged for computation on the platform. Gas is the name for the execution fee for every operation made on an Ethereum blockchain. Its price is expressed in ether and it’s decided by the miners, which can refuse to process transaction with less than a certain gas price. To get gas you simply need to add ether to your account. The Ethereum client automatically converts Ether to gas and gas to Ether when transactions are processed.

solid

When a transaction is sent from an EOA to a CA, it is sent with input code and Ether. The input code and ether is then processed by the Contract Account, thereby activating itself and thus executes its code. A CA can then send a message out to other (CA) contracts.The contracts are essentially talking and passing messages between themselves, in this way, sending a message is exactly like calling a function. This could produce another smart contract, send Ether to another address, register a vote of confidence, open a door to a house; virtually any sort of call to or update to the state of the decentralized network.

The total cost of a transaction is based on 2 factors:

  • gasUsed is the total gas that is consumed by the transaction
  • gasPrice price (in ether) of one unit of gas specified in the transaction

Total cost = gasUsed * gasPrice

An EOA can also send a transaction to another EOA and nothing happens accept transfer some Ether (P2P payment or ether).

Solidity

Visit the Solidity website to see example Smart Contracts and write and edit them within your wallet. You will be able to use Electron by Shapeshift to deposit bitcoin in exchange for Ether so you pay the mining fee and begin deploying your first smart contracts.

Start with the following three example smart contracts.

Create a cryptocurrency

Crowdfund your idea

Create a DAO

A new block is created every 15 seconds in Ethereum. Essentially you are sending binary data to invoke state transition rules through EVM bytecode at the assembly level thus updating the distributed state of the blockchain; AKA deploying your Smart Contract.

Mining Ether = Securing the Network = Verifying Computation on the Global Computer

Next: 3 RaspPi3’s, 32GB SD cards each a running the Ethereum computer (Web3.0, next-generation peer-to-peer technology platform) running on each…

Final Thoughts

Watch Ethereum for Dummies – Dr. Gavin Wood

A global cryptographic, decentralized, immutable, permissionless world computer.

Internet = Communications

Bitcoin = Finance

Etheruem = Computation

https://gateway.ipfs.io/ipfs/QmSbS6tk4GG4k2yEPWaYXBZquUxV1uxjmMsQyZTbM5Duyk

UPDATE:

This thing is AWESOME! I have been deploying contracts, sending transactions, and it’s all (near) real time. I can create a couple wallets and a couple cryptocurrencies and exchange them back and forth all confirming within 12 confirmations < a minute or 2. It’s pretty wild to keep the network stats up on on one screen the Wallet on the other and see them contracts confirm. Working on the front end now, possibly Salesforce integration + React.

Sources:

Ethereum White Paper

Ethereum Yellow Paper

Ethereum.Org

https://media.readthedocs.org/pdf/ethereum-homestead/latest/ethereum-homestead.pdf                 

https://media.readthedocs.org/pdf/solidity/latest/solidity.pdf

https://www.ethereum.org/assets

https://github.com/androlo/solidity-workshop

https://ethstats.net/

Smart Contracts and Chains of Distributed Ownership

Blockchains and sidechains: decentralized and distributed store of value and transfer networks that consist of replicated, unalterable, and time-stamped transaction ledgers.

Smart contract: a legally enforceable agreement written in computer code made by competent parties, to perform or not perform a certain act.  Contracts may be express or implied, bilateral or unilateral, executory or executed, and void, voidable, unenforceable, or valid. The contract is executed on the blockchain based upon met or unmet inputs.

Everyone who has been following the development of Bitcoin now understands that this is something way more profound then a new way to transfer money to the other side of the world in 10 seconds. We are now moving into the infrastructure that will enable the creation of a blockchain for any type of asset or organization. We know that the blockchain is a true computational advancement and it will be the foundation for a whole new ecosystem of financial technology. A new proposal by Blockstream, pegged sidechains, creates an internetwork of blockchains that are able to transverse to and from one another. This creates a fluid interoperable network of blockchains that have their own properties, rules, and units which can be pegged and transferred back and forth from the Bitcoin blockchain and other sidechains. It creates a complete new form of verifying and transferring ownership of assets, commodities, currency, and value in a distributed, unalterable, globally accessible network. Take any existing trust based business model that can be decentralized, apply this 10x blockchain technology and it will be decentralized (Johnston’s Law).

To be able to use this blockchain technology, you have to buy a unit of the network e.g. a bitcoin. There are only so many of these bitcoin units for the exponential number of people and things that will be using the network. This creates scarcity, value, and a number of network effects that further increase the liquidity of the bitcoin blockchain. By buying units of the network, you’re buying a globally transferable credit. You can program these credits into smart contracts which effectively let you determine when to allocate the units to other parties based upon met or unmet inputs. In doing so, you eliminate counterparty risk and can alternate between an internetwork of transaction ledgers without the need for a trusted third party. This concept effectively could bring everyone and everything onto the same financial grid to negotiate and authorize trade. You could authorize the transfer of title and a time stamped key to your secondary home. You could create an escrow smart contract on the blockchain that executes once both parties have fulfilled their promises in the bilateral agreement. You could buy or sell financial instruments and have same day affirmation. Not only does this augment p2p exchange, but also m2m or machine to machine. Autonomous vehicles communicating for road space, your refrigerator communicating with your solar panel for energy storage, your hard drive negotiating data storage space with another computer. It is a layer of value transfer without the need for a processor, an irrefutable layer of ownership without the need for an agent, a secure layer of storage without the need for a physical vault. The challenging part of this next stage is creating a UX that allows someone to build the bridge between the language of a legal contract and the language of a developer. It needs to be consumable by the general audience. Easier to implement and use then going through a specialized agent and trusting that they are going to not make any mistakes. For the consumer, the lexicon used in the contract model has to be simple enough to understand but detailed enough to cover all of the possible outcomes.

They will take time to implement, but the combination of smart contracts and side chains will undoubtedly bring us into a new age of distributed trust and ownership. We want to have a secure protocol that lets us move value from one chain to another but the Bitcoin blockchain wasn’t intended to scale or be used for anything other than bitcoin transactions. The problem is it is too risky to make a hard fork to the Bitcoin source code that is not backward compatible.

Sidechains

We know that some amount of hashing power will move the coin from the bitcoin blockchain to the sidechain. It is not feasible to provide a full proof in the entire history of the blockchain to bring that coin back to the bitcoin blockchain. When you run a full node, your node checks every single block. Your node checks the height from block 332,000 all the way down to the genesis block making sure that it is first linking the entire train and making sure every transaction is valid. The sidechain proposal is a (Simplified Payment Verification) SPV proof, a method that shows the path of an asset to verify that each transaction in its history in the sidechain was valid. With an SPV, it uses the block header to check the blocks depth in the blockchain, or how many blocks it has been since the transaction took place. If it has been 10 blocks since the transaction took place, we have 10 blocks of trust versus the entire block chain of trust or 322,000 blocks of trust.  When you move something from a sidechain back to bitcoin blockchain the problem is that that move requires a proof of hashing power to verify the transactions that happened in the sidechains were valid. The bitcoin is held in stasis until there is proof that it is valid and come back to the bitcoin blockchain. If the pool is hacked or 51% attack takes place on the sidechain, it could permanently destroy the bitcoins that were moved to that sidechain.

Is Mergemining a valid solution?

With mergemining the same hashing power that keeps bitcoin secure, keeps the sidechain secure. The mining part is zero different, you just have to setup a full node and download the entire blockchain of the sidechain. Namecoin is an alternative decentralized domain name system that reuses the bitcoin blockchain for hashing its chain. The same hashing power that keeps bitcoin secure, keeps Namecoin secure. The incentive for mergemining is the miners get to mine both coins. In fact 3/4 of the bitcoin hashing power is also mining Namecoin. So say all of these SHA 256 based cryptocurrency sidechains start emerging. You realize there are an unlimited number of chains that you can mine at the same time. Any sidechain that uses a SHA 256 merge mining protocol. The only additional overhead is additional data storage to keep the the entire blockchain of each sidechain. So in theory you can build a miner that has every single blockchain downloaded to it, and this thing would be an absolute cryptomachine mining like 2500 different blockchains. This mergemining is allowing you to use the SHA 256 to record and verify because it uses the same work. You could mine thousands of chains but there is a maintenance cost for mergemining; setting up a node for each blockchain. You can mine all of these different sidechains and this is great but ultimately the big issue is that mergemining leads to further centralization. These sidechains need honest miners with lots of hashing power running full nodes to secure the network. The security is in the mining, its the backbone of the technology. How the mining process is organized. If mergemining isn’t a long term solution to achieve scalability, fluid interchangeability, and security for user created assets, then what is?

Treechains

A new proposal, treechains, would take the block and divide it up into levels of binary branches. So what is this effectively doing and why does it secure the mining? The process is bringing specialization and decentralization to the transaction recording and verification process. Instead of linearly recording and verifying each block, you can split the block up to be worked on at different levels. You sign and timestamp transactions a few levels down, not even knowing what they mean and if they are valid, but your signature verifies that they existed at the point in time. You act as a notary and some other miner for whom the transaction is significant to can come back and act as the verifier. The transaction is proven to have existed because of your signature validating its existence at the previous point in time. This then creates a new form of trust that validates the transaction path of a coin from when it left the original blockchain and when it was brought back. By going through the path that the coin took and verifying that all of the transactions were valid, it verifies that the asset is valid and it is brought back to the bitcoin blockchain.

This is a system where there is a root parent blockchain. Right now we have a linear where another follows another that follows that forms a chain of blocks. Now this proposal is saying that miners can work on different parts of the block and everyone is contributing  at random. So we have this huge tree structure. At the first level down you would have two branches – left (0) and right (1) – and you could only mine one of them. The mining difficulty is 1/2 of that at the top level. Let’s go one more level down. We are now at 4 branches- left left(0-0), left right(0-1), right left(1-0), and right right(1-1) – each with a difficulty 1/4 of that at the top level. Now the levels we can go down are unlimited, and the difficulties get lower and lower. There is a distribution within the data structure as opposed to a distribution of nodes in pools. Not all branches need to be verified right away, just recorded. When is a transaction confirmed? It is not absolute. The transaction publisher doesn’t move value from one block to another, the miner comes back to the transaction and the mining mechanism now can be specialized to recording without verifying and announcing. In theory, you could solo mine a branch that is 40 levels down with a 336MH/S USB Stick miner. So what is this effectively doing and why does it secure the mining? The miner is basically publishing the transaction and the validation can be retrieved in a merkel tree. A merkel tree is simply describing a path of coins as they changed hands in a way that you can validate the data structure that is a map of who held the asset. So what does this all lead to? You can let miners work on different parts of the block simultaneously and effectively determine if it has a valid transaction history.

In conclusion, these proposal are ways to augment the protocols ability to tackle the problems of scalability, fluid interchangeability, security, decentralization, scripting, and unification all in different ways. Whether its Ethereum creating their own new blockchain, Counterparty creating tokenized assets, sidechains creating a two way peg, treechains specializing the mining process; it comes down to making something that works but doesn’t completely compromise the existing Bitcoin network. It is now about making the most effective way to create a scalable internetwork of p2p, b2b, m2m decentralized asset ledgers.

 

 

Decentralized Asset Exchanges

The next layer on top of the Bitcoin protocol is real time asset distribution information, consensus , and public ledger. Stocks, bonds, real-estate, escrow, microloans, gambling, crowdfunding and P2P contracts will be executed on decentralized networks. This has been referred to as colored coins or designated digital “contracts” by a new protocol named Ethereum. Ethereum is a platform, a scripting language, and ultimately a new decentralized system for developers around the world to build with. This can be any sort of deal, contract, exchange that can be mathematically expressed in code. It enables the parties to set the terms in a publicly verifiable and protected transaction. This can revolutionize the way the internet of money serves as self evident. There is an even greater application that will emerge from these types of systems. This is the DAO, or Decentralized Autonomous Organization.

Imagine a corporation 20 years from now that is completely automated, checked and balanced in its management by computer code, providing a service that is globally accessible. This is the DAO. An organization that relies on the network and the programmers pivoting with hacks that maximize the user experience and delegate operations more efficiently to the computer system. Developers around the world can instill Artificial Intelligence into a publicly traded corporation, a voting system, or even a manufacturing facility.  The open source system will enable people to effectively build an organization with code, set it in motion, and delegate operations to machines and data servers around the world.

The value in a decentralized distributed system such as Ethereum is that anyone with an apparatus verifying contracts is now an additional node on network. Marc Andreesen of Andreesen Horowitz predicted that chip manufactures will soon start building chips that can support an OS and mine. An ever growing network of nodes, in every electronic device, verifying contracts between two people or within autonomous organizations. It is truly empowering to acquire the skills to build on a platform like Ethereum. It is an essential technological intermediate for what decentralized protocols like Bitcoin will enable in the future.

For more information about Etheruem you can read the white paper here.

Colored Coins video