Ethereum and Solidity Smart Contracts

Definitions

Turing-Complete
theoretically capable of expressing all tasks accomplishable by computers - sequences, selections, and iterations
Addresses
20 byte values. Every account and smart contract on the Ethereum blockchain has an address and can send and receive Ether to and from this address
Wallet
An application that contains public and private keys
Transaction
A signed message from an external account, shared over the network, and mined
Nonce
Used for one occasion. A scalar that is an up to date count of the number of mined transactions originated from an account
Node (or Peer)
A computer on a peer-to-peer network
Peer-to-Peer Network
Computers directly connected to each other without a central server
Deterministic
Always having the same predictable output from given input/s
Hash (Hash function)
A hash function takes any string and creates a fixed size output. The attributes of such a function would be deterministic, efficient, collision free, and difficult to deconstruct. There are collisions, but they are not detectable. To generate radom text, 2130, 99.8 will be collision free

Overview

Ethereum is like a network acting like a single machine. Each machine on the network (node) shares the exact state as other nodes. This exact state is the Ethereum Blockchain. The network is the single computing instance ‘world computer’. The programs that run on this world computer are called contracts. The ledger is the list of transactions. All this is done in the Ethereum virtual machine, peer-to-peer network.

Solidity is the language used to program Ethereum contracts. These scripts exist in the Ethereum Blockchain at an Address.

You can create your own private Ethereum blockchain. As it would be private you don’t need mining as there is inherent trust.

Accounts and Addresses

First, install Metamask and get some Eth from a faucet. Then check the status. You now should have an account and some Eth. Great.

Your new account is called an EOA or Externally Owned Account (or Wallet). There is another type of account, called a Contract Account.

You can also create your own keypair address:

openssl ecparam -name secp256k1 -genkey -noout | openssl ec -text -noout

Transactions

Everything on a blockchain is a transaction. A transaction is a change of state. Transactions take time and energy, so they are paid using 'gas'. Viewing a transaction is not a transaction therefore does not cost any gas. The gas pays the miners for mining, as they do the hard work validating transactions. As energy is involved (cost) Ethereum has a currency called Eth. This value can be sent to a contract address or from person to person.

These transactions are signed messages transmitted by the Ethereum network, then mined (recorded) on the blockchain.

A transaction can have value and/or data or nothing. So value would be a payment, like you sending me 1 ETH. A data payload to a smart contract contains serialised hex encoding of a function name and parameters.

Digital signature

The essence of a digital signature is:

  1. you have a public and private key
  2. you have a message/document that needs signing
  3. you hash the document, and hash that using your private key
  4. the signature can be verified by using your public key to decrypt the hash, and the result will equal a hash of message/document

How this works in Ethereum is the message in the transaction is hashed using your private key, and sent along with the message.

Smart contracts

A Smart Contract is a program that executes predefined actions when specific conditions are met. Most contracts are written in Solidity and compiled into assembly.

A smart contract is created by sending a transaction with an empty 'to' field.

Solidity development

Install:
nom install -g truffle ganache-cli
Run:
ganache-cli
In another terminal run:
truffle develop
web3.eth.accounts //list accounts
web3.eth.coinbase // should be the same as the first account
web3.eth.getBalance(web3.eth.coinbase) // shows the ETH as WEI in BigNumber format

Definitions

BigNumber -

Writing Solidity

To check the validity of something, like assert:

require([boolean conditions])

JSON interface AKA ABI

Parity

https://medium.com/@preitsma/setting-up-a-parity-ethereum-node-in-docker-and-connect-safely-f881faa17686

https://wiki.parity.io/Configuring-Parity

Forks

https://vitalik.ca/general/2017/03/14/forks_and_markets.html

https://www.coindesk.com/short-guide-bitcoin-forks-explained/

Consensus algorithms

Proof of Elapsed Time (PoET) - Consensus algorithm used by Hyperledger Sawtooth that utilizes a lottery function in which the node with the shortest wait time creates the next block.

Proof of Stake (PoS) - Consensus algorithm where nodes are randomly selected to validate blocks, and the probability of this random selection depends on the amount of stake held.

Proof of Work (PoW) - Consensus algorithm first utilized by Bitcoin that involves solving a computational challenging puzzle in order to create a new block.

  • Overview

  • Use parity-solo instead of rinkeby/geth on dev

  • Make hub pick up contract address from file (see vodacoin-app)

  • Deploy contract using inventrust-truffle docker container (see tests sections in website-logic Jenkinsfile)

  • Write contract address to file during restart (see vodacoin-network Jenkinsfile)
    It might make sense to set up a separate staging environment (on Rinkeby) in the future.

let tokenRegistryAddress = process.env.TOKEN_REGISTRY_ADDRESS
if (tokenRegistryAddress === undefined) {
tokenRegistryAddress = fs.readFileSync('token_registry_address.txt').toString().trim()
}
logger.info('Token registry address', tokenRegistryAddress)

Solidity and Truffle

Start by installing and running testrpc.

Run Ganache

truffle compile
truffle test

ethereumjs-testrpc

modifier modifierName([params]) {
 // ok or error
}

function functionName() [visibilitySpecifier] [modifiers] [returns (values)] { //logic }

A library and a smart contract.

DAO - contract structure

DApps

New economies such as steemit

rpc or ipc

there are no null values in solidity
large numbers better stored as string

storage types:

  • storage (in closure)
  • locks

locks cost less gas

Example: Charity

Use case:

I want to donate to charity. How do I know it gets delivered and put to good use?

As a charity I want to register
As an organiser I want to remove charities?

As a user I want to donate

As a charity I want to request coins

Blockchain is a combination of 3 existing technologies:

  • peer-to-peer

  • cryptography

  • gamification

  • state machine - a device in a condition based on its previous condition plus the values input over time

  • genesis - the beginning

  • address creation and structure

  • mining

  • transaction composition

  • block composition

  • merkle tree

  • patricia merkle tree

  • proof of work

  • block difficulty

  • pbft practical byzantine fault tolerance

  • proof of work

  • proof of stake

tolerance is minimum number of nodes is one third for BFT

two = 50/50
three = 33
four = 3/4

a valid block has a hash that is less than a target number
repeated hashing and check against difficulty. target is 15 seconds for a block.

pow - expensive, high energy use
low transaction volume
unknown parties
public blockchain

Mine

any node on the network can declare itself as a miner and can attempt to validate a block.

pow needs mining. it is hard to mine but easy to verify.

proof of stake

stake some currency for the chance to determine a block

public and private blockchains

public
permissioned/consortium
private

Accounts

In the Ethereum blockchain the state is made up of objects called accounts.

There are two types of accounts.

20 byte stored in a merkle patricia key

Tools

Swarm
https://swarm-guide.readthedocs.io/en/latest/introduction.htm/l

IPFS
https://ipfs.io/

Web3
https://github.com/ethereum/wiki/wiki/JavaScript-API

Ganache
http://truffleframework.com/ganache/

Truffle
http://truffleframework.com/

Remix
https://remix.ethereum.org/#optimize=false&version=soljson-v0.4.24+commit.e67f0147.js

Metamask
https://metamask.io/

Parity
https://www.parity.io/

Mist
https://github.com/ethereum/mist/wiki

Development

Ganeche

https://www.npmjs.com/package/ganache-cli

Oracles

A blockchain smart contract does not currently initiate the retrieval of external data. Instead, one or more trusted parties ('oracles') must create a transaction which embeds that data in the chain. This data is often gathered and stored in a traditional database by the oracle. Any interaction between a blockchain and the outside world is restricted to regular database operations.

In other words, an oracle pushes data onto the blockchain, rather than a smart contract pulling it in. Once the oracle pushes the data, every node will have an identical copy of this data. This allows for the data to be safely used in a smart contract computation. While oracles allow for blockchain interface with external data, they undermine the goal of a decentralized system. Examine when such a trusted authority should be retained. When the trusted authority would or should be retained, efficiencies in the blockchain are not as high as in other applications.

Gamified learning

https://ethernaut.zeppelin.solutions/
https://cryptozombies.io/

Resources

-Hashing

https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI

https://blog.ethereum.org/2016/07/12/build-server-less-applications-mist/

https://medium.com/@merunasgrincalaitis/the-ultimate-end-to-end-tutorial-to-create-and-deploy-a-fully-descentralized-dapp-in-ethereum-18f0cf6d7e0e

https://www.ethereum.org/greeter

https://github.com/ethereum/mist/releases/tag/0.8.0

https://coursetro.com/posts/code/99/Interacting-with-a-Smart-Contract-through-Web3.js-(Tutorial)

https://dappsforbeginners.wordpress.com/tutorials/javascript-api-1/

http://truffleframework.com/

Byzantine Fault Tolerance Algorithm - A consensus algorithm designed to defend against failures in the system caused by forged or malicious messages. In order to be fault tolerant of a Byzantine fault, the number of nodes that must reach consensus is 2f+1 in a system containing 3f+1, where f is the number of faults in the system.

Consensus Algorithm - Refers to a system of ensuring that parties agree to a certain state of the system as the true state.

Cryptocurrency - is a digital asset that is used as a medium of exchange. A cryptocurrency is exchanged by using digital signatures to transfer ownership from one cryptographic key pair to another key pair. Since this digital asset has characteristics of money (like store of value and medium of exchange), it is generally referred to as currency. Note: It should not be confused with digital currency or virtual currency.

Cryptoeconomics - A field of study that explores the intersection of cryptography and economic incentives. While cryptography is used for ensuring network security at various levels and functions, the built-in economic incentives provided to the participating nodes in the network ensure that, at any given point, the majority of players in the network operate in a desirable way.

Cryptography - The study of the techniques used to allow secure communication between different parties, and to ensure the authenticity and immutability of the data being communicated.

Distributed Ledger - A type of data structure which resides across multiple computer devices, generally spread across locations and regions.

Key/Value Pair - It consists of two parts, one designated as a 'key', and another as a 'value'. The 'key' is an identifier that allows you to look up the 'value'. The 'value' is the data that is stored for a given 'key'.

Private/Public Keys - Private keys are used to derive a public key. While private keys remain confidential, public keys are available to everyone in the network (similar to an email address). Anything encrypted with a public key can only be decrypted using its corresponding private key, and vice versa.

State - Contains up-to-date data that represents the latest values for all keys included in the network's ledger. The state of a network encompasses all past transactions in the network, from the genesis block to the present time.

https://etherscan.io/

https://www.quora.com/How-does-Ethereum-verify-contract-execution

https://media.consensys.net/ethereum-gas-fuel-and-fees-3333e17fe1dc

https://ethgasstation.info/

https://medium.com/@preethikasireddy/how-does-ethereum-work-anyway-22d1df506369

https://ethstats.net/

Gas price spreadsheet

https://github.com/ethereum/wiki/wiki/Light-client-protocol

https://levelup.gitconnected.com/https-medium-com-zubairnahmed-react-ethereum-getting-started-with-the-minimum-toolset-required-part-1-of-4-9562efa23d18