Dapp Development Basic

Sueky Lv1

Ethereum basics

what is Ethereum?

  • From a computer science perspective: Ethereum is a deterministic but practically unbounded state machine, consisting of a globally accessible singleton state and a virtual machine that applies changes to that state.

    Function

    • allows users to create and use smart contracts and decentralized apps

    ethereum vs bitcoin

    • purpose:

      • Not only to be a digital currency payment network, but also is intended as a utility currency to pay for use of the ethereum platform as the wold computer.

        • Ethereum’s purpose is not primarily to be a digital currency payment network

          While the digital currency ether is both integral(必须的) to and necessary for the operation of Ethereum, ether is intended as a utility currency to pay for use of the Ethereum platform as the world computer.

    • programming language:

      • Ethereum uses general-purpose programming blockchain that runs a virtual machine capable of executing code
      • Bitcoin uses a very limited scripting language

Turing completeness

ethereum Simulate any Turing machine

  • ethereum can execute a stored program in a state machine(ethereum virtual machine) while 读写数据to memory ,which make it as a turing-comlete system.
  • Given the limitations of finite memory,ethereum can execute any algorithm that can be computed by any Turing machine.

“Infinite loops”

  • Ethereum can’t predict if a smart contract will terminate, or how long it will run, without actually running it (possibly running forever)
  • is Undecidable by just looking at the code
  • Result:abuse world’s resource

Gas

  • a metering(计量) mechanism, can allocate scarce resources of the network
  • As the EVM executes a smart contract, it carefully accounts for every instruction (computation, data access,etc.)
    • Each instruction has a predetermined cost in units of gas
  • the amount of gas depends on:
    • how large of a contract you are trying to execute
    • how fast you want to execute it
  • How does one get gas to pay for computation on the eth world computer?
    • Ether needs to be sent along with a transaction
    • Ether needs to be explicitly marked for the purchase of gas,along with an acceptable gas price
  • Transaction example
    • note-dapp-1
  • Gas limit
    • the maximum amount of gas you are willing to consume on a transaction
    • if you put a gas limit of 50,000 for a simple ETH transfer, the EVM would consume 21,000, and you would get back the remaining 29,000
    • if you specify too little gas, for example, a gas limit of 20,000 for a simple ETH
      transfer, the EVM will consume your 20,000 gas units attempting to fulfill the
      transaction, but it will not complete
      • The EVM then reverts any changes, but since the miner has already done 20k gas units
        worth of work, that gas is consumed
  • How to compute: Total fee = Units of gas used × (base fee + priority fee)

Ethereum 1.0 vs 2.0: PoS

Ethereum 1.0 Architecture = bitcoin

  1. combine Consensus and execution as follows:

    1. Every node assembles(组装) a block containing valid transactions (to establish validity, this peer already pre-executes those transactions);
    2. The peer tries to solve a PoW puzzle
    3. If the peer is lucky and solves the puzzle, it =disseminates the block to the network via a gossip protocol;
    4. Every peer receiving the block validates the solution to the puzzle and all transactions in the block. Effectively, every peer thereby repeats the execution of the lucky peer from its first step. Moreover, all peers execute the transactions sequentially (within one block and across blocks)
  2. Limitation: Environmental Factors:energy consumption

Pos(proof of stake)

Consensus algorithm:

  • Pow(such as bitcoin):minerslove hard, useless problems to create block
    • etc. calculating the cryptographic hash value that satisfies the threshold requirement
  • Pos
    • what?is another consensus algorithm used by blockchain networks to achieve distributed consensus and that cuts on the energy consumption of PoW
    • how?随机选择新区块,取决与以太坊上用户的财富(stake)/参与验证交易和创建新区块的节点是通过质押一定数量的以太币来获得权益的:The creator of a new block is chosen in a random way, depending on the user’s wealth locked in Ethereum, also defined as “stake”
    • 锻造or铸造而不是开采:in the PoS system, blocks are said to be ‘forged’ or ‘minted’, not mined
    • validator
      • It requires users tostake their ETH to become a validator (aka staker)
        in the network
      • Users who validate transactions and create new blocks in this system
        are referred to as forgers/validators
      • Validators are responsible for the same thing as miners in PoW
        • ordering transactions and creating new blocks so that all nodes
          can agree on the state of the network
  • Advantage:
    • 能源高效/降低硬件需求/更去中心化/分治链
      • better energy efficient
        • Do not need to use lots of energy mining blocks
      • Reduce hardware requirements
        • Do not need elite hardware to stand a chance of creating new blocks
      • Stronger immunity to centralization
        • pos lead to more nodes in the network
      • stronger support for shard chain
        • Key upgrade: scaling(缩放/拓展) the ethereum network 扩展以太坊网络

Wallet and account types

  • you do not digitally possess your money in your own local storage since your money infomation in stored in blockchain

  • Wallet:The physical storage and/or software that manages your private key and generates your signatures is called wallet in the world of blockchain

    • Software-metamask
    • Hardware-trezor
  • key

    • private key is generated randomly using ecdsa(Elliptic Curve Digital Signature Algorithm)
    • Public key derive(源于) from private key
      • dont lose it,cant recover it
    • Address= 0x+the last 160bits(20bytes) of hash(public key) using keccak256
      algorithm
      • an Ethereum address is related to the public key, which is related to your private key

    Account model in ethereum

    1. externally owned account
      1. controlled by users
      2. have private key, address derived from pk ,bitcoin address
    2. Contract account
      1. Controlled by contract code only
      2. no private key
      3. It has a space to store code and state variables
      4. address: derived from its creator’s address+nonce

Smart contract and transactions

Smart contract

  • In the context of Ethereum, we define smart contracts as “immutable computer programs that run deterministically in the context of an Ethereum Virtual Machine as part of the Ethereum protocol.”
  • DApp:
    • Applications created with smart contracts and (mostly) static content are called
      Distributed Applications (DApps)
  • note-dapp-2

Creation and call

  • Anybody can create contract for a small fee, by uploading its program code in a special transaction, then the program lives on the blockchain
    • written in bytecode (or compiled from higher-level language) and executed by a EVM
    • Own balance of funds(资金余额)
  • make procedure calls through api(the program exposes),then the contract can send and receive money according to its own logic

properties

  1. Event-driven, needs to be invoked(call 调用)

    1. • Cannot run in the background
    2. • Cannot set a timer
  2. function calls can carry ether given to the contract

  3. contracts are immutable

    • Code can not be change
    • cant add new function(even the owner)
    • Mistake will stay forever?
      • Locked?
      • Can tweaks(调整):run code from state

Transaction

  • What

    • are signed messages originated by an externally owned account (EOA)

    • transmitted by the Ethereum network

    • recorded on the Ethereum blockchain

  • Function:Trigger a change of state or cause a contract to execute in the EVM.

    • If successfully change the state, the transaction will be recorded on the blockchain Ethereum blockchain.
  • how to handlle replay?

    • a transaction counter tracking how many transactions one account has sent
    • No two transaction from the same account can have the same counter value
  • Atomicity

    • Transactions execute in their entirety
      • If execution completes successfully, any changes in the global state are recorded.
      • If execution fails due to an error, all of its effects (changes in state) are rolled back as if the transaction never ran. Additionally, the ether spent on gas for the execution is deducted from the originating account.

Lecture 4

Life cycle of smart contract

  1. Written in a high-level language, such as Solidity
  2. Compiled to the low-level bytecode
  3. Deployed on the Ethereum platform using a special contract
    creation transaction, which is identified as such by being sent to the special contract creation address, namely 0x0
    • Each contract is:
      • identified by an Ethereum address, which is derived from the contract
        creation transaction as a function of the originating account and nonce
      • used in a transaction as the recipient, sending funds to the contract or calling one of the contract’s functions
  4. All smart contracts in Ethereum are executed, ultimately, because of a transaction initiated from an EOA
    • A contract can create another contract
    • A contract can call another
    • Transactions execute in their entirety, with any changes in the global state
      (contracts, accounts, etc.) recorded only if all execution terminates
      successfully
  5. A contract can be “deleted,” removing the code and its internal
    state (storage) from its address, leaving a blank account (using
    SELFDESTRUCT)
  • Any transactions sent to that account address after the contract has been
    deleted do not result in any code execution
  • Deleting a contract in this way does not remove the transaction history (past)
    of the contract, since the blockchain itself is immutable

SOLIDITY

Special function:

The receive function is similar to the fallback function, but it is designed specifically
to handle incoming ether without the need for a data call.

  • receive()
    › It executes on calls to the contract with no data (calldata), e.g., calls made
    via send() or transfer()
  • fallback()
    › always receives data, but to also receive Ether, if you mark it as payable

Lecture 6

Anything written on the blockchain cannot be changed
  • Yes.
  • The immutability of blockchain ensures that data recorded on it remains unchanged and cannot be altered or tampered with.
How about variables being updated?
  • once a variable is written to the blockchain, its value can change over time.
  • However, the historical values of the variable are still preserved on the blockchain, providing a transparent and auditable record of its changes.
How about selfdestruct?
  • allows for the deletion of a contract from the blockchain.
  • This function can be used to remove a contract and its associated data from the blockchain.
But the code cannot be changed, right?

Yes

While the code of a smart contract cannot be changed after deployment, it is possible to utilize upgradability patterns during contract development. These patterns allow for the implementation of upgradeable contracts, where the logic of the contract can be modified without altering the code itself. However, such upgradability requires careful design and planning.

  • Proxy upgradability patten
    • The basic idea is using a proxy for upgrades.
    • The first contract is a simple wrapper or “proxy” which users interact with directly and is in charge of forwarding transactions to and from the second contract, which contains the logic. The key concept to understand is that the logic contract can be replaced while the proxy, or the access point is never changed.
    • Both contracts are still immutable in the sense that their code cannot be changed, but the logic contract can simply be swapped by another contract. The wrapper can thus point to a different logic implementation and in doing so, the software is “upgraded”.
Feature! But no upgradeability
  • Cannot add a new function

  • Even the owner cannot do this

    • In terms of adding new functions to a deployed contract, Ethereum 1.0 does not support it. Once a contract is deployed, new functions cannot be added or removed. This limitation is known as lack of native upgradeability.
  • So mistakes stay forever

Ether locked forever?
  • If ether (ETH) is locked within a contract, it is typically not permanently locked. Contracts can have mechanisms built in to enable the release or transfer of the locked ether based on predefined conditions or logic within the contract code.
  • For example, a contract might have a function to withdraw funds held within it or a specified timeframe for releasing locked funds.

Dao(decentralized autonomous organization)

  • Fully autonomous organization, unlike traditional organizations
  • Not governed by a single person but is instead governed through code, supposedly protected from human intervention
    • Will operate transparently, according to the code and transaction log
  • Governance decisions/rulings are decided via DAO token voting
  • Governance token holders are tasked with stewardship of the protocol

proposing upgrades

  • Protocol upgrades in the DAO setting come through proposals in the
    form of executable code, on which governance token holders vote
  • The proposer has to hold or have been delegated a threshold number
    of governance tokens
  • For a protocol upgrade to be executed, a minimum number of votes is
    required, which is commonly called a “quorum”
  • Examples
    • Change stability fee in DAI

lecture 9

3 roles

1. client

2.peers

  • Contain endorser and committing peers

3.orderers

chaincode

Chaincode, in the context of blockchain technology, particularly in systems like Hyperledger Fabric, is essentially the term used for the “smart contracts” that run on the network nodes. It plays a crucial role in blockchain networks by defining the business logic and rules that govern transactions.

  1. Application-Level Code: Chaincode is a set of application-level instructions or code that is stored on the blockchain ledger as part of a transaction. This code defines how transaction data is to be handled and processed.
  2. Modifying World State: When chaincode runs, it can execute transactions that modify the world state, which is a record of the current state of all assets or data managed by the blockchain.
    • Transaction Logic as a Contract: The logic of a transaction is written as a contract using programming languages like Go, Java, or JavaScript. This contract, or chaincode, is then executed within secure containers to maintain the integrity and security of the blockchain.
  3. Data Transformation: The transaction, as dictated by the chaincode, transforms data. This transformation is scoped by the contract on the channel from which it operates, meaning that the chaincode’s effect is confined to a specific context or domain within the blockchain network.
  4. Installation on Peers: The chaincode is installed on peers (nodes) in the blockchain network. These peers need access to the asset states (the world state) to perform read and write operations as defined by the chaincode.
  5. Instantiation on Channels: Once installed, the chaincode is instantiated on specific channels and peers. A channel in blockchain networks like Hyperledger Fabric represents a private “subnet” of communication between specific members of the network, providing a way to segregate transactions and data for privacy and security.
  6. Sharing within a Channel: Within a channel, the chaincode can be shared across all peers or with a specific subset of peers. This allows for flexible and controlled deployment of business logic, depending on the needs and permissions of different network participants.

channel

  1. Function of a Channel:

    • A network channel connects various components of a blockchain network: the application, smart contract (chaincode), ledger, peer, and ordering service.
    • It creates a domain-specific network that these components use, tailored to specific business concerns or applications.
  2. Domain-Specific Networks:

    • Channels are used to segregate different types of business applications within the same blockchain network.
    • Examples include separate channels for trade finance, food provenance, or international payments. Each of these channels would have its own unique network configurations and rules.
  3. Multiple Channels in Hyperledger Fabric:

    • Hyperledger Fabric supports multiple channels, allowing it to function as a “network of networks.”
    • This multi-channel support enables diverse and complex business networks to coexist within the same overarching blockchain infrastructure.
  4. Peer Participation in Multiple Channels:

    • A single peer in Hyperledger Fabric can be part of different channels, each with its own ledger and set of smart contracts.
    • This allows for versatile interactions across various domains and networks simultaneously.
  5. Privacy and Security:

    • Channels ensure privacy and security by segregating transactions and ledger states.
    • Since peers exchange messages using consensus through channels, this structure maintains privacy between different ledgers.
      • Each channel is a separate blockchain
  6. Characteristics of Channels:

    • Not all nodes in the network are required to connect to every channel.
    • Peers connect to channels based on an access control policy, which governs participation and visibility.
    • The ordering service is responsible for ordering transactions that are broadcast to a channel.
    • Peers in a channel receive transactions in the exact same order, ensuring consistency and reliability.
    • Transactions are delivered in cryptographically linked blocks to maintain the integrity and security of the blockchain.
    • Every peer connected to a channel validates the blocks delivered specifically for that channel (channel-specific delivered blocks)and then commits them to the ledger.

Transcation Recording in Fabric Blockchain

  1. Client A1 submits a transaction proposal to its endorser
  2. Endorser P1 executes PTx1 and endorses it. The endorsed transaction, Tx1, is returned to A1.
  3. A1 submits the endorsed transaction Tx1 to the orderer,P4.
  4. P4 groups endorsed transactions sequentially into a block, and sends it to ALL peer nodes
  5. Each peer validates the newly received block, and updates its ledger accordingly.

Reference

  • POLYU COMP5566
  • Title: Dapp Development Basic
  • Author: Sueky
  • Created at : 2023-12-14 18:01:30
  • Updated at : 2024-03-23 18:07:45
  • Link: https://stephaniesuu.github.io/2023/12/14/Dapp-Development-Basic/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments