Skip to main content

Basic stuff to know about Blockchain and Smart Contracts in Ethereum

I could guess if you are here reading this blog, it's because you want to win some money with the popular cryptocurrencies and blockchain. But, wait, the first thing that you need to learn is to be very patient, as everything in this life, nothing is simple and easy, you need to work hard and persistent, then, you will see the fruits.

So, let's start defining very simple concepts on this huge topic:

Currency: The traditional currency exchanges currencies for something else, but it requires trusted third party, example: bank, credit card company, etc

Cryptocurrency: It is a digital currency

Hash: It is a mathematical function that only works one way; it is easy to calculate but difficult to reverse (transform data using ASCII)

Blockchain (blocks of data):

  • Introduced in 2008 by Satoshi Nakamoto
  • It has been able to solve all the major problems of distributed processing (more than one computer is used to run an application)
  • It helps to exchange things of value without a trusted third party, eliminating middlemen, with efficiency, resilience and transparency
  • The blockchain only allows create (add) and read data (once you add data in the chain, you can NOT delete it)
  • The genesis block, or block 0, is the first block in the blockchain
  • Each block is linked by storing the previous block's hash (if data in any block is changed, it changes its hash, thus breaking the link to each block after it)
  • The body of each block contains the transactions

Blockchain immutability: The data is stored on multiple nodes (devices), each node store an identical copy of the blockchain, the nodes compare their copies of the blockchain and can tell if anything has changed (they must agree before anything is changed on the blockchain).

Nonce: It is a value added to the block data to create a new hash (it is a number used only once), coupled with block data creates a new hash value, but finding the nonce is difficult to calculate (to meet complexity requirements takes a lot of computational power and energy).

Mining: The process of finding the right Nonce (very resource-intensive, lots of energy and electricity). Multiple miners or nodes compete at the same time to be first in adding this new block to the chain to get paid a reward for it.

Blockchain consensus: No nodes have more authority than another, they use consensus to agree to add blocks to the blockchain, and the consensus is achieved when more than half the nodes agree. Some examples of types are:

  • Proof of work (PoW): Nodes compete to solve mathematical puzzle (resource intensive).
  • Proof of Stake (PoS): Each node submits a bet, selection is randomized (less computing power, richest node does not always win).
  •  Delegated Proof of Stake (DPoS): Modified PoS with other nodes voted in for fairness
  • Delegated Byzantine Fault Tolerance (dBFT): Nodes select a delegate, delegate speaker chosen at random, 2/3 of delegates must agree with hash

Full nodes: Download entire copies of the blockchain

Lightweight nodes: Only download most recent blocks

Bitcoin and Ethereum are both implementations of blockchain technology, but Ethereum came out with native cryptocurrency and smart contracts, with allowed for much more autonomy.

Smart contracts: they create rules that must be followed by every node in order to access the blockchain, they have to run in a special environment called the Ethereum Virtual Machine (code that runs on the EVM)  and they are deterministic (output on every node is the same ensuring consistency of the blockchain).

Crypto wallets: It is a device, physical medium, program or a service which stores the public and/or private keys for cryptocurrency transactions (examples: MyEtherWallet, Exodus, Metamask, Coinomi, Trezor, Keepkey).

Comparing Blockchain and Database Storage

  • Databases tend to have better options when it comes to control, data format (blockchain is free format), updating data (blockchain add or read only), optimizing performance (blockchain is slower), confidentiality (in blockchain normally the data is public) and paying for storage (blockchain pays for access)
  • Blockchain excels when it comes to transparency (normally, you can see everything), integrity (we trust in the consensus algorithms) and resilience (all the nodes run/have the same data). 
 
Be sure Blockchain technology fits very well in your solution (it does not mean because it is popular nowadays, you have to use it). Normally, it could be great for enhancing auditability and compliance.

 

Building an Ethereum Blockchain App 

dApps: Decentralized applications, the end result of all the smart contract code you write. They have automatic history tracking, built-in tolerance, and you can trust the data because all nodes on the blockchain are deterministic.

Mainnet: It is the term used to describe when a blockchain protocol is fully developed and deployed, meaning that cryptocurrency transactions are being broadcasted, verified, and recorded on a distributed ledger technology (blockchain):

  • Uses real money
  • More miners and nodes
  • Unexpected delays
  • Unexpected transaction orders (miners may favor higher paying transactions)
  • Must have an account with real ETH before deploying
  • All changes to the blockchain are immutable

Gas: It is the cryptocurrency cost of accessing the Ethreum blockchain, it incentivizes people to store local blockchain copies and mine blocks, limits reduce denial of service (DoS) attacks and incentivize developers to create efficient smart contract code.

    Gas price: It is the highest price per unit of gas a transaction originator is willing to pay (like price per gallon of gas in the real world). Miners (usually) choose most lucrative transactions. Higher gas price usually mean more complex and longer to mine.

    Gas limit:  It is the total number of gas units a transaction originator is willing to pay (like total gallons of gas). It depends on complexity of algorithm.

    Gas cost: Every operation in Solidity has a gas cost or cost per operation (add operation costs 3 gas units, multiply costs 5 gas units)

    Transaction fees: fee to access to the blockchain, total cost for computations in a transaction (transaction fee = total gas cost * gas price)

    Unused gas = gas budget - gas used (goes back to transaction originator's account)

    Note: if during the transaction computing it identify an error, you could create an infinity loop to run out of gas and be bumped back to you and then you can go fix it (protection mechanism). Try to avoid as many of those operations that cost gas as possible.

Local simulated blockchain:

  • Deploy a local blockchain environment (examples: Ganache (you could disable AUTOMINE to simulate a realistic environment), Truffle, Cliquebait, Local Ethereum Network)
  • Go Ethereum (Geth) is a full Ethereum blockchain node; you can access the complete blockchain, run the EVM, mide ether, create transactions and smart contracts, and examine blocks (geth --syncmode "light")
  • Used for development and testing
  • Never deploy to mainnet without testing
  • Same as traditional development (write and test codde in safe, simulated environment)
  • IDEA (example: EthFiddle
  • Development and testing framework: Truffle, Solidity, Remix, Populus, Embark
Public Test Blockchains:
  • Shared with other users
  • Don't have to pay real money or gas
  • Examples: 
    • Infura
    • Ropsten:
      • PoW (Proof of Work) consensus algorithm
      • Miners earn small amount of ETH
      • New blocks added every ~30s
      • Supported by Geth and Parity
      • Good for observing the effect of mining on smart contracts
      • Request fake ETH here or here
    • Rinkeby:
      • PoA (Proof of Authority) consensus algorithm
      • New blocks added every ~15s
      • ETH is pre-mined
      • Supported by Geth (not Parity
    • Kovan:
      •  PoA (Proof of Authority) consensus algorithm
      •  New blocks added every ~4s
      • Supported by Parity (not Geth)

Ethereum tokens: They are basically smart contracts that define a set of standards to manage cryptocurrency. These standards are important because, in order for people to buy, sell, and trade the tokens, they must be compatible with a cryptocurrency wallet (like a physical currency). The ERC-20 token standard is the most popular in Ethereum.

Let's build an example using a real word supply chain using Ethereum blockchain app: Write 2 smart contracts: one to define a token for payment and another for asset tracking and management:

1) Supply chain smart contract: The 4 functions you may need: 

  • Creating new participants (username, password, etc) and updating them
  • Adding new products (model #, part #, etc) and updating them
  • Transferring product ownership (product ID, transaction time, etc)
  • Tracking products or assets

2) Token smart contract: It will use the ERC-20 compliant Ethereum token or EIP (Ethreun Improvement Proposal)

  • Data items: totSupply (total # of tokens in circulation), name, decimals, symbol (short identifier), balances (current balance of each participating account, mapped to the account's address), and allowed (# of tokens authorized to transfer between accounts, mapped to sender's address)
  • Functions: totalSupply(), balanceOf(), allowance(), transfer(), transferFrom(), and approve()

Solidity: It is the most popular Ethereum programming language (similar to JavaScript), Solidity smart contracts run on all nodes via the EVM and control access to the blockchain. It includes the compiler version, comments, imported files and the actual code (functions of the contract). For more examples here.

    Type of variables:

  1. Local: These are not stored between smart contract executions
  2. State: These are stored in the blockchain and are persistent, but you have to pay money to store them

    Type of memory:  

  1. Stack: Simple variables (like an integer), these lives in local memory in the EVM
  2. Memory: For more complex data/structure and it lives in other local (EVM) memory (not the stack)
  3. Storage: data which costs money to store on the actual blockchain

    Type of data:

  1. unit: Stored non-negative integers (256 bits), good for counting. To avoid paying a lot, you could use "unit8", which only stores up to 8 bits in length
  2. int: Integer, unsigned - 0 or greater, it can store negatives
  3. bool: Boolean (true or false)
  4. address: Ethereum account address, "msg.sender" is the owner of the smart contract
  5. bytes32: Allows to store arrays of data of any type, you can store strings because it is easy to manipulate
  6. String: It is an array of characters

    Visibility:

  1. public: It means anyone can invoke it or access it from anywhere
  2. external: It means only external entities can invoke
  3. internal: Functions and variables can only be invoked and accessed from within smart contracts (or any contracts derived from the smart contract)
  4. private: it means can only be invoked from within the current smart contract (not from the outside or any derived contract)

    view: Tells the compiler that the function will only reference local variables (i am not touching the blockchain, to save gas)

    Handling errors:

  • First, use require() wherever you can to avoid running into errors
  • If you encounter errors, use revert() to stop the transaction and refund gas
  • Just in case everything goes wrong, use assert()

Common Security Mistakes:

  • Avoid generating random numbers
  • Update state data before transferring control to another function, which will help with re-entrancy issues
  • Test boundary conditions to avoid overflow and underflow issues
  • Avoid using the delegate-call function, which allows one smart contract to execute a function from another smart contract.

Testing Code Operations:

  • Overflows and underflows: check that numbers are not larger or smaller than allowed
  • Valid return values: check that each function returns the correct values for caller
  • Boundary conditions: Code can handle data that meets or exceeds expected limits
  • Iteration limits: test that each loop iterates correctly
  • Input and output data formats: data provided in unexpected format can still be handled
  • Input and output data validation: invalid characters are sanitized or rejected

Notes: 

  • Be sure to test your code thoroughly before deploying; bugs will be there forever.
  • It's OK to take longer writing test cases than the function itself, its the right way to do it


Source code:

https://github.com/sergioalberto/ethereum-lab

References:


Popular posts from this blog

ISTQB - Foundation Level Agile Tester Recap

ISTQB - Foundation Level Agile Tester Recap This is a summary that will help you to approve the Agile Tester certification test. 1 - Agile Software Development 1.1 - The fundamentals of Agile Software Development  The Agile Manifesto has 4 values : - Individuals and interactions over processes and tools (people-centered) - Working software over big documentations (time to market advantage) - Customer collaboration over contract negotiation (customer requirements) - Responding to change over following plan (change is more important)   The Agile Manifesto has 12 principles : - Satisfy the customer with continuous delivery - Changing requirements - Deliver software frequently (few weeks or months) - Business people and developer must work together - Build projects around motivated individuals - Face to face conversation - Working software is the primary measure of progress - The team should maintain a constant pace indefinitely - Technical excellence and good design - Simplic

RasPI Assistant: Google Assistant + Dialogflow + Raspberry Pi

Would you like to control the TV using your voice without spend a lot of money? ... Amazing right?. So, in this post, I will teach you how to do that and more. Some of my dreams always have been control things without touch them, for example: the television, due to tired to raise the hand to change the channel. So ... let's create a device that can do this action automatically. What things will we need? First, I should understand the problem and be aware about it. For example: if we want to control a TV that is not smart, how will we do that? ... a possibility is to send infrared signals (IR) to transmit the events that the person's desire. Also, if I want that the device can hear me, I may need a microphone. Additionally, it should have a speaker to talk with the people. Further, I will need a database to save all the information, APIs that can help me with the smart logic and cheap electronic components like a Raspberry Pi , resistors, leds, wires an

How to create a simple Chatbot?

Developing an amazing Chatbot ... What is a Chatbot? First to understand how it works, you need to know how it was originated and some algorithms  like  the Natural Language Processing (NLP). It is another AI area, but it is around the language (usually written), it is the component that bridges the gap between human conversation and understanding programmed by a computer. NLP allows the computer to interpret the vast and complicated human language, understand it, process it, and effectively "speak", just like humans. Through the process, the machine has to understand all the jargon that is being using and developing or adapting with the ability to respond, as a human computer. NLP has to do with the creation of systems that process or "understand" the language to perform certain tasks, such as answering questions, analyzing the sentiment in a sentence, making translations between different languages, and another. In the past, the NLP involved a lot