banner
leaf

leaf

It is better to manage the army than to manage the people. And the enemy.
follow
substack
tg_channel

Blockchain, Ethereum, and Smart Contracts

The main working principle of Ethereum is to accept transactions initiated by accounts, update their states, and then maintain that state until another transaction updates them. On Ethereum, the entire process of accepting, executing, and writing transactions is divided into two stages. The acceptance of transactions and the execution and writing of transactions to the ledger are decoupled. This decoupling is essential for decentralized and distributed architectures to effectively support the normal operation of the system.

Blockchain mainly has the following three uses:

  • Trust: Blockchain can be used to create decentralized applications, enabling data to be collectively controlled by multiple people, where none of them has the power to change or delete previous records. Even if someone manages to do so, the data they produce will not be accepted by other participants.

  • Autonomy: For applications on the blockchain, there is no single owner. Since there is no unique owner, no one can control it alone, but everyone can participate in the governance process through their actions, which helps establish a solution that cannot be manipulated or easily corrupted.

  • Disintermediation: Blockchain-based applications can eliminate intermediaries in existing processes. For example, in scenarios like vehicle registration and driver's license issuance, there is usually an intermediary role responsible for these tasks. If the process is designed based on blockchain, then this intermediary role becomes unnecessary, as once the data on the blockchain is confirmed, the driver's license will be automatically issued, and the vehicle will be automatically registered. Blockchain will usher in a new era where many businesses no longer require intermediaries for endorsement.

Cryptography is a science that transforms understandable and straightforward content into secret, hidden, and meaningless content; similarly, decryption is the reverse operation. Encryption technology helps in transmitting and storing data and cannot be easily decrypted.

In the field of computing, there are two types of encryption technologies: symmetric encryption and asymmetric encryption.

  • Symmetric encryption and decryption: Symmetric encryption refers to using the same key for both encryption and decryption. If this technology is used to exchange information, it means that many people will use the same key.

  • Asymmetric encryption and decryption: This involves using two keys during the encryption and decryption processes. Either key can be used for encryption and decryption. Information encrypted with a public key can be decrypted with a private key. Information encrypted with a private key can be decrypted with a public key. For example, Tom encrypts a message using Alice's public key and sends it to Alice, who can then decrypt it using her private key to extract the original information. In simple terms, information encrypted with Alice's public key can only be decrypted by her unique private key, which is a common application scenario for asymmetric encryption. Asymmetric encryption also has another use, which will be introduced later: digital signatures.

Hashing is the process of converting input data into a fixed-length random string (hash value), but it is impossible to reverse-engineer or identify the original data from the result; therefore, hashing is also referred to as a data fingerprint. It is nearly impossible to derive input data from its hash value, and even a slight change in the original data will produce a completely different hash value, ensuring that no one dares to tamper with the original data. Hashing has another characteristic: although the input string data may vary in length, the resulting hash value length is fixed. For example, using the SHA256 hashing algorithm, regardless of the size of the input data, it will always produce a 256-byte hash value. This is particularly useful when dealing with large amounts of data, as it consistently produces a 256-byte hash value that can be saved as evidence. Ethereum uses hashing technology in many places; it hashes each transaction, re-hashes the hash values of two transactions, and ultimately generates a root hash value for each transaction within the same block.

Another important feature of hashing is that, mathematically, two different input data will not produce the same hash value. Similarly, it is computationally and mathematically impossible to reverse-engineer the input value from the hash value.

Ethereum uses Keccak256 as its hashing algorithm.

The following screenshot shows an example of hashing. The input "Ritesh Modi" produces a hash value, as shown below:

Even a slight change to the input data[1] will produce a completely different hash value, as shown below:

[1] Here, the space between the two words has been removed. — Translator's note

Asymmetric encryption has an important application in creating and verifying digital signatures using asymmetric keys. A digital signature is similar to a handwritten signature on paper. Like a handwritten signature, a digital signature helps identify a person and ensures that information is not tampered with during transmission. Let’s use an example to understand digital signatures.

Alice intends to send a message to Tom. The question arises: how can Tom ensure that the message he receives is from Alice and that it has not been tampered with during transmission? The solution is not to send the original message/transaction; Alice first needs to obtain the hash value of the message she intends to send, then encrypt the hash value with her private key, and finally, she attaches the newly generated digital signature to the hash value and sends it to Tom. Upon receiving the message, Tom uses Alice's public key to extract the digital signature and decrypt it to find the original hash value. At the same time, he extracts the hash value from the actual message received and compares the two hash values. If the two hash values match, it indicates that the message has not been tampered with during transmission.

Digital signatures are commonly used for asset or cryptocurrency (such as Ether) owners to sign and confirm transactions.

Ether is the currency on Ethereum. Every activity on Ethereum requires the consumption of Ether as a fee, and miners who successfully produce blocks also receive Ether as a reward. Ether can be easily exchanged for fiat currency through trading platforms.

Ether uses a decimal measurement system, with its smallest unit being wei. Below are some measurement units, and more information can be found at https://github.com/ethereum/web3.js/blob/0.15.0/lib/utils/utils.js#L40.

Executing tasks on Ethereum requires consuming Ether. Since Ether is publicly traded on exchanges, its price fluctuates. When paying fees, if Ether is used directly, the cost for the same service may vary significantly due to its unstable price. In such cases, people may choose to execute transactions when the price of Ether is low. This situation is not ideal for a platform[1]. The role of gas (fuel) is to alleviate this issue; it is the current internal currency of Ethereum. By pricing in gas, users can determine the execution cost of a transaction in advance, which is the gas cost. By adopting this method, when the price of Ether skyrockets, the gas price can be appropriately lowered, and when the price of Ether plummets, the gas price can be appropriately raised. For example, using a function in a smart contract to modify a character will consume a certain amount of gas, and since the cost of gas has been predetermined, users can execute smart contracts in a regular manner.

[1] This creates a peak and valley effect, where during low prices, the execution volume is too high, causing the platform to operate beyond capacity. — Translator's note

Blockchain is an architecture that consists of multiple components, and its uniqueness lies in the functions and interactions of these components. Important components include: EVM (Ethereum Virtual Machine), miners, blocks, transactions, consensus algorithms, accounts, smart contracts, mining, Ether, and gas. In this chapter, we will introduce these components.

A blockchain network is composed of numerous nodes, some of which are mining nodes owned by miners, while others do not mine but help execute smart contracts and transactions. These nodes are collectively referred to as EVM. The various nodes in the network are interconnected and communicate with each other via a P2P protocol, using port 30303 by default.

Each node maintains an instance (copy) of the ledger that contains all the blocks on the chain. Due to the large number of mining nodes on the network, to avoid discrepancies in block data between nodes, these nodes continuously synchronize blocks to ensure consistency in ledger data.

In subsequent chapters, we will discuss ledgers, blocks, and transactions in more detail.

Smart contracts also run on the EVM. Smart contracts extend the capabilities of Ethereum by writing personalized business functions. When executed, smart contracts are part of transactions and follow the mining process mentioned earlier.

Users with accounts on the network can send messages to complete Ether transactions between accounts or send messages to invoke a function within a contract. For Ethereum, both methods are essentially transactions. When confirming transactions and changing account balances, account owners must digitally sign the transaction with their private key to verify the sender's identity. The structure of Ethereum is shown in the diagram below.

In blockchain and Ethereum, each block is connected to another block. The relationship between two blocks is one of parent and child, and it is a one-to-one relationship, thus forming a chain. Later in this chapter, we will discuss blocks, and in the next diagram, we will illustrate with three blocks (Block 1, Block 2, Block 3). Block 1 is the parent block of Block 2, and Block 2 is the parent block of Block 3. The hash value of the parent block is stored in the header of each block, establishing the parent-child relationship.

Block 2 stores the hash value of Block 1 in its header, and Block 3 stores the hash value of Block 2 in its header. So, the question arises: who is the parent block of the first block? Ethereum has a concept of a genesis block, which is the first block. This block is automatically created when the chain is first initiated. You can also think of the entire chain as starting with the genesis block (generated through the genesis.json file) as the first block.

Knowing that blocks are interconnected, you may wonder how transactions are bound to blocks. In Ethereum, transactions are stored within blocks, and executing a transaction requires consuming a certain amount of gas. Since each block has a gas limit, the total gas consumed by pending transactions cannot exceed this limit, preventing all transactions from being stored in one block. When the gas limit is reached, no other transactions can be written to this block, at which point nodes begin mining.

Once a transaction generates a hash value, it is stored in the block, and then the mining program selects the hash values of two transactions for re-hashing, producing a new hash value. Clearly, all transactions within a block will ultimately produce a unique hash value, known as the Merkle root hash, which is stored in the block header. If any transaction within the block changes, the hash value of that transaction will also change, ultimately leading to a change in the root transaction hash value. When the hash value of the block changes, since child blocks store the hash value of the parent block, the hash values of its child blocks must also change, triggering a chain reaction that requires the entire blockchain to change, thus making the immutability of the blockchain possible.

Nodes are computers that are interconnected through the P2P protocol, forming the Ethereum network.

There are two types of nodes in Ethereum:

  • EVM
  • Mining nodes

It is important to note that this classification is merely for conceptual differentiation; in most scenarios, there is no dedicated EVM; rather, all mining nodes perform the functions of the EVM.

The daily work of miners is quite similar to that of financial accountants, whose main job is to record data in financial ledgers. Similarly, the primary responsibility of miners is to write transaction data to Ethereum. The motivation behind this is the rewards they can earn; there are two types of rewards for miners: the first is the reward for writing blocks to the blockchain, and the second is the gas fees paid for transactions within the block. Generally, there are many miners on the blockchain competing with each other; however, ultimately, only one miner can win and write a block to the ledger, while other miners are not authorized to write. The determination of which miner wins is based on solving a problem. During mining, each miner faces the same problem, and miners can only solve it through their machine's computational power. The first miner to solve this problem will write the block containing the transactions to their local ledger and send the block and Nonce value[1] to other miners for confirmation. Other miners receive the block and verify whether the answer is correct; if it is, the block will be written to their local ledger. In this process, the winning miner will also receive a reward of 5 Ether. Each node maintains a copy of the Ethereum ledger, and the miners' responsibility is to synchronize data to keep their local ledgers up to date, ultimately achieving consistency among all miners' ledgers.

Miners or mining nodes have three important functions:

  • Mining or packaging transactions to produce new blocks and write them to the Ethereum ledger.
  • Sending the latest blocks to other miners and notifying them to receive them.
  • Receiving blocks from other miners and updating their local ledgers.

Mining nodes refer to those nodes that belong to miners; they, along with EVM nodes, are part of the entire network. At any given moment, miners will generate new blocks, then collect transactions from the transaction pool and package them into the newly created block. Ultimately, this block is added to the blockchain.

Next, we will explain some other concepts, such as consensus and solving problems.

[1] The answer to the problem solved. — Translator's note

For all miners on the network, the mining program is the same; they need to continuously execute mining tasks according to the rules in the program. On one hand, miners strive to compute the program to mine new blocks, while on the other hand, they are constantly listening for new transactions in the transaction pool, receiving, verifying, and forwarding blocks from other miners. As mentioned earlier, miners first create a block, then collect transactions from the transaction pool and add them to the block. Before adding, they check whether the transaction has already been written to a block by other miners; if it has, they discard it.

To receive mining rewards, miners need to add their coinbase transaction (the first transaction in a block that is the reward for mining), then generate the block header and execute the following steps:

  1. The miner grabs the hash values of two transactions, re-hashes them, and generates a new hash value. After hashing all transactions, they will obtain a unique hash value, known as the root transaction hash or Merkle root transaction hash, which will be added to the block header.

  2. The miner also needs to determine the hash value of the previous block, as it is the parent block of the current block, and this hash value must be stored in the current block header.

  3. The miner calculates the state and receipts root hash values[1] of the transactions and writes them into the block header.

  4. The Nonce and timestamp are recorded in the block header.

  5. The hash value of the entire block (including the block header and body) is generated.

  6. The mining process begins, with the miner continuously changing the Nonce value until they find a hash value that solves the problem. It is important to remember that the execution process is the same for miners on the network.

  7. Clearly, a miner will eventually find the answer to this problem, and they will send the result to other miners on the network. Other miners will first confirm whether the answer is correct; if it is, they will begin verifying each transaction, then accept the block and add it to their local ledger.

The entire mining process described above is referred to as Proof of Work (PoW) because the miner provides proof of the answer obtained through continuous computation. Additionally, there are other algorithms, such as Proof of Stake (PoS) and Proof of Authority (PoA); since Ethereum does not use these algorithms, this book will not discuss them further. The block header and its components are shown in the diagram below:

[1] Here, the state and receipts refer to two other Merkle trees. Ethereum has three Merkle trees: the transaction Merkle tree, the state Merkle tree, and the receipts Merkle tree.

Accounts are a primary component of the Ethereum system. The process of saving transactions to the ledger on Ethereum is essentially the process of interaction between accounts. There are two types of accounts on Ethereum: external accounts and contract accounts. Each account has a default balance attribute that shows the current balance of Ether in that account.

External accounts owned by users on Ethereum. In Ethereum, accounts cannot be called by name. When you create an external account on Ethereum, a pair of public and private keys is generated. The private key needs to be kept secure, while the public key serves as proof of ownership of the account. The public key is generally 256 characters long, but Ethereum only uses the first 160 characters to identify the identity.

For example, if Bob creates a new account on the Ethereum network (whether on a public or private network), he keeps the private key for himself, while the first 160 characters of the public key will become his identity identifier, allowing other accounts to send Ether or other Ethereum-based cryptocurrencies to this account.

External accounts can hold Ether but cannot execute any code. They can transact with other external accounts and can also execute transactions using functions within smart contracts.

A transaction is an agreement between a buyer and a seller, a supplier and a consumer, or a provider and a consumer to exchange assets, products, or services using currency, cryptocurrency, or other assets. Ethereum ensures the smooth execution of transactions, and the following are the three types of transactions supported on Ethereum:

  1. Sending Ether from one account to another: The receiving account can be either an external account or a contract account. The following scenarios may occur:
  • In a transaction, one external account sends Ether to another external account.
  • In a transaction, one external account sends Ether to a contract account.
  • In a transaction, one contract account sends Ether to another contract account.
  • In a transaction, one contract account sends Ether to an external account.
  1. Smart contract deployment: An external account deploys a contract on the EVM through a transaction.

  2. Using or invoking functions within a contract: If a function within a contract needs to be executed to change a state, a transaction is required; if executing the function does not change any state, no transaction is needed.

Below are some important properties related to transactions:

The From account property indicates that this account is the initiator of the transaction, sending gas or Ether. We have previously introduced the concepts of Ether and gas. The From account can be either an external account or a contract account.

The To account property refers to the account receiving Ether or other benefits; it can be either an external account or a contract account. If it is a transaction deploying a contract, the To field will be empty.

The Value account property indicates the amount of Ether transferred between accounts. The Input account property refers to the bytecode of the contract that has been deployed on the EVM after compilation. The input is also used to store information about the function calls with parameters in smart contracts. The diagram below shows where the Input field is used in a typical Ethereum transaction; note that it contains a function call with parameters.

The BlockHash account property refers to the hash value of the block to which this transaction belongs.

The BlockNumber account property refers to the block number of the block to which the transaction belongs.

The Gas account property indicates the amount of gas paid by the sender of the transaction.

The GasPrice account property indicates the gas price paid by the sender, measured in wei (the concept of wei was mentioned earlier in this chapter). Total gas consumption = gas amount * gas price.

The Hash account property refers to the hash value of the transaction.

The Nonce account property refers to the transaction number generated by the sender before the current transaction.

The TransactionIndex account property refers to the serial number of the current transaction in the block.

The Value account property refers to the amount of Ether transferred, calculated in wei.

The V, r, and s properties refer to the digital signature and transaction signature.

Below is a common transaction on Ethereum, where an external account sends Ether to another external account (note that the input field is not used here). The transaction in the screenshot transferred 2 Ether, with the value field measured in wei.

Transferring Ether between external accounts can also be implemented using the following code, based on the web3 JavaScript framework, which will be introduced later.

The diagram below shows a transaction that deployed a smart contract; note that the input field contains the bytecode compiled from the contract.

A block is an important concept in Ethereum. A block is a container for transactions, consisting of multiple transactions. Due to the gas limit of the block (which will be discussed later) and block size restrictions, the number of transactions contained in each block varies. Blocks are linked together to form a blockchain, with the exception of the first block (also known as the genesis block), which has no parent block; all other blocks have a parent block, and the hash value of the parent block is stored in the block header.

The diagram below shows the structure of a block:

Blocks have many attributes; to facilitate understanding of the key content, only some important parts are introduced below:

The Difficulty attribute indicates the computational difficulty that miners face to mine this block.

The GasLimit attribute indicates the total gas limit allowed for the block. It determines how many transactions can be included in the block.

The GasUsed attribute indicates the actual amount of gas consumed by the transactions in the block.

The Hash attribute refers to the hash value of this block.

The Nonce attribute refers to a number that is the answer to the problem.

The Miner attribute refers to the miner's account, which can be identified by the coinbase or etherbase address.

The Number attribute refers to the sequence number of this block in the blockchain.

The ParentHash attribute refers to the hash value of the parent block.

The ReceiptsRoot, stateRoot, and TransactionsRoot attributes refer to the Merkle trees mentioned in the previous mining process.

The Transactions attribute refers to an array of transactions that make up the block.

The TotalDifficulty attribute refers to the overall difficulty of the blockchain.

End-to-End Transaction#

Sam intends to send a digital asset (e.g., dollars) to Mark. First, Sam creates a transaction that includes fields such as from, to, and value, and then sends it to the Ethereum network. This transaction is not immediately written to the ledger but is temporarily stored in the transaction pool.

Mining nodes create a new block and, according to the gas limit standards, extract transactions from the transaction pool (Sam's transaction will also be extracted) and add them to the block. All miners on the network are performing the same task.

Next, miners begin competing to solve the problem, and after a period (or a few seconds), the winner (the first to solve the problem) will issue a notification claiming they have found the answer, won the race, and need to write the block to the blockchain. At the same time, the winner will add the answer to the block and send it to other miners. Upon receiving the notification, other miners will first verify the answer; once confirmed as valid, they will immediately stop their computations, receive the block containing Sam's transaction, and add it to their local ledger. Thus, a new block is generated on the chain, which will exist permanently across time and space. During this process, both parties' account balances will be updated, and finally, the block will be distributed and copied to all nodes on the network.

What is a Contract#

A contract is a legal document agreed upon by two or more parties to execute a transaction immediately or in the future. Because a contract is a legal document, it has enforceability and executability. There are many scenarios for contract applications, such as a person signing a contract with an insurance company to purchase health insurance, or a person buying a piece of land from another person, or a company selling equity to another company.

What is a Smart Contract#

A smart contract is code written according to user requirements and deployed and run on the Ethereum Virtual Machine. Smart contracts are digitalized, embedding the rules for transactions between accounts within the code. Smart contracts facilitate the transfer of digital assets through atomic transactions and can also be used to store important data, which can be used to record information, events, relationships, balances, and information that needs to be agreed upon in real-world contracts. Smart contracts are similar to object-oriented class definitions, allowing one contract to call another, just as we can call and instantiate between class objects. We can also think of smart contracts as small programs composed of functions. You can create a new contract and use functions within the contract to view data on the blockchain and update data according to certain rules.

How to Write a Smart Contract#

Peter Todd, one of the core developers of Bitcoin, summarized the current state of smart contracts, stating, "The conclusion of the discussion on smart contracts is that no one understands what smart contracts really are. If we are to implement smart contracts, we need oracles."

Indeed, clarifying the concept and essence of smart contracts is not easy.

We start with the origin of the smart contract concept. The term "smart contract" was proposed by computer scientist and cryptographer Nick Szabo around 1993. In 1994, he wrote the paper "Smart Contracts," which is considered the seminal work on smart contracts.

Nick Szabo begins his explanation of smart contracts with the example of an automatic vending machine. We can consider the original ancestor of smart contracts to be the unassuming vending machine. After potential assessments with limited losses, the vending machine ensures that the money in the cash box is far less than the cost incurred by the vandal. The vending machine charges coins based on the displayed product price, forming the initial design of computer science through a simple mechanism, and it automatically delivers products based on the amount of coins inserted. The vending machine is a transport contract: anyone with coins can transact with the supplier. Locking the cash box and other security mechanisms protect the coins and goods stored in the vending machine from being vandalized, thus supporting the deployment of vending machines in various areas and generating profits.

Based on the concept of the vending machine, Nick Szabo provides the following definition of smart contracts:

"Smart contracts transcend the category of embedding various valuable attributes in vending machines, controlling contracts digitally. Smart contracts involve properties with dynamic and frequently proactive execution attributes, providing better observation and verification points, where proactive measures must be precise."

What Nick Szabo tells us is that the essence of smart contracts is an abstract concept that serves as a recognized tool for forming relationships between individuals, institutions, and properties, a set of agreements that establish relationships and reach consensus. The terms of smart contracts (such as collateral, property division, etc.) can be embedded into processing hardware and software in such a way that the cost of breach is very high (even prohibitive). For example, a digital guarantee smart contract designed for a house continuously improves the house collateral agreement to better embed it into the processing of contract terms. According to the contract terms, these agreements will ensure that the cryptographic keys are fully controlled by the person with operational attributes, who will also rightfully own the property of the house. Simply put, to prevent theft, the user must complete the correct unlocking process; otherwise, the house will switch to an unusable state, such as disabling access control and facility failures. In traditional methods, if a house is used for mortgage repayment, a headache for creditors is the difficulty in recovering the house from defaulters, requiring frequent communication to retrieve the house keys, etc. To solve this problem, we can create a smart lien protocol: if the owner fails to pay, the smart contract invokes the lien protocol, transferring control of the house keys to the bank. This protocol may be cheaper and more effective than hiring a debt collector.

At the same time, Nick Szabo proposed three essential elements of smart contracts:

  1. A lock that allows the owner to simultaneously exclude illegal third parties;
  2. A backdoor that allows creditors secret access;
  3. The backdoor is only opened during a period of default and non-payment; after the final electronic payment is completed, the backdoor will be permanently closed.

Essentially, the operation of these smart contracts is similar to the if-then statements of computer programs. Smart contracts interact with real-world properties in this way. When a predefined condition is triggered, the smart contract executes the corresponding contract terms. The reason Nick Szabo's theory of smart contract operations has not been realized for a long time is due to the lack of inherently programmable digital systems that support them. If financial institutions still need to manually approve asset transfers, the goal of smart contracts will not be achieved. Phil Rapoport, head of markets and trading at Ripple Labs, said, "One major obstacle to realizing smart contracts is that current computer programs cannot truly trigger payments." The emergence and widespread use of blockchain technology are changing the status quo that hinders the realization of smart contracts, thus providing an opportunity for Nick Szabo's ideas to be realized. Smart contract technology is now built on the foundation of blockchain, as the blockchain itself is a computer program, and smart contracts can interact with it just as they can with other programs.

Based on the proposed concept of smart contracts and the continuous development of blockchain technology in recent years, we will attempt to provide a more specific and detailed explanation of smart contracts.

A smart contract is a set of commitments defined in digital form, controlling digital assets and containing the rights and obligations agreed upon by the participants in the contract, executed automatically by a computer system.

The commitment defines the essence and purpose of the smart contract. For example, in a sales contract: the seller commits to sending goods, and the buyer commits to paying a reasonable price. The digital form means that the contract needs to be written in executable code for computers; as long as the participants reach an agreement, the rights and obligations established by the smart contract will be executed by a computer or a computer network.

Let’s illustrate smart contracts with a simple example:

If Event_X_Happened:

Send(Alice, 1000$)

Else:

Send(Bob, 1000$)

This means: if Event X occurs, the contract sends $1000 to Alice; otherwise, it sends $1000 to Bob.

This is the simplest contract.

The diagram shows a model of a smart contract, with the definitions of its components as follows:

  1. Contract participants: Relevant participants executing the smart contract.
  2. Contract resource set: Resources involved in executing the smart contract, such as the accounts of the parties involved, owned digital assets, etc.
  3. Automatic state machine: The key to the next execution step of the smart contract, including current resource state judgment, next contract transaction execution selection, etc.
  4. Contract transaction set: The next actions or behaviors of the smart contract, controlling contract assets and responding to external information received.

Smart Contract Model

There are many tools for writing smart contracts, such as Visual Studio. Among them, the simplest and fastest development method is to use browser-based development tools, such as Remix. You can directly use it by opening the website http://remix.ethereum.org. Remix is a new name; it was previously called browser-solidity. Remix provides a rich Solidity integrated development environment for creating, developing, deploying, and debugging smart contracts in the browser. Operations related to contract maintenance (such as creation, publishing, debugging) can all be done in the same environment without switching to other windows or pages.

Some people may not be accustomed to using the online version of Remix. Since Remix is an open-source tool, it can be downloaded from https://github.com/ethereum/browser-solidity. After compilation, Remix can be used locally. Another advantage of using local tools is that it can connect to your own private network; otherwise, after writing the code on the webpage, you would need to copy the file locally and compile it before publishing it to the private network. Now let’s gradually understand Remix.

  1. Open the remix.ethereum.org website, and a smart contract will be opened by default in the browser.

If you don’t need it, you can delete it.

  1. Create a new contract by selecting the + in the left menu bar.

  2. Name this Solidity file with a .sol suffix. Enter the contract name HelloWorld, click "OK," and you will create a blank contract, as shown in the diagram below:

  3. In the blank space of the production bar, enter the following code to create your first contract.

The details of the contract will be explained in Chapter 3. For now, simply understand that you can use the keyword contract to create a contract, declare global state variables and functions, and save the contract as a file with the .sol suffix. In the source code snippet below, when the GetHelloWorld function calls the HelloWorld contract, it will return the "Hello World" string.

To the right of Remix is the operation window, which has many tab pages: compile, run, settings, debug, analyze, and support. These operations are used to compile, publish, debug, and call the contract. The debug tab will compile the contract into bytecode (the code understood by Ethereum), and it will display warnings and error messages that occur during debugging. You should pay enough attention to these messages, as resolving them will enhance the robustness of the contract. The run page will require more time compared to the contract writing page. In the "Environment" option, since Remix binds the Ethereum runtime environment in the browser, it allows you to publish contracts using the JavaScript virtual machine. The Injected Web3 option is used to work with Mist and MetaMask tools (which will be mentioned in the next chapter), and the Web3 Provider option is used when connecting Remix to a private chain locally. In this chapter's example, we will use the JavaScript virtual machine option by default. The remaining options will be discussed when introducing Solidity in Chapter 3.

  1. However, the most important operation for publishing the contract is to use the "Create" button, as shown in the diagram below:

  2. Clicking the Create button will allow you to run Ethereum in the browser, and the functions within the contract will be displayed below the Create button. Since there is only one function, GetHelloWorld, there is only this option. As shown in the diagram below:

  3. Clicking the GetHelloWorld button will call and execute this function. The execution result will be displayed in the section below Remix, as shown in the diagram below:

Congratulations! Your first contract has been successfully created, published, and executed. If you don’t like typing code directly, you can copy the HelloWorld contract code from this chapter into Remix for direct use.

Remix simplifies the publishing process, but many programs are still executed in the background. Understanding these steps will help us better control the publishing process.

Publishing Process

  1. Automation dimension: Smart contracts can automatically determine triggering conditions and select the corresponding next transaction; traditional contracts require manual judgment of triggering conditions, which is not as accurate or timely as smart contracts.

  2. Subjective and objective dimension: Smart contracts are suitable for objective requests, while traditional contracts are suitable for subjective requests. The agreements, collateral, and penalties in smart contracts need to be clearly defined in advance; however, subjective judgment indicators are difficult to incorporate into contract automata for judgment, making it challenging to guide the execution of contract transactions.

  3. Cost dimension: The execution cost of smart contracts is lower than that of traditional contracts, as the rights and obligations of contract execution are written into computer programs for automatic execution, providing cost advantages in state judgment, reward and punishment execution, and asset disposal.

  4. Execution time dimension: Smart contracts belong to a pre-scheduled, preventive execution model; traditional contracts adopt a post-execution model, determining rewards and punishments based on state.

  5. Breach penalty dimension: Smart contracts rely on collateral, deposits, and digital assets with digital attributes; once breached, participants' assets will suffer losses; traditional contracts' breach penalties mainly rely on criminal penalties, and legal means can be used to protect rights once breached.

  6. Applicability dimension: Smart contract technology can be adopted globally and is suitable for a worldwide scope; traditional contracts are limited by specific jurisdictions, and various legal and cultural factors in different international regions affect the execution process of traditional contracts.

How to Deploy a Contract#

The first step is to compile the contract using the Solidity compiler (in the next chapter, we will introduce how to download and use the Solidity compiler).

After compilation, there are mainly two outputs:

  • ABI specification
  • Contract bytecode

ABI (Application Binary Interface) is an interface composed of external functions with parameters and public functions. If a contract and other users intend to call functions within the contract, they can use the ABI to achieve this.

Bytecode is the representation of the contract that runs on Ethereum. During publishing, bytecode is required, while ABI is only used when calling functions within the contract. You can use the ABI to create a new contract instance.

The publishing of a contract itself is a transaction. Therefore, to publish a contract, you need to create a new transaction. During publishing, you need to provide the bytecode and ABI. Since transactions consume gas during execution, this gas needs to be provided by the contract. Once the transaction is packaged and written to the blockchain, you can use the contract via its address, and the caller can also call functions within the contract through the new address.

A deep understanding of how blockchain and Ethereum work will help you write more robust, secure, and efficient smart contracts using Solidity. This chapter introduced the basic concepts of blockchain, explained what blockchain is, why it is important, and what value it has for building decentralized and distributed applications. This chapter also briefly introduced the architecture of blockchain and some important concepts, such as transactions, blocks, gas, Ether, accounts, cryptography, and mining. Additionally, this chapter touched on some aspects of smart contracts, such as using Remix to write smart contracts and how to run them. The introduction was relatively simple, as further detailed explanations will follow, at which point you will be able to develop smart contracts using Solidity.

You will notice that this chapter did not mention some tools related to Ethereum. The next chapter will introduce the installation of Ethereum and related tools. The Ethereum ecosystem is rich, with many tools available for use. We will select some key ones for introduction, such as web3.js, TestRPC, Geth, Mist, and MetaMask.

Smart Contracts and Blockchain#

Nick Szabo's theory of smart contract operations has not been realized for a long time, primarily due to the lack of digital systems and technologies that can support programmable contracts. The emergence of blockchain technology has solved this problem, as it not only supports programmable contracts but also has advantages such as decentralization, immutability, and process transparency, making it inherently suitable for smart contracts. Therefore, it can also be said that smart contracts are one of the features of blockchain technology.

If blockchain 1.0 is represented by Bitcoin, which solved the decentralization of currency and payment methods, then blockchain 2.0 is more macro in decentralizing the entire market, using blockchain technology to convert many different digital assets, not just Bitcoin, to create different asset values. The decentralized ledger function of blockchain technology can be used to create, confirm, and transfer various types of assets and contracts. Almost all types of financial transactions can be transformed for use on the blockchain, including stocks, private equity, crowdfunding, bonds, and other types of financial derivatives such as futures and options.

Smart contracts appear to be a segment of computer execution programs that can be accurately and automatically executed. So why is it difficult to achieve this with traditional technology, necessitating new technologies like blockchain? Traditional technology, even through software restrictions and performance optimizations, cannot simultaneously achieve the characteristics of blockchain: first, data cannot be deleted or modified, only added, ensuring historical traceability, while the cost of malicious behavior will be high because such actions will be permanently recorded; second, decentralization avoids the influence of centralized factors.

Smart contracts based on blockchain technology can not only leverage the advantages of smart contracts in cost efficiency but also avoid malicious behavior interfering with the normal execution of contracts. Writing smart contracts in digital form into the blockchain ensures that the entire process of storage, reading, and execution is transparent, traceable, and immutable, thanks to the characteristics of blockchain technology. At the same time, the consensus algorithm built into the blockchain constructs a state machine system that allows smart contracts to run efficiently.

How Smart Contracts Work#

Blockchain-based smart contracts include mechanisms for transaction processing and storage, as well as a complete state machine for accepting and processing various smart contracts, with both transaction storage and state processing completed on the blockchain. Transactions mainly contain the data to be sent, while events describe this data. After transaction and event information is passed into the smart contract, the resource state in the contract resource set will be updated, triggering the smart contract to perform state machine judgments. If the triggering conditions for one or more actions in the automatic state machine are met, the state machine will automatically execute the contract actions based on preset information.

The smart contract system automatically issues preset data resources and events containing triggering conditions when the triggering conditions are met, based on the event description information. The core of the entire smart contract system lies in the processing of transactions and events through the smart contract module, outputting another set of transactions and events; the smart contract is merely a system composed of a transaction processing module and a state machine that does not generate or modify smart contracts; its existence is solely to ensure that a complex set of digital commitments with triggering conditions can be executed correctly according to the will of the participants.

The construction and execution of blockchain-based smart contracts involve the following steps:

  1. Multiple users collaboratively participate in formulating a smart contract.
  2. The contract spreads through the P2P network and is stored on the blockchain.
  3. The smart contract constructed by the blockchain is automatically executed.

Step 1, "Multiple users collaboratively participate in formulating a smart contract," includes the following steps:

A. Users must first register as users of the blockchain, and the blockchain returns a public key and private key to the user; the public key serves as the user's account address on the blockchain, while the private key is the only key to operate that account.

B. Two or more users agree on a commitment that includes the rights and obligations of both parties; these rights and obligations are programmed in machine language in electronic form; participants sign with their respective private keys to ensure the validity of the contract.

C. The signed smart contract will be transmitted to the blockchain network based on the commitment content.

Step 2, "The contract spreads through the P2P network and is stored on the blockchain," includes the following steps:

A. The contract spreads through P2P across the entire blockchain network, and each node receives a copy; the validating nodes in the blockchain will first save the received contract in memory, waiting for the next round of consensus time to trigger consensus and processing for that contract.

B. When the consensus time arrives, the validating nodes will package all contracts saved in memory during the recent period into a contract set and calculate the hash value of this contract set, finally assembling the hash value of this contract set into a block structure and spreading it across the network; other validating nodes that receive this block structure will extract the hash of the contract set contained within it and compare it with their saved contract set; at the same time, they will send a contract set they recognize to other validating nodes; through this multi-round sending and comparison, all validating nodes will ultimately reach consensus on the latest contract set within the specified time.

C. The latest agreed contract set will spread across the network in the form of a block, as shown in the diagram. Each block contains the following information: the hash value of the current block, the hash value of the previous block, the timestamp when consensus was reached, and other descriptive information; at the same time, the most important information in the blockchain is a set of contracts that have reached consensus; nodes receiving the contract set will verify each contract, and only contracts that pass verification will be finally written to the blockchain, with the verification content mainly focusing on whether the private key signatures of the contract participants match their accounts.

Smart Contract Execution

Step 3, "The smart contract constructed by the blockchain is automatically executed," includes the following steps:

A. The smart contract periodically checks the state of the automaton, traversing each contract's state machine, transactions, and triggering conditions; transactions that meet the conditions will be pushed to the queue for verification, while transactions that do not meet the triggering conditions will continue to be stored on the blockchain.

B. Transactions entering the latest round of verification will spread to each validating node, and like ordinary blockchain transactions, validating nodes will first perform signature verification to ensure the validity of the transaction; transactions that pass verification will enter the pending consensus set, and once a majority of validating nodes reach consensus, the transaction will be successfully executed and notify the user.

C. Once the transaction is successfully executed, the built-in state machine of the smart contract will determine the status of the contract; when all transactions included in the contract have been executed in sequence, the state machine will mark the contract's status as complete and remove that contract from the latest block; otherwise, it will be marked as ongoing and continue to be stored in the latest block, waiting for the next round of processing until completed; the entire transaction and state processing is automatically completed by the smart contract system built into the blockchain, with full transparency and immutability.

Suppose user Alice and user Bob need to construct a blockchain smart contract, with the purpose of Alice leasing her house to Bob for a rent of 1000 yuan per month, to be paid monthly, for a lease term of one year. Suppose Alice's house door lock can be controlled via the internet, and its unlocking key is Key (generated once a month), with Alice's bank account being MA and Bob's bank account being MB. The execution of the smart contract includes the following steps:

  1. Alice and Bob submit a contract construction request to the smart contract server, generating the contract, which is then published to the blockchain to take effect.

  2. Alice provides the Key and MA to the smart contract server.

  3. Bob pays 12000 yuan as a deposit to the smart contract server through MB, or Bob pays a small amount to the smart contract server through a third-party institution's guarantee.

  4. The contract begins execution; the smart contract server sends the Key to Bob, deducts 1000 yuan from Bob's deposit and sends it to Alice's account, and generates a record of the participants stored on the blockchain.

  5. Every month, the smart contract will periodically check; if the contract has not expired, it will continue to deduct 1000 yuan from Bob's deposit and send it to Alice's account while sending the Key to Bob, generating a record of the participants stored on the blockchain.

  6. The entire process is monitored by a third-party institution, and all participants and third-party institutions can query the contract execution status through the blockchain.

  7. After the lease term ends, the smart contract server generates a contract record indicating the termination of the contract and publishes it to the blockchain, thus terminating the contract execution.

The development of smart contracts may require a long road, but more smart contract mechanisms are being designed, and more talents from various fields are joining in. So far, for automated contract execution from vastly different fields such as economics, cryptography, network science, and finance, collaboratively designing research contract standards is an essential path. Without cross-communication, whether due to a lack of technology or a lack of awareness of business use models, it will lead to inefficiencies in smart contracts.

Currently, platforms such as Orisi, Codius, Symboint, Hedgy, BitHalo, Mirror, Hyperledger, Eris Industries, Ethereum, Smart Contract Workshop, NEO, Colored Coin, and IBM are already committed to the development and related research of smart contracts, and the application prospects of smart contracts are bright.

References

[1] http://www.fastcolabs.com/3035723/app-economy/smart-contracts-could-be-cryptocurrencys-killer-app

[2] https://medium.com/@heckerhut/whats-a-smart-contract-in-search-of-a-consensus-c268c830a8ad

[3] http://www.wtoutiao.com/p/14dyEMP.html

[4] http://www.coindesk.com/smart-contract-myths-blockchain/

[5] http://8btc.com/article-1921-1.html

[6] http://wangxiaoming.com/blog/2016/03/03/blockchain-2-0-he-yue/

Ethereum Network#

The Ethereum network is an open-source platform for creating and deploying distributed applications, supported by a large number of computers (nodes) that interact with each other and store data in a distributed ledger. Here, the meaning of distributed ledger is that each node on the network has a copy of the ledger. For developers, there are various network deployment options available, allowing them to choose a suitable network based on actual needs and scenarios when deploying solutions and smart contracts, so they do not have to pay real Ether or incur other expenses. Of course, there are also free networks available, as well as networks that require users to pay with Ether or other currencies.

The Ethereum mainnet is a global public network that anyone can use, and access to the network is available through accounts. For anyone, creating an account, deploying solutions, and contracts is free. The usage fee on the mainnet is measured in gas. Its code name is homestead (previously called Frontier). Through the internet, people can connect to the mainnet and view data and transactions on it.

Test Network#

The purpose of the test network is to help people quickly adapt to and use the Ethereum environment, and it is an accurate copy of the mainnet. On the test network, deploying and using contracts incurs no real costs because the Ether used for testing is generated arbitrarily and can only be used on the test network. At the time of writing this book, there are multiple test networks available, such as Ropsten, Kovan, and Rinkeby.

Ropsten is the first test network to produce blocks using the PoW consensus algorithm. It was previously called Morden. As mentioned above, you can use it free of charge to build and test contracts. You can enter the test network by adding the --testnet parameter in Geth. The usage of Geth will be introduced later. Ropsten is currently the most popular test network.

Rinkeby is another Ethereum test network that uses the PoA consensus mechanism. The mechanisms for establishing consensus among miners differ between PoW and PoA. PoW is stronger in maintaining immutability and decentralization, but its drawback is that it cannot effectively control miners. PoA has the advantages of PoW while also having a certain level of control over miners.

The Kovan test network can only be used among a small number of users, so more information can be accessed at: https://kovan-testnet.github.io/website/.

Private Network#

A private network is established and operated on a network owned by the user, with control held by a single organization. For testing purposes, people may not want to place solutions, contracts, and scenarios on a public network, so they need to establish a development, testing, and production environment, thus users should set up a private network to maintain full control.

Consortium Network#

A consortium network is also a private network, but with one difference: the nodes in a consortium network are managed by different organizations. In fact, no single organization can solely control the network and data on a consortium chain; instead, it is jointly controlled by all organizations and individuals within those organizations who have viewing and modification permissions. Consortium chains can be accessed via the internet or VPN networks.

Geth#

Currently, there are various Ethereum client nodes and tools written in multiple languages, including Go, C++, Python, JavaScript, Java, and Ruby. These functionalities are not limited by language, allowing developers to choose the one that best suits them. This book uses Go language, which is referred to as Geth, and can connect to public and test networks; it can also run mining and EVM (transaction nodes) on private networks.

Geth is a command-line tool written in Go language, which can be used to create nodes and miners on a private network. Geth can be installed in Windows, Linux, and Mac environments.

Installing Geth on Windows#

Before setting up a private network, you need to download and install the Geth (goethereum) tool.

The following are the steps for downloading and installing:

  1. You can visit https://ethereum.github.io/go-ethereum/downloads/ to download, with both 32-bit and 64-bit versions available. In this book, the operating system used is Windows Server 2016 on Azure cloud.

  2. After downloading, execute the installation file, and proceed step by step according to the default configuration to complete the development environment setup.

  3. Once the installation is complete, you can use it in CMD and PowerShell.

  4. Open the command line and enter geth --help.

It is important to note that when you enter geth, it will connect to the mainnet and begin synchronizing and downloading block and transaction data. Currently, the entire Ethereum blockchain has exceeded 30GB[1]. After executing the help command, the screen will display the available commands for geth, including the version number.

Geth is based on the JSON RPC protocol. It defines a remote call specification using JSON format. Geth can connect using the following three JSON RPC protocols:

  • Inter-Process Communication (IPC): Internal communication, usually used within a single computer.

  • Remote Procedure Calls (RPC): Communication across computers, typically using TCP and HTTP protocols.

  • WS, WebSockets: Using sockets to connect to Geth.

  • Configuring Geth involves many commands, switch parameters, and options, including:

  • Configuring IPC, RPC, and WS protocols.

  • Configuring the type of network connection—private network, Ropsten, and Rinkeby.

  • Mining options.

  • Console and API.

  • Network.

  • Debugging and logging.

Among these, some options used when creating a private network will be mentioned in the next section.

Geth can directly connect to the public chain using geth (without options). Homestead is the name of the current public chain. Its Network ID and Chain ID are 1.

Different networks have different Chain IDs. Among them:

  • Chain ID 1 is the main public chain.
  • Chain ID 2 is the Morden network (open to a limited number of people).
  • Chain ID 3 is the Ropsten network.
  • Chain ID 4 is the Rinkeby network.
  • Chain IDs greater than 4 are private networks.

Additionally, you can use geth --testnet to connect to the Ropsten network, and --rinkeby to connect to the Rinkeby network; Geth can also be used in conjunction with Chain ID.

Setting Up a Private Network#

Once Geth is installed, you can first configure it locally without connecting to the internet. Each network has a genesis block, which is the first block of the entire network and has no parent block. The genesis block is generated by the genesis.json file. The following code shows the content of genesis.json.

Following the steps below, we will begin setting up a private network.

  1. During network initialization, Geth needs to use the genesis.json file and provide a directory to save block data and account private keys (keystore).

  2. Enter the geth init command, the genesis.json file, and the folder for storing block data and keystore to initialize.

The output result is as follows:

  1. In the screenshot above, we can see that the genesis block has been generated, and the Geth node can be started. By default, Geth uses the IPC protocol upon startup. To ensure that the Geth node can be accessed via the RPC protocol, the command needs to include the RPC parameter.

  2. To set up the environment for running the node, execute the following command:

The execution result is as follows:

In the command execution, we can see that the command uses the datadir parameter, enables RPC, exposes modules and APIs to the outside, and the Network ID is 15, indicating that this is a private network[1]. From the execution result, we will find some valuable information. First, the etherbase or coinbase has not been set; it needs to be configured before mining starts. Currently, the mining task has not been initiated (it can also be started via command line). The screen displays the location where block data is stored, as well as the Chain ID, and whether it is connected to the Homestead mainnet; a value of 0 indicates that it is not connected to the mainnet. The enode information on the screen is the node's identity marker in the network. If other nodes are preparing to join this network, they will need to provide their enode value.

Finally, the screen shows that the IPC and RPC protocols are running and accepting requests. RPC access can be done via http://127.0.0.1:8545 or http://localhost:8545, and IPC access can be done via \.\pipe\geth.ipc.

  1. The above command will start the Ethereum node. Observant readers may notice that the command runs as a service, which prevents executing other commands. Therefore, to manage these running nodes, we can open another command line window on the local machine and enter geth attach ipc:\\.\pipe\geth.ipc to connect to the node using the IPC protocol, allowing us to execute other commands. The following diagram shows this:

  2. To connect to the local private network, you can use the RPC method by entering the command geth attach rpc:http://localhost:8545 or geth attach rpc:http://127.0.0.1:8545. If the result you see is different from what is shown above, it is because in my example, the coinbase account has already been set. The coinbase account will be introduced later.

  3. The default RPC access port is 8545, which can be set in the command line using the --rpcport parameter. The IP address can also be set using the --rpcaddr parameter.

  4. After connecting to the Geth node, the next step is to set the coinbase or etherbase account. First, you need to create a new account, which can be done using the personal object's newAccount method. When creating an account, you need to enter a password. The following screen shows the account ID information after the account is created.

  5. After the account is created, you need to determine whether to use the coinbase account or etherbase account. If you need to change the existing coinbase account address, you can do so using the address.miner object's setEtherBase function. This operation will replace the original coinbase account with the new account. The result of the change will be displayed as true or false.

  6. Execute the following query command, and you will find that the address you just set has taken effect.

Once the coinbase address is successfully set, the Geth node starts running, and mining can be initiated. Since we only have one miner, it will receive all the mining rewards, and the Ether in the coinbase account will gradually increase.

  1. Execute the following code to start mining:

You can also use the following command:

The execution result of the above command is as follows:

The parameter in start represents the number of threads used for mining. This command will start the mining program, and you can also see the execution result on the screen.

  1. If you need to stop mining, you can execute the miner.stop() command in another window.

[1] As mentioned earlier, IDs greater than 4 indicate private networks. — Translator's note

ganache-cli#

In Ethereum, the process of writing transactions to the ledger is divided into two stages:

  • Creating a transaction and placing it in the transaction pool.
  • Regularly fetching transactions from the transaction pool and then starting mining. Mining means writing these transactions to the Ethereum database or ledger.

From the above process, it can be seen that developing and testing solutions and smart contracts on Ethereum can be very time-consuming. Ganache-cli (formerly known as TestRPC) was created to alleviate this issue. Ganache-cli contains the transaction processing flow and mining functionality of Ethereum, but mining does not require competition; once a transaction is generated, it will be immediately written to the ledger. For developers, using ganache-cli can serve as an Ethereum node, allowing transactions to be written to the ledger without mining.

Ganache-cli is developed based on Node.js, so you need to install Node.js before deploying ganache-cli. You can download it from the website https://nodejs.org/en/download/, choosing the appropriate 32-bit or 64-bit operating system version, and click the link displayed on the screen to download the installation package:

Now, we will download the 64-bit Windows installation version, which can be used to install the Node Package Manager (NPM) and Node.js.

Solidity Compiler#

Solidity is a language for writing smart contracts. The following chapters will detail smart contracts. After writing Solidity code, it needs to be compiled using the Solidity compiler, which will generate bytecode and other outputs that will be used when deploying smart contracts. Previously, Solidity was part of the Geth installation package, but it has now been separated from the Geth installation process and needs to be installed independently. The Solidity compiler is referred to as solc and can be installed using the npm command:

web3 JavaScript Library#

The web3 library is an open-source JavaScript library that can connect to local or remote Ethereum nodes using IPC or RPC protocols. The web3 library is client-facing and can be used with web pages to initiate query requests and transaction submission requests to Ethereum nodes. We can install it using node management tools, just like the installation of the Solidity compiler. When writing this book, the latest version of web3 could not run and prompted that it was not installed correctly due to the missing BigNumber.js file. However, previous stable versions could connect to the backend of Ethereum nodes. The following steps show how to install the web3 JavaScript library.

  1. Install web3 using the following command:

After execution, the result is as follows:

  1. After web3 is installed, it can be called using Node.js. In command line mode, as shown in the diagram, execute the node command to enter node mode.

  2. In node mode, entering the following command will connect to the Ethereum node. The Ethereum node can be a TestRPC or a private network based on Geth. The following example shows web3 connecting to the Ethereum node using the RPC protocol:

The first line of the command loads the web3 module, and the second command creates a new HttpProvider instance to connect to the Ethereum node on local port 8545.

  1. To verify whether web3 is connected to the Ethereum node, you can execute the isConnected method. If the return value is true, it indicates that web3 has successfully connected.

Mist Wallet#

Ether runs on Ethereum, so a wallet is needed to send and receive Ether. Mist is such a wallet that allows users to send and receive Ether, and it also facilitates users to conduct transactions on the Ethereum network (including both public and private networks). In Mist, users can create accounts, send and receive Ether, deploy and call smart contracts.

Mist can be downloaded from https://github.com/ethereum/mist/releases. Users need to choose a suitable installation package based on their situation (in this example, we are using Windows 2016 environment, so we downloaded Ethereum-Wallet-win64-0-9-2.zip), and after downloading, unzip it. After unzipping, the files are shown in the diagram below; double-click the Ethereum Wallet icon.

Mist will start. Mist has a certain level of intelligence; if a private chain is running locally, it will recognize and connect to it. If there is no private network running locally, it will connect to the mainnet or the Rinkeby test network.

In this book, we have already set up a private network, and the following diagram shows its connection status:

Once connected successfully, you can interact with the Ethereum network, send and receive Ether, deploy smart contracts, and call functions within smart contracts.

MetaMask#

MetaMask is a lightweight plugin for the Chrome browser that can interact with the Ethereum network. It is also a wallet for sending and receiving Ether. MetaMask can be downloaded from https://metamask.io. Since MetaMask runs in the browser, blockchain data cannot be downloaded locally; it can only be stored on remote servers, and users access it through the browser. Below are the operational steps:

  1. MetaMask can be added as a plugin, as shown in the diagram:

  2. After confirming the privacy reminder and user agreement, a small icon will appear next to the go button. MetaMask can connect to multiple networks, as shown in the diagram connecting to the local network on Localhost 8545.

  3. In MetaMask, to verify identity, when creating a key, you need to provide a protective password. This information is stored in the MetaMask server's key vault, as shown in the diagram:

  4. Click the Account icon and use the Import Account menu to import an existing account:

  5. After the account is created, MetaMask can transfer Ether from one account to another through Ethereum transactions.

  6. To send Ether to another account, first select a sending account, then click the Send button, enter the target account address and amount in the pop-up window, and then click the Next button:

  7. Click the submit button to submit the transaction. At this point, the transaction will be stored in the transaction pool and be in a pending state. The mining task will begin to write this transaction into permanent storage.

  8. Start the mining task in the Geth console, and the transaction will be packaged, as shown in the diagram:

After a while, the transaction will be written to the ledger, and the account balances of both parties in MetaMask will change.

Ethereum nodes provide JSON RPC connection methods, and we can connect using various methods such as WebSockets, IPC, RPC, etc. In this chapter, we introduced various blockchain networks: public networks, main networks, test networks, and private networks. This chapter also explained how to build a private network and how to set up a development environment, which will be used in the next chapter. This chapter focused on how to install various tools in a Windows environment. These tools have various uses. It is evident that some tools overlap in functionality. For example, both Geth-based private networks and ganache-cli development environments can create Ethereum nodes, but there are still some differences. This chapter also introduced how to install Geth, the Solidity compiler, ganache-cli, the web3 library, JavaScript framework, Mist, and MetaMask wallet.

Thus, Ethereum has established a programmable, Turing-complete blockchain. On this blockchain, you can produce various digital assets through simple programs, and you can also precisely control the state of blockchain assets circulating on Ethereum by writing programs, such as whether this asset is pending payment, locked, or has limits, whether this account is on a blacklist or whitelist, and the automatic exchange between Ethereum and other digital assets, etc. At the same time, Ethereum serves as a programmable, Turing-complete blockchain network foundation, on which we can realize more functional products for non-blockchain assets. For example, I can use Ethereum to establish smart contracts applied in personal daily economic life and corporate economic activities, and such applications can also be realized.

Ethereum is a brand new open blockchain platform built on the concepts of blockchain and blockchain assets. It allows anyone to establish and run decentralized applications on the platform using blockchain technology. In simple terms, Ethereum technology is blockchain technology plus smart contracts.

From its inception, Ethereum has planned a detailed development path and iteration versions, with a total of four planned iteration versions:

The first version Frontier

The second version Homestead

The third version Metropolis

The fourth version Serenity

Now, let’s recount some significant events in Ethereum's history:

At the end of 2013, founder Vitalik released the initial version of the white paper, launching the project.

In July 2014, Ethereum conducted the first pre-sale of Ether. This was also one of the more well-known cases in early ICOs. However, at that time, the term ICO did not exist; people in the circle referred to this token issuance as "coin crowdfunding." Through a 42-day pre-sale, the Ethereum team raised over 30,000 Bitcoins and pre-sold 60 million Ethers.

In October 2014, Ethereum reduced the block time from 60 seconds to 12 seconds, which is now basically stabilized at 15 seconds.

On July 30, 2015, the first version Frontier was released, which was the initial version of Ethereum, featuring only a command-line interface and no graphical interface, primarily suitable for developers.

On March 14, 2016, Pi Day, Ethereum released the second version Homestead, which is the version currently in operation, greatly improving usability with a graphical interface, allowing ordinary users to experience Ethereum's functions and development.

In July 2016, Ethereum underwent a hard fork, splitting into Ethereum ETH and Ethereum Classic ETC. This will be discussed in detail later.

Recently, Ethereum aims to release the third version Metropolis. In the third version Metropolis, the Ethereum founding team will release a browser designed for non-technical users, named the Mist browser. You can think of it as a Chrome browser, which is very convenient to use and has a powerful and complete application store. The Mist browser will also include a decentralized application store and basic applications. If such a browser can be released, it will greatly benefit the participation and experience of decentralized applications for a wide range of internet users. According to the current progress announced by the Ethereum team, the third version is expected to be released by the end of 2017.

The release date for the final stage Serenity has not yet been determined. In the first three stages, Ethereum's consensus mechanism adopted the Proof of Work (PoW) consensus mechanism, while the fourth stage will switch to a hybrid consensus mechanism.

The hybrid consensus mechanism combines the Bitcoin-style Proof of Work (PoW) with the Proof of Stake mechanism created by Vitalik, balancing the rights and interests of miners and coin holders.

After discussing version iterations, I will list some terms related to Ethereum, which can help you understand the entire Ethereum system.

Ether

The first term is Ether. It is the token in the Ethereum system, abbreviated as ETH. Ether is the main fuel within Ethereum, providing the primary liquidity for running various digital asset transactions on this system and also used for paying smart contract fees. It is the built-in blockchain asset of Ethereum used to pay for the operation of smart contracts. This concept is relatively simple to understand; we previously learned about Hash Cash and Proof of Work. I wonder if everyone remembers. We learned that to prevent the network from being flooded with spam, the sending computer must perform some work calculations. This imposes a significant burden on computers sending large amounts of spam. Similarly, in the Ethereum network, establishing and running smart contracts also requires a small threshold, which is relatively low for serious developers but poses a significant burden for initiators of numerous spam projects or attackers. However, the threshold in Ethereum is not work but fuel, which we call "Gas," and Gas is exchanged for Ether.

Imagine if running a smart contract did not require any fees; many garbage contracts or applications would appear on this blockchain, leading to attacks that would render the entire network unusable. Therefore, the Ethereum blockchain requires a certain amount of Gas to be paid each time a smart contract is executed to ensure the stability and security of this blockchain.

Regarding the denomination of Ether, we are familiar with Bitcoin's smallest denomination being a satoshi, which is one hundred millionth of a Bitcoin. Ethereum also has its smallest denomination, named wei. How small is it? One Ether token is divided into 18 decimal places, which equals 1 wei.

Additionally, in July 2016, a hard fork occurred in the Ethereum blockchain, splitting Ethereum into two blockchains. The upgraded Ethereum, led by founder Vitalik, is called Ethereum, with the token code ETH. The chain that did not accept this upgrade is called "Ethereum Classic," with the original chain's Ether token code being ETC.

Ethereum Virtual Machine (EVM)

The second concept is the Ethereum Virtual Machine (EVM). In a programming system, there are usually some compilation and execution virtual machines to support it. Just as Java has the JVM, Ethereum has its virtual machine that can execute any complex algorithm code. Developers can use existing friendly programming languages like JavaScript or Python to create the applications they desire on Ethereum.

Smart Contract

The third concept is the smart contract. The idea of smart contracts is not new; it was first proposed by cryptographer Nick Szabo in 1995, almost simultaneously with the internet, referring to commitments defined and automatically executed by computer programs. Although the idea has been around for a long time, it was not until the emergence of Ethereum that smart contracts became widely applied. An important reason is the previous lack of a friendly, programmable foundational system.

With smart contracts, anyone can create the decentralized applications they want on Ethereum. Once created, smart contracts on Ethereum can automatically execute without the involvement of intermediaries, and no one can stop their operation. Smart contracts on Ethereum can control various digital assets on the blockchain and perform complex algorithms and operations.

For example, we often purchase flight delay insurance when flying, but when a delay actually occurs, you may still need to call customer service to understand the process, obtain proof offline, and contact the insurance company to complete your delay insurance claim. If smart contracts were in place, by inputting conditions and linking flight data, the insurance company could automatically pay you after the flight delay. The execution of the contract does not require third-party involvement and is automatic, greatly improving the efficiency of social and economic activities.

On the Ethereum blockchain, you can write asset code, create new blockchain assets, and simply put, you can issue your own blockchain tokens. You can decide what kind of issuance mechanism to use, what the token is called, how many to issue, and how to issue them. Doesn’t that sound interesting? At the same time, you can also create functionalities for non-blockchain assets by writing smart contract code, such as voting, betting, conditional contracts, etc.

To support smart contracts, Ethereum has two types of account addresses: one is called an ordinary account, and the other is called a contract account. Ordinary accounts are similar to accounts in the Bitcoin network, while contract accounts are mainly used for smart contracts.

Now, let’s review this lesson. We introduced the second type of blockchain project, the smart contract platform, represented by Ethereum. I guided you through the origins of Ethereum, version iterations, and important terms.

Ethereum was created by Russian developer Vitalik in 2013, addressing the shortcomings of the Bitcoin blockchain system, such as the lack of Turing completeness. Ethereum established a programmable, Turing-complete blockchain that helps people more conveniently produce various digital assets and more precisely control the state of blockchain assets.

Ethereum's development is planned in four stages: Frontier, Homestead, Metropolis, and Serenity.

"Frontier" is the initial version of Ethereum, featuring only a command-line interface, primarily used by developers.

The second version "Homestead" added a graphical interface similar to Windows, allowing ordinary users to easily experience Ethereum's functions.

The third version "Metropolis" will include a browser similar to Google Chrome, which, in addition to being user-friendly, will also have a powerful application store for installing plugins to achieve more functionalities. The third version is expected to be released by the end of 2017.

The release date for the fourth version "Serenity" has not yet been determined. It is expected that the consensus mechanism used in the first three versions, Proof of Work (PoW), will switch to a hybrid consensus mechanism.

After discussing the four versions of Ethereum, we also learned about three important concepts related to Ethereum: "Ether," "Ethereum Virtual Machine," and "Smart Contract," which represent the tokens in the Ethereum system, the operating environment of the Ethereum system, and the blockchain project represented by Ethereum, respectively. Understanding these concepts will help us better learn about Ethereum.

Regarding tokens, the biggest difference between Ethereum and Bitcoin is their production and total quantity. Bitcoin's production is halved every four years, while Ether's production is fixed. We know that the total quantity of Bitcoin is 21 million, but what is the total quantity of Ether? This is an interesting story, so let me explain it to you slowly.

The total issuance of Ethereum = X + 0.99X + 0.99X

In 2014, the Ethereum team discussed and made a regulation: Ethereum would first conduct a pre-sale, and the result of the pre-sale would be set as a baseline number to determine the total issuance of Ethereum and its annual production.

Assuming that during the first pre-sale, X Ether was sold, then another 0.99X would be newly issued and allocated to early contributors who participated in the development before the pre-sale, and another 0.99X Ether would be newly issued and allocated to long-term project researchers. Therefore, during the pre-sale period, a total of X + 2 * 0.99X Ether would be issued.

The annual issuance of Ether = 0.26X

After the pre-sale of Ether, the Proof of Work mechanism (PoW) will be used for mining, and it is stipulated that the number of Ether issued each year is 0.26X. Thus, this baseline number from the pre-sale determines the total quantity and issuance of Ethereum.

Let’s calculate how many Ethers will be mined after Ethereum goes live. Each year, approximately 6 million * 0.26 (60102216 * 0.26 = 15626576) will be mined, which is about 15.6 million Ethers. Hearing so many numbers, you might feel a bit dizzy. Don’t worry; reviewing the text content after class will help you understand quickly.

Now, let’s continue. You might be curious: with so many Ethers produced each year, how will miners share them? Is it divided equally per block? Of course not.

The reward mechanism of Ethereum: block reward + uncle block reward + uncle

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.