Blockchain Unit-4 Notes

unit4

Ethereum

  • It is a whole network, with its own internet browser, coding language and payment system.
  • It enables users to create decentralized application on Ethereum blockchain.
  • It is an open-source, blockchain-based, decentralized software platform used for its own Cryptocurrency (ether)
  • It enables smart contracts and distributed application (DApps) to be built and run without any downtime, fraud, interference from third party.

4.1. Ethereum network

  • Ethstats.net is a dashboard of live statistics of the Ethereum network. This dashboard displays important information like current block, hash difficulty, gas price and gas spending etc.
  • EtherNodes.com displays current and historical data on node count and other information on both Ethereum main net and modern TestNet.
  • Ethereum network Step:
    1. All the nodes in Ethereum network & transaction get updated in the ledger
    2. We hit in button corresponding to the item that we want & record of that get updated in the Ethereum network & ledger.
    3. The item comes out & we collect it and this get recorded by all the nodes and the ledger.

    MainNet the main Ethereum network

    • https://ethereum.org site provide statistics for public Ethereum network.
    • The ETH carries real value of the ether on the MainNet. As the size of MainNet grows, we need to compute storage power to validate the blocks on the MainNet.

    TestNet the test Ethereum network

    The ether on the TestNet does not carry any real value and is only for collaborative testing on the network.

    Private Network

    Network is private if the nodes are not connected to the main network. If you supply own custom network ID which is different than the main network, it mean your nodes will not connected to other nodes and form a private network.

4.2. EVM

    EVM architecture

  • EVM has a stack-based architecture. A stack machine is a computer that uses a last-in, first-out stack to hold temporary values. The size of each stack in the EVM is 256-bit, maximum size is 1024 bit.
  • EVM also have own memory, non-volatile storage and maintained as part of the system state.
  • EVM stores program code separately in a virtual ROM that can only access via special instructions.
  • EVM also has its own language "EVM byte code". EVM byte code means as a programmer we write smart contract for operate Ethereum, we use high level language solidity. When we compile that solidity code EVM byte code generate that the EVM can understand.
  • EVM exe0cuter transaction recursively, computing the system state and machine state for each loop
  • The machine state is containing gas availability, program counter, and stack contents.

4.3. Transaction fee

    Three types of Transaction in Ethereum:
  • Transfer Transaction:
    Transfer ether balances from one account to another without the usage of the interpreter.Also known as external transaction.
  • Message-call Transaction:
    It contain data payload(additional data) which is used an input to execute smart contracts published on the Ethereum Blockchain.
  • Contract creation transaction:
    It is publish new smart contracts onto the Ethereum blockchain,Also know as internal transaction.
  • Transaction Fees are calculated by:
    Transaction Fee = gas usage * gas price (in wei)

4.4. Mist

  • In order to communication in Ethereum blockchain we require client
  • Client is responsible for broadcasting transactions, mining, signing message and communicating with smart contracts.
  • The most popular client for Ethereum is Geth and parity. Both come as command line tool with terminal. So most of the people not comfortable using command line tools.
  • The mist is created for client extensions. Mist binds the functionality of client in a user friendly interface.
  • Mist is a program which connects together in the background and also serves as an interface for the wallet.

4.5. Ether, gas

  • In Ethereum has two native “tokens”, Ether and Gas
  • Ether is a currency
  • Gas is commodity (product) like oil.
  • Ether:

  • It is one type of Cryptocurrency. In order to support the Ethereum network, developers need the Cryptocurrency, so ether is create and run applications.
  • It is used to pay for transaction fees and services.
  • Users can send ether to other user and developers can write smart contracts that receive, hold and send ether.
  • Ether comes existence by the validations of transactions on the Ethereum platform, through a process called mining.
  • Those performing validation are referred to as “miners”. When miners verify a group of transactions they are awarded ether.
  • Gas:

  • Gas is a unit that measures the amount of computational effort that it will take execute certain operations.
  • The gas is fuel of the Ethereum network which is used conduct transactions, execute smart contracts and launch DApps as well as pay data storage.
  • Transaction fee for authored transaction id a product of the amount of gas and bided gas price i.e. Transaction fee= amount of gas * gas price
  • Valid transaction that have leftover gas will be refunded to transaction author.
  • The gas has two components: Limit and Price.

4.6. Solidity - Smart contracts

    Solidity:Solidity is an object-oriented programming language for writing smart contracts. It is used for implementing smart contracts on various blockchain platforms, Ethereum.

    Smart Contract:Smart contracts help you exchange money, property, shares, or anything of value in a transparent, conflict-free way while avoiding the services of a middleman. They showed the world how the blockchain can grow from a simple payment mechanism to something far more meaningful and powerful. Smart contracts are automated contracts. They are self-executing with specific instructions written in its code which get executed when certain conditions are made. Smart contracts are how things get done in the Ethereum ecosystem(network). When someone wants to get a particular task done in Ethereum they initiate a smart contract with one or more people. Every single transaction that you are doing, the smart contracts will get recorded and updated by the network. It keeps everyone involved with the contract responsible for their actions.

    Smart contracts are implemented by using SOLIDITY Programming Language. Solidity is a programming language, smart contracts are series of instructions that write in 'solidity'. Language is set of instruction if the first set of instructions are done then execute the next instruction and after that the next and keep on repeating until you reach the end of the contract. Each and every step that you take acts like a trigger for the next step to execute itself like a vending machine.

    Some important point of solidity language.
  • Solidity is a typed language; the type of each variable (state and local) needs to be specified at compile-time. Solidity provides several elementary types which can be combined to form complex types.
  • Solidity is a contract-oriented, high-level language for implementing smart contracts. It was partially by C++, Python and JavaScript and is designed to target the Ethereum Virtual Machine (EVM).
  • Solidity supports inheritance, libraries and complex user-defined types among other features.
    1. Structure of solidity Program :A Solidity source files can contain any number of contract definitions, import directives and pragma directives. pragma contract {>=0.4.0}
      • Pragma: The first line is a pragma directive which tells that the source code is written for Solidity version 0.4.0 or anything newer that does not break functionality up to, but not including, version 0.6.9. You also write this but it specific compile Pragma solidity ^0.4.0;
      • Contract: A Solidity contract is a collection of code like function and data that resides at a specific address on the Ethereum blockchain.
      • Importing Files: The following statement imports all global symbols from "filename". import "filename";
      • Variable declaration: Variables are the names you give to computer memory locations
      • Mapping: Mapping is a reference type as arrays and structs.
      • Constructor: is a special kind of function. It uses to initialize the variables, data.
      • Function: Functions are the executable units of code within a contract.
      • Function modifiers: can be used to amend the semantics of functions in a declarative Function Modifiers are used to modify the behavior of a function.
    2. Comment: // This is a comment. It is similar to comments in C++
      /* * This is a multi-line comment in solidity * It is very similar to comments in C Programming */
    3. Reserved Keywords: Following are the reserved keywords in Solidity
    4. After alias apply auto byte case copyof default
      defined Final implements in inline let macro match
      mutable Null of partial promise reference relocatable
      sealed Sizeof static supports switch typedef typeof
      var
    5. Data Type: Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.
      Data Type used in Solidity: bool, integer (int8-int256/uint8-uint256), address, bytes, string, hex, enum .
    6. Variable: Variables are the names you give to computer memory locations which are used to store values in a computer program. Solidity supports three types of variables.
      • State Variables -Variables whose values are permanently stored in a contract storage. That declared into contract.
      • Local Variables -Variables whose values are present till function is executing. That declared inside a function.
      • Global Variables -Special variables exists in the global namespace used to get information about the blockchain.
        This are specific variables that are exist in global workplace. Scope of local variables is limited to function in which they are defined but State variables can have three types of scopes with names public ,private, internal.
        e.g. uint public x = 40;
    7. Operators: Solidity supports the following types of operators.
      • Arithmetic Operators: +, -, *, / , %, ++, --
      • Comparison Operators: ==, , <=, >=,! =
      • Assignment Operators: =, += ,-=, *=, /=, %=
      • Logical (or Relational) Operators:&&, ||,!
      • Assignment Operators:&, | , << , >>, ~, ^, >>>
      • Conditional (or ternary) Operators:?:
    8. Loops:
      • while loop :is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates.
        Syntax: while (conditional expression)
        {Statement(s) to be executed if conditional expression is true}
      • Do…while loop: The do...while loop is similar to the while loop except that the condition check happens at the end of the loop
        Syntax:do {Statement(s) to be executed ;}
        While (conditional expression);
      • For Loop: It is a iterative loop. Its contains initialization, condition, iteration statement
        Syntax: for (initialization; condition; iteration statement)
        {Statement(s) to be executed if condition is true}
    9. Decision making statement: Decision making statements such as If statement, if else statement & If else if statement same as c programming language.
    10. String: String is nothing but a sequence of characters. String literal using both double quote (") and single quote (') .
      eg: string myname = "Rajashri";
      In Solidity we can assign String literal to a byte32 type variable easily.
      byte32 myname = “Rajashri”;
      We can convert byte to string following code bytes memory
      bstr = new bytes(10);
      string message = string(bstr);
    11. Array: Arrays can have a compile-time fixed size, or they can have a dynamic size. The type of an array of fixed size k and element type T is written as T[k], and an array of dynamic size as A[].
      • Bytes and Strings as Arrays :Variables of type bytes and string are special arrays. A bytes is similar to byte [], but it is packed tightly in call data and memory. String is equal to bytes but does not allow length or index access.
      • Allocating Memory Array: Memory arrays with dynamic length can be created using the new operator. As opposed to storage arrays, it is not possible to resize memory arrays (e.g. the .push member functions are not available). You either have to calculate the required size in advance or create a new memory array or copy every element.
      • pragma solidity >=0.4.16 <0.7.0;
        contract C {
        function f(uint len) public pure
        {
        uint[] memory a = new uint[](7);
        bytes memory b = new bytes(len);
        assert(a.length == 7);
        assert(b.length == len);
        a[6] = 8;
        }
        }
    12. Array Members
      1. length: Arrays have a length member that contains their number of elements. The length of memory arrays is fixed (but dynamic, i.e. it can depend on runtime parameters) once they are created.
      2. push(x): Dynamic storage arrays and bytes (not string) have a member function called push(x) that you can use to append a given element at the end of the array. The function returns nothing.
        Syntax: x.push().t = 2 or x.push() = b.
      3. pop: Dynamic storage arrays and bytes (not string) have a member function called pop that you can use to remove an element from the end of the array. This also implicitly calls delete on the removed element.
    13. Function: Functions are the executable units of code within a contract. Function Calls can happen internally or externally and have different levels of visibility towards other contracts. Functions accept parameters and return variables to pass parameters and values between them.
      Function syntax:
      e.g. function hi() public pure returns (string memory)
      {
      return ("Hello World");
      }
    14. Cryptographic Function: Solidity provides inbuilt cryptographic functions as well. Some inbuilt function like
      • keccak256 (bytes memory): this function is useful for to computes the Keccak-256 hash of the input.
      • ripemd160 (bytes memory) returns (bytes20): this function computes compute RIPEMD-160 hash of the input the SHA-256 hash of the input.
      • sha256 (bytes memory): This function is useful to compute the SHA-256 hash of the input.
      • recrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) returns (address) : This function is useful for recover address associated with the public key from elliptic curve signature or return zero on error.
        e.g. function callKeccak256() public pure returns(bytes32 result{
        return keccak256("ABC");
        })
    15. Function modifiers: can be used to amend(alter) the semantics of functions in a declarative Function Modifiers are used to modify the behavior of a function. The function body is inserted where the special symbol "_;" appears in the definition of a modifier.
      //SPDX-License-Identifier: MIT
      pragma contract ^5.0.0
      contract Purchase {
      address public seller;
      modifier onlySeller() { // Modifier
      require( msg.sender == seller,
      "Only seller can call this."
      );
      _;
      function abort() public view onlySeller
      {
      // Modifier usage // ...
      }
      } }
    16. Contract: Contract in Solidity is similar to a Class in C++. A Contract have following properties.
      • Constructor -A special function declared with constructor keyword which will be executed once per contract and is invoked when a contract is created.
      • State Variables -Variables per Contract to store the state of the contract.
      • Functions -Functions per Contract which can modify the state variables to alter the state of a contract.
      Visibility Quantifiers
      Following are various visibility quantifiers for functions/state variables of a contract.
      • external -External functions are meant to be called by other contracts. They cannot be used for internal call. To call external function within contract this.function_name() call is required. State variables cannot be marked as external.
      • public -Public functions/ Variables can be used both externally and internally. For public state variable, Solidity automatically creates a getter function.
      • internal -Internal functions/ Variables can only be used internally or by derived contracts.
      • private -Private functions/ Variables can only be used internally and not even by derived contracts.
        E.g. public contract MyContract { // Statements }
        Contracts support inheritance like using is keyword
        Contract C is D { //statements }
    17. Mapping: Mapping is a reference type as arrays and structs. Mapping can only have type of storage and are generally used for state variables. Mapping used as public modifier. Solidity automatically creates getter for it.
      Syntax: mapping(_KeyType => _ValueType)
      • KeyType - can be any built-in types plus bytes and string. No reference type or complex objects are allowed.
      • ValueType - can be any type.
    18. Address: The address type is to use for account address specially. comes in two flavors, which are largely identical:
      • address: Holds a 20 byte value (size of an Ethereum address).
      • address payable: Same as address, but with the additional members transfer and send. The idea behind this distinction is that address payable is an address you can send Ether to, while a plain address cannot be sent Ether
        Members of Addresses
      • balance and transfer: It is possible to query the balance of an address using the property balance and to send Ether (in units of wei) to a payable address using the transfer function.
        address payable x = address(0x123);
        address myAddress = address(this);
        if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10);
      • send: Send is the low-level counterpart of transfer. If the execution fails, the current contract will not stop with an exception, but send will return false.
        recipient.send(1 ether);
      • call, delegatecall and staticcall: In order to interface with contracts that do not adhere to the ABI, or to get more direct control over the encoding, the functions call, delegatecall and staticcall are provided.
        bytes memory payload = abi.encodeWithSignature("register(string)", "MyName");
        (bool success, bytes memory returnData) = address (nameReg).call (payload);
        require(success)

4.7. Truffle

  • It is a development environment, testing framework and asset pipeline for Ethereum aiming to make life as Ethereum developer easier.
  • With truffle, we can built-in smart contract compilation, linking, deployment and management.

4.8. Web3

  • It is a collection of libraries which allow you to interact with local or remote Ethereum node, using HTTP or IPC connection.
  • It is javascript libraries interacts with Ethereum blockchain
  • It can retrieve user accounts, send transactions, and interact with smart contracts.
  • Web3.js API type:
    • Eth: Ethereum blockchain related methods
    • Net: Nodes network status
    • Personal: Account function and sending
    • Db: Get/put for local LevelDB
    • Shh: P2P messaging using whisper

4.9. Design and issue Cryptocurrency

A Cryptocurrency is a digital asset designed to work as a medium of exchange.

    Advantages of own Cryptocurrency:

  • Eliminate fraud risk
  • Lower operational cost
  • Immediate transactions
  • Security for funds
    Designing a Cryptocurrency:

  1. Choose consensus Mechanism :
    It is mechanism are the protocols that consider a particular transaction validate and add to the block.
  2. Pick a blockchain platform :
    Select blockchain platform based on consensus mechanism you have selected.
  3. Design the nodes :
    You have to decide the working and functionality of your blockchain and design the nodes accordingly.
  4. Establish Blockchain internal architecture :
    Be sure all the aspects before launch as you won't be able to change several parameters of the blockchain after it's launched and running.
  5. Integrate API's :
    Some platforms don't provide pre built APIs so make sure your does. There are several 3rd party block chain API providers like Bitcore, Gem, Colu etc.
  6. Design the interface :
    You need to make sure that the web, FTP servers and external database are of most recent and front-end and back-end programing done with the future upgrades in mind.
  7. Make your Cryptocurrency legal :
    Make sure that your Cryptocurrency is prepared and abiding by the soon to become laws of international Cryptocurrency regulations.

4.10. Mining

  • Mining is the process of record keeping done through the use of computer processing power.
  • It is a process of adding transaction records to the Ethereum public ledger called the blockchain.
  • All the transaction need to get approved by the miners. The transaction has to be verified and put inside the Ethereum blockchain. This verification process is call proof of work (PoW).
  • Three ways to mine Ethereum:
  • Pool mining

  • Mining Ethereum in a pool is the simplest and quickest way to get started.
  • In pool mining, you join forces with other individuals.
  • All the miners joining a pool agree that if one of them solves the cryptographic puzzles, rewards will be split among them according to the hashpower provided.
  • The size of the pool, measured in hashpower, determines how many blocks the group finds on average.
  • When choosing a pool, three key characteristics should be considered: pool size, minimum payout, and pool fee.
  • The pool fee specifies the share the pool administrator gets for running the pool. If a pool has higher fees than 3%, you may want to consider finding another pool.
  • Minimum payout defines the smallest amount one can withdraw from the pool. For instance, if the minimum payout is 1 ether, it can take weeks or months until you reach the required amount in reward payments and can cash out.
  • Mining alone (solo mining)

  • Mining on your own seems like an attractive alternative to pool mining, as no pool fees must be paid and rewards don't have to be shared.
  • To have a realistic chance to solve one of the cryptographic puzzles in a reasonable amount of time though, a miner needs dozens of GPUs.
  • Therefore, solo mining is mostly for professional miners, who run their own mining farms.
  • Using Cloud mining service

  • In cloud mining, you pay someone else to mine for you.
  • Instead of owning and running mining hardware yourself, you rent someone else's computing power and let them do the work for you.
  • In return, you get the mining rewards.
  • But be aware: cloud mining requires trust in the counterparty, especially when done over an online service.
  • There is no guarantee that the money paid upfront is used to run mining equipment or that there even exists such equipment.

4.11. DApps

  • Decentralized Applications
  • DApps developed application using front-end (html+css+js), back-end (solidity smart contract) programming code and server in Ethereum platform.
  • DApps are digital applications or programs run on a blockchain or P2P network of computers instead of a single computer.
  • Instead of using a centralized server or database these applications rely on the blockchain as a backend for program logic and storage.

  • Properties of DApps:
  • Open Source
  • Decentralized Consensus
  • No central point of failure

4.12. DAO

  • Digital Decentralized autonomous organization.
  • It exists as a set of contracts among people that resides on Ethereum blockchain.
  • DAO has a certain set of members or shareholders (67%majority) have the right to spend the entity's funds and modify its code.
  • The members would decide on how the organization should allocate its funds.
  • In DAO all members have equal share in the decision making and require 67% of member to agree to add or remove a member.

No comments:

Post a Comment