0 117 min 4 dys

  Original text:

  Translator: Feilong

  Protocol: CC BY-NC-SA 4.0

  Since the early success of Bitcoin, many alternative currency projects have been launched. Bitcoin was released in 2009, and the first alternative coin project (named Namecoin) was launched in 2011. In 2013 and 2014, the alternative currency (also known as altcoins) market experienced explosive growth, launching many different types of alternative currency projects.

  其中一些取得了成功,而许多因缺乏兴趣而不受欢迎,并因此未获成功。有一些是炒作和抛售骗局,短暂出现但很快就消失了。比特币的替代方法可以大致分为两大类,根据其开发的主要目的。如果主要目标是构建一个去中心化的区块链平台,它们被称为另类链;如果替代项目的唯一目的是推出新的Online casino and How to find it ,它就被称为另类货币。

  另类区块链将在第十四章“另类区块链”中详细讨论。

  本章主要专注于旨在推出新的Online casino and How to find it (币)的另类货币,尽管也会介绍一些建立在比特币之上提供各种服务的另类协议的内容。其中包括 Namecoin 等概念,其主要目的是提供去中心化的命名和身份服务而不是货币。

  目前,截止 2018 年底,市场上有数百种另类货币,它们具有一定的货币价值,如 Namecoin、Zcash、Primecoin 等。我们将在本章的后面部分对其中一些进行详细考察。Zcash 是一种成功的另类货币,于 2016 年推出。另一方面,Primecoin 并没有获得太多的关注,但仍在使用。许多另类项目是比特币源代码的直接分叉,尽管有些是从头开始编写的。一些另类货币旨在解决比特币的限制,如隐私问题。其他一些提供不同类型的挖矿、改变区块时间和分配方案。

  根据定义,硬分叉的情况下会产生一种替代币。如果比特币发生硬分叉,则其他旧链有效地被认为是另一种货币。然而,尚无确立的规则规定哪条链成为替代币。这在以太坊中已经发生过,其中一次硬分叉导致了一种新的货币以太坊经典(ETC)的产生,除了以太坊(ETH)货币之外。以太坊经典是旧链,而以太是硬分叉后的新链。这样具有争议的硬分叉出于某些原因是不可取的。首先,它违背了去中心化的真正精神,因为以太坊基金会,一个中央实体,决定继续进行硬分叉,即使并非每个人都同意该提议;第二,它还由于对硬分叉的分歧而分裂了用户社区。尽管硬分叉在理论上会生成一种替代币,但它在提供的内容上受到限制,因为即使更改导致硬分叉,通常在货币的基本参数周围也没有重大变化。它们通常保持不变。出于这个原因,最好要么从头开始编写一个新币,要么分叉比特币(或其他币种的源代码)来创建一个具有所需参数和功能的新货币。

  Alternative coins must be able to attract new users, transactions, and miners, otherwise the currency will be valueless. The value of a currency, especially in the Online casino and How to find it field, is due to network effects and community acceptance. If a currency fails to attract enough users, it will soon be forgotten. Users can be attracted by providing an initial amount of currency, and this can be achieved through various methods. However, there is a risk that if the new coin performs poorly, their initial investment may be lost. The methods for providing an initial amount of alternative coins are described as follows:

  Creating a new blockchain: Alternative coins can create a new blockchain and distribute currency to the initial miners, but due to many fraudulent schemes or hype and dumping plans, this method is now unpopular. In this method, the initial miners profit from the launch of the new currency and then disappear.

  Burn Proof (PoB): Another method for distributing initial capital for new alternative coins is PoB, also known as one-way anchoring or price ceiling. In this method, users permanently destroy a certain amount of Bitcoin, proportional to the number of alternative coins to claim. For example, if ten Bitcoin are destroyed, the value of the alternative coin may not exceed some of the destroyed Bitcoin. This means that Bitcoin is converted into alternative coins through destruction.

  Ownership Proof: Unlike the permanent destruction of Bitcoin, an alternative method is to prove that the user owns a certain amount of Bitcoin. This ownership proof can be used to declare alternative coins by binding the alternative coin blocks with Bitcoin blocks. For example, this can be achieved through merged mining, where Bitcoin miners can mine alternative coin blocks while mining Bitcoin without additional work. Merged mining will be explained later in this chapter.

  Fixed Sidechain: As the name implies, a sidechain is a blockchain separate from the Bitcoin network, but Bitcoin can be transferred to them. Alternative coins can also be transferred back to the Bitcoin network. This concept is known as two-way anchoring.

  Investing and trading these alternative coins is also a big business, although not as large as Bitcoin, it is enough to attract new investors and traders, and provide liquidity to the market. The combined market value of alternative coins is as shown above.

  This chart is generated by.

  

  This chart shows that the combined market value of alternative cryptocurrencies at the time of writing exceeded 2 trillion US dollars.

  The market value of the top ten cryptocurrencies as of March 2018 is as follows:

  Name Market Cap Price USD Bitcoin $151,388,873,045 $8,951.83 Ethereum $68,472,253,587 $697.94 Ripple $31,340,920,806 $0.801723 Bitcoin Cash $17,182,167,856 $1,010.08 Litecoin $9,952,905,688 $179.11 NEO $5,638,100,000 $86.74 Cardano $5,450,310,987 $0.210217 Stellar $5,438,720,268 $0.294010 EOS $4,347,501,290 $6.04 Monero $4,211,690,257 $266.40

  Data from.

  With the emergence of altcoins, various factors and new concepts have appeared. Many of these concepts were even invented before Bitcoin, but with the advent of Bitcoin, not only were new concepts such as solutions to the Byzantine General’s Problem introduced, but previous ideas such as hashcash and Proof of Work (PoW) were cleverly utilized and gained attention.

  Since then, with the launch of altcoin projects, various new technologies and concepts have been developed and introduced. To appreciate the current landscape of alternative cryptocurrencies, it is essential to understand some theoretical concepts first.

  In this section, various theoretical concepts that have developed over the past few years along with the introduction of different altcoins are introduced.

  In the context of cryptocurrencies, the PoW scheme was first used in Bitcoin and serves as a mechanism to ensure that miners have completed the required work to find a block. In return, this process provides decentralization, security, and stability to the blockchain. This is the main means by which Bitcoin provides decentralized distributed consensus. The PoW scheme requires a very ideal property called progress-freeness, which means that the reward for consuming computing resources should be random and proportional to the miner’s contribution. In this case, even those miners with relatively less computing power have a certain chance to win the block reward.

  The term ‘progress-free’ was first proposed by Arvind Narayanan and others in the book ‘Bitcoin and Cryptocurrency Technology’. Other requirements for the mining computational难题 include adjustable difficulty and fast verification. Adjustable difficulty ensures that the difficulty target of blockchain mining is adjusted according to the increased hash power and user number.

  Fast verification is a property that means the verification of mining computational puzzles should be simple and fast. Another aspect of the PoW scheme, especially the one used in Bitcoin (double SHA-256), is that power has been shifting since the introduction of ASICs to miners or mining pools that can afford the costs of large-scale ASIC farms. This power shift challenges the core decentralization concept of Bitcoin.

  Some alternative solutions have been proposed, such as ASIC-resistant puzzles, which are designed in such a way that building ASICs to solve this puzzle becomes infeasible and does not bring significant performance gains compared to commodity hardware. One common technology for this purpose is the application of computationally difficult problems known as memory hard problems. The core idea behind this method is that since solving the puzzle requires a large amount of memory, it is not feasible to implement it on an ASIC-based system.

  This technology was initially used in Litecoin and Tenebrix, where the Scrypt hash function was used as an anti-ASIC PoW scheme. Although this scheme was initially promoted as ASIC-resistant, the Scrypt ASIC has now been released, proving that Litecoin’s initial statement was incorrect. This is because Scrypt is a memory-intensive mechanism, and it was initially believed that it would be difficult to build ASICs with large memory capacity due to technical and cost limitations. However, the situation has changed now that memory is becoming cheaper, and there is the ability to produce nanoscale circuits that can build ASICs capable of running the Scrypt algorithm.

  Another method to resist ASICs is to require the calculation of multiple hash functions to provide PoW. This is also known as a chained hash scheme. The theoretical basis for this idea is that designing multiple hash functions on ASICs is not very feasible. The most common example is the X11 memory hard function implemented in Dash. X11 includes 11 SHA-3 competitors, where one algorithm outputs the calculated hash to the next algorithm until all 11 algorithms are used in sequence. These algorithms include BLAKE, BMW, Groestl, JH, Keccak, Skein, Luffa, CubeHash, SHAvite, SIMD, and ECHO.

  This method initially indeed provided some resistance to the development of ASICs, but now ASIC miners are commercially available and support mining with X11 and similar schemes. A recent example is the ASIC Baikal Miner, which supports X11, X13, X14, and X15 mining. Other examples include miners such as the iBeLink DM384M X11 miner and the PinIdea X11 ASIC miner.

  There may be another way, which is to design smart or randomly changing PoW schemes or their self-changing puzzles. This strategy will make it almost impossible to implement in ASICs, as it will require designing multiple ASICs for each function, and random changes to the scheme are almost impossible to handle in ASICs. It is currently unclear how to implement this in practice.

  PoW indeed has various disadvantages, the most significant of which is energy consumption. It is estimated that the total electricity consumed by Bitcoin miners currently exceeds that of Bangladesh, reaching 54.69 terahashes (TWh). This is huge, and all the energy is wasted to some extent; in fact, there is no useful purpose other than mining. Environmentalists have expressed genuine concerns about this situation. In addition to electricity consumption, the carbon footprint is currently very high, with each transaction approximately 387 kilograms of CO2.

  The following chart shows the scale of Bitcoin energy consumption compared to other countries. It will only continue to grow, and it is estimated that by the end of 2018, the energy consumption may reach about 125 TWh annually.

  

  Energy consumption in various countries

  The chart shown above is from a website that tracks this topic. It can be found on [the website].

  It has been proposed that the PoW difficulty can be designed to have two purposes. First, their main purpose is in the consensus mechanism, and secondly, to perform some useful scientific calculations. In this way, not only can the scheme be used for mining, but it is also expected to help solve other scientific problems. This useful work proof was recently implemented by Primecoin, which requires finding special prime number chains, namely Kanihara chains and twin prime chains. Since the research on prime number distribution has special significance in scientific disciplines such as physics, by mining Primecoin, miners can not only obtain block rewards but also help find special prime numbers.

  Also known as retrievability proof, this is another useful work proof type that requires storing a large amount of data. Introduced by Microsoft Research, this scheme provides useful benefits for distributed storage. Miners need to store a portion of a large amount of pseudo-randomly selected data for mining.

  This proof is also known as virtual mining. It is another mining difficulty alternative to the traditional PoW scheme. It was first proposed by Peercoin in August 2012. Under this scheme, users need to prove that they own a certain amount of currency (coins) to prove that they have certain rights to the currency. The simplest form of ownership is to reward users who own more lottery and How to find it with relatively easier mining methods. The advantages of this scheme are twofold; first, compared to purchasing high-end ASIC devices, obtaining a large amount of lottery and How to find it is relatively difficult, and secondly, it can save computing resources. Various forms of ownership have been proposed and will be briefly discussed in the following sections.

  不同类型的权益将在下面的小节中介绍。

  货币的年龄指的是货币上次使用或持有的时间。这与通常的 PoS 形式不同,在这种方式中,对于持有另类币中最大权益的用户来说,挖矿变得更容易。在基于货币年龄的方法中,每次挖出一个区块时,货币的年龄(货币权益)都会被重置。矿工因为持有而不使用货币一段时间而获得奖励。这种机制已经在 Peercoin 中以一种创造性的方式与 PoW 结合实施。

  挖矿难题(PoW)与货币的时间成反比,这意味着如果矿工使用货币进行货币权益交易,那么 PoW 的要求就会得到缓解。

  这一方案的核心思想是,矿工新生产的区块在一定时间内无法使用。更确切地说,这些硬币在挖矿过程中被锁定了一定数量的区块。该方案允许矿工在冻结一定数量的硬币一段时间的代价下进行挖矿。这是一种 PoS(权益证明)的类型。

  作为计算能力的备用支出,PoB 实际上是销毁一定数量的比特币,以获得相应的另类币。这在启动新的代币项目时通常被使用,作为一种公平分配的手段。这可以被看作是一种替代的挖矿方案,因为新币的价值来自于之前销毁了一定数量的硬币。

  该方案是 PoW 和 PoS 的混合体。在该方案中,区块最初是通过 PoW 产生的,然后每个区块会随机分配三个利益相关者来对其进行数字签名。后续区块的有效性取决于先前随机选择的区块成功签名的情况。

  然而,有一个可能的问题被称为“利益无所不利”问题,即一个人可以轻易创建一个区块链的分叉。这是可能的,因为在 PoW(工作量证明)中需要适当的计算资源来进行挖矿,而在 PoS 中没有这样的要求;因此,攻击者可以尝试使用相同的硬币在多个链上进行挖矿。

  这一难题的关键动机是抵抗挖矿池的发展。先前讨论过的挖矿池向所有参与者提供奖励,比例与他们消耗的计算能力成正比。然而,在这种模式中,挖矿池操作员是一个能够强制执行特定规则的中央当局,所有的奖励都归该操作员所有。此外,在此模式下,所有的矿工只信任彼此,因为他们共同致力于实现共同目标,希望挖矿池经理能获得奖励。非外包难题是一种允许矿工自己声称奖励的方案;因此,由于匿名矿工之间的内在不信任,挖矿池的形成变得不太可能。

  There are also various other alternative solutions to replace PoW, some of which are described in Chapter 1, Blockchain 101, and others will be explained in the subsequent chapters of this book, including Chapter 13, Hyperledger, and Chapter 16, Scalability and Other Challenges. Since this is an ongoing research field, new alternative solutions will continuously emerge with the development of blockchain technology.

  With the emergence of Bitcoin and alternative currencies, another concept of difficulty adjustment algorithm was introduced. In Bitcoin, the calculation of difficulty target is very simple, just as the following equation; however, other currencies either developed their own algorithms or implemented modified versions of the Bitcoin difficulty algorithm:

  T = Previous Time * Actual Time / 2016 * 10 Minutes

  The concept of difficulty adjustment in Bitcoin is that generating 2016 blocks should take approximately two weeks (about 10 minutes between blocks). If it takes more than two weeks to mine 2016 blocks, the difficulty will decrease, and if it takes less than two weeks to mine 2016 blocks, the difficulty will increase. When ASICs are introduced due to high block generation rates, the difficulty increases exponentially, which is a flaw in the non-ASIC protected PoW algorithm. This leads to the centralization of mining power.

  This also brings another problem; if a new cryptocurrency starts now, adopting the same SHA-256 based PoW as Bitcoin, malicious users can easily use ASIC miners to control the entire network. If there is not much interest in the new alternative currency, someone decides to consume a sufficient amount of computing resources to take over the network, this attack will be more realistic. If other miners with similar computing power also join the alternative currency network, this attack may not be feasible because miners will compete with each other.

  In addition, multi-pools also bring greater threats, as a group of miners can automatically switch to a profitable currency. This phenomenon is known as pool hopping, which can have adverse effects on the blockchain, thereby affecting the growth of alternative currencies. The impact of pool hopping on the network is detrimental because the jumpers only join the network when the difficulty is low and they can obtain quick rewards; once the difficulty increases (or is readjusted), they will leave and then rejoin after the difficulty is readjusted again.

  For example, if a multi-pool rapidly consumes resources to mine new currency, the difficulty will increase very quickly; when the multi-pool leaves the currency network, it will be almost unusable because the difficulty has now increased to a level that is no longer beneficial for independent miners and cannot be maintained. The only way to solve this problem is to initiate a hard fork, which is usually not desirable for the community.

  Some algorithms have emerged to solve this problem, and these algorithms will be discussed in the following chapters. All these algorithms are based on the idea of responding to changes in hash rate, including parameters such as the number of previous blocks, the difficulty of previous blocks, the adjustment ratio, and the amount by which the difficulty can be reduced or increased.

  In the following section, readers will be introduced to a few difficulty algorithms that are currently in use and proposed in various altcoins.

  This algorithm is used for adjusting difficulty in various altcoins. This method was first introduced in Megacoin and is used to adaptively adjust the difficulty of each block on the network. The logic of the algorithm is as follows:

  KGW = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228))

  The algorithm operates in a loop, calculating a new adjustment value through a set of predetermined blocks (PastBlockMass). The core idea of the algorithm is to develop an adaptive difficulty adjustment mechanism to respond to rapid fluctuations in hash rate. Kimoto Gravity Well (KGW) ensures that the time between blocks is roughly the same. In Bitcoin, difficulty is adjusted every 2016 blocks, but in KGW, difficulty is adjusted on each block.

  This algorithm is susceptible to the time warp attack, which allows attackers to temporarily enjoy lower difficulty when creating new blocks. This attack allows a time window where the difficulty is reduced, and attackers can quickly generate many coins at a faster rate.

  For more information, please refer to the link.

  Dark Gravity Wave (DGW) is a new algorithm designed to address certain flaws in the KGW algorithm, such as the time warp attack. This concept was initially introduced in Dash, previously known as Darkcoin. It utilizes multiple exponential moving averages and simple moving averages to achieve a smoother adjustment mechanism. The formula is as follows:

  2222222/ (((Difficulty+2600)/9)²)

  This formula has been implemented in Dash, Bitcoin SegWit2X, and various other altcoins as a mechanism for adjusting difficulty.

  Version 3.0 of DGW is the latest implementation of the DGW algorithm, which can achieve better difficulty adjustment compared to KGW.

  For more information, please refer to.

  This is another difficulty adjustment algorithm recently used in Zcash, which has been modified and tested appropriately. The algorithm calculates the time taken to generate previous blocks by looking at a fixed number of them, and then adjusts the difficulty to the previous block’s difficulty by dividing the actual time span by the average of the target time. In this scheme, the adjustment calculation is faster, and it recovers quickly from sudden increases or decreases in hash rate. This algorithm can prevent multipools, which could lead to rapid increases in hash rate.

  The network difficulty is adjusted each block or every minute depending on the implementation. The key innovation is a faster adjustment time relative to KGW.

  Zcash uses DigiShield v3.0, which adjusts difficulty using the following formula:

  (New Difficulty) = (Previous Difficulty) x SQRT [(150 seconds) / (time of last solution)]

  A detailed discussion of this issue can be found elsewhere.

  The Multi-Interval Difficulty Adjustment System (MIDAS) is a more complex algorithm than the ones previously discussed, as it uses more parameters. This method responds faster to sudden changes in hash rates. The algorithm can also prevent time distortion attacks.

  The original post about this matter can now be found through the Wayback Machine on the internet.

  Readers interested in more information can find it at the aforementioned location.

  This concludes our introduction to various difficulty adjustment algorithms.

  Many alternative cryptocurrencies and protocols have emerged, attempting to address the various limitations of Bitcoin.

  The various limitations of Bitcoin have also sparked interest in alternative currencies, which are specifically designed to address the limitations of Bitcoin. The most prominent and widely discussed limitation is the lack of anonymity in Bitcoin. We will now discuss some of the limitations of Bitcoin.

  Since the blockchain is the public ledger of all transactions and is publicly available, analyzing it becomes trivial. Combined with traffic analysis, transactions can be traced back to their source IP address, which may reveal the initiator of the transaction. From a privacy perspective, this is a significant issue.

  Even though it is suggested and commonly practiced in Bitcoin to generate a new address for each transaction to achieve a certain degree of unlinkability, this is not enough. Various technologies have been developed and successfully used to track the flow of transactions throughout the network and trace them back to their initiators. These technologies help link users to transactions by analyzing the blockchain through transaction graphs, address graphs, and entity graphs, thereby raising privacy concerns. The technologies mentioned in the aforementioned analysis can be further enriched by using publicly available transaction information and linking it to actual users. Open-source block analyzers are available for extracting transaction information, balances, and scripts from blockchain databases.

  A parser that can be used in the Rust language provides advanced blockchain analysis capabilities.

  Various proposals have been put forward to address the privacy issues of Bitcoin. These proposals can be divided into three categories: mixing protocols, third-party mixing networks, and inherent anonymity.

  A brief discussion of each category is as follows.

  These proposals are used to provide anonymity for Bitcoin transactions. In this model, a mixing service provider (intermediary or shared wallet) is used. Users send coins to this shared wallet as a deposit, and then, the shared wallet can send some other coins of the same value deposited by other users to the destination. Users can also receive coins sent by others through this intermediary. In this way, the link between input and output will no longer exist, and transaction graph analysis will not be able to reveal the actual relationship between the sender and the receiver.

  

  Three users combine their transactions into a single larger CoinJoin transaction.

  CoinJoin is an example of a mixing protocol where two transactions are merged into one transaction while keeping the inputs and outputs unchanged. The core idea behind CoinJoin is to build a shared transaction signed by all participants. This technology improves the privacy of all participants involved in the transaction.

  There are various third-party mixing services to choose from, but if the service is centralized, tracking the mapping between senders and recipients can be a threat because the mixing service knows all the inputs and outputs. Moreover, even completely centralized miners can bring the risk of the service administrator stealing coins.

  Various services based on CoinJoin (mixing) transactions vary in complexity, such as CoinShuffle, Coinmux, and Darksend in Dash (coin). CoinShuffle is a decentralized alternative to traditional mixing services because it does not require a trusted third party.

  However, there are some weaknesses in the CoinJoin-based solutions, the most prominent of which is that users may launch a denial-of-service attack. This is due to the fact that the users who initially promised to sign the transaction have not provided their signature, thus delaying or stopping the joint transaction.

  This category includes privacy coins, where privacy is built into the design of the currency. The most popular is Zcash, which achieves anonymity using zero-knowledge proofs (ZKP). Detailed discussions on this will be provided in the following chapters. Other examples include Monero, which provides anonymous services using ring signatures.

  The next section introduces various enhancement features that have been or are being proposed to expand the Bitcoin protocol.

  In the several protocols discussed below, some protocols have been proposed and implemented to enhance and expand the Bitcoin protocol, and to use it for various purposes other than just as an Online casino and How to find it.

  Colorful coins represent a method for indicating digital assets on the Bitcoin blockchain. Commonly referred to as coloring Bitcoin, it involves updating it with some metadata, which represents digital assets (smart assets). The coins still function as Bitcoin and operate, but carry additional metadata indicating certain assets. This can be some information related to the asset, some calculations related to transactions, or any arbitrary data. This mechanism allows for the issuance and tracking of specific bitcoins. Metadata can be recorded using Bitcoin’s opcodes or optionally in multi-signature addresses. If privacy issues need to be addressed, this metadata can also be encrypted. Some implementations also support storing metadata on publicly available seed networks, which means almost unlimited amounts of metadata can be stored. Typically, these are JSON objects representing various attributes of colorful coins. In addition, smart contracts are also supported. An example of such an implementation is Colu, which can be found here.

  Colored coins can be used to represent various assets, including but not limited to commodities, certificates, stocks, bonds, and votes. It should be noted that to use colored coins, a wallet that interprets colored coins is needed, while ordinary Bitcoin wallets do not work. Ordinary Bitcoin wallets cannot distinguish between colored coins and non-colored coins.

  You can set up a colored coin wallet online using the provided service. By using this service, you can create and issue any digital asset.

  The concept of colored coins is very attractive because it does not require any modification to the existing Bitcoin protocol and can utilize the existing secure Bitcoin network. In addition to traditional digital asset representation, it is possible to create smart assets that behave according to their defined parameters and conditions. These parameters include time verification, transfer restrictions, and fees.

  Important use cases can be the issuance of financial instruments on the blockchain. This will ensure low transaction fees, effective and mathematically secure ownership proof, quick transferability, and the ability to pay dividends to investors quickly without intermediaries.

  Rich APIs can be found for colored coins.

  This is another service for creating custom tokens that act as cryptocurrencies, which can be used for various purposes, such as issuing digital assets on the Bitcoin blockchain. It is a very powerful platform that is based on the Bitcoin blockchain but has developed its own client and other components to support the issuance of digital assets. The architecture includes Counterparty servers, counter block, counter wallet, and. Counterparty is based on the same idea as colored coins, embedding data into regular Bitcoin transactions but providing more efficient libraries and a set of powerful tools to support the processing of digital assets. This embedding is also known as embedded consensus because Counterparty transactions are embedded in Bitcoin transactions. The method of embedding data is using opcodes in Bitcoin.

  The currency produced and used by Counterparty is called XCP and is used as the fee for running contracts by smart contracts. At the time of writing, its price is 2.78 US dollars. XCP is created using the previously discussed PoB method.

  Counterparty allows the use of Solidity language to develop smart contracts on Ethereum and enables interaction with the Bitcoin blockchain. To achieve this, BTC Relay is used as a means to provide interoperability between Ethereum and Bitcoin. This is a clever concept where Ethereum contracts can communicate with the Bitcoin blockchain and transactions. The relay (nodes running BTC Relay) obtain Bitcoin block headers and transmit them to smart contracts on the Ethereum network, verifying PoW. This process verifies that a transaction has occurred on the Bitcoin network.

  Available here.

  Technically speaking, this is an Ethereum contract that can store and verify Bitcoin block headers, just like the Bitcoin Simple Payment Verification lightweight client uses a Bloom filter. SPV clients have been discussed in detail in the previous chapters. This idea can be visualized with the following chart:

  

  BTC Relay Concept

  Counterparty can be found here.

  From a coding perspective, it is very quick to start an altcoin project by simply forking the source code of Bitcoin or another coin, but this may not be enough. When launching a new coin project, several things need to be considered to ensure a successful launch and the long-term existence of the coin. Typically, the codebase is written in C++, as in the case of Bitcoin, but almost any language can be used to develop a coin project, such as Golang or Rust.

  Writing code or forking the code of an existing coin is a trivial matter, the challenging issue is how to launch a new currency to attract investors and users. Typically, the following steps are taken to launch a new coin project.

  From a technical perspective, if a fork is made from the code of another coin, such as Bitcoin, there are various parameters that can be changed to effectively create a new coin. To create a new coin, these parameters need to be adjusted or introduced. These parameters can include but are not limited to the following.

  There are multiple consensus algorithms to choose from, such as PoW used in Bitcoin or PoS used in Peercoin. There are also other available algorithms, such as Proof of Capacity (PoC) and other algorithms, but PoW and PoS are the most common choices.

  This can be SHA-256, Scrypt, X11, X13, X15, or any other hash algorithm suitable for use as a consensus algorithm.

  There are many choices in this field that can provide a difficulty realignment mechanism. The most prominent examples are KGW, DGW, Nite’s Gravity Wave, and DigiShield. In addition, all these algorithms can be adjusted as required to produce different results; therefore, there may be many variants.

  This is the time that passes between the generation of each block. For Bitcoin, blocks are generated every 10 minutes, and for Litecoin, every 2.5 minutes. Any value can be used, but the appropriate value is usually a few minutes; if the generation time is too fast, it may make the blockchain unstable, and if too slow, it may not attract many users.

  The block reward is given to miners who solve the mining puzzles, and they are allowed to own a coinbase transaction containing the reward. Bitcoin originally started with 50 coins, and now many altcoins set this parameter to very high numbers; for example, Dogecoin is currently set to 10,000.

  This is another important factor; in Bitcoin, it halves every 4 years, now set to 12.5 bitcoins. This is a variable number that can be set to any time period or not set at all.

  This is another important factor in determining the transaction rate on the network. The block size limit in Bitcoin is 1 MB, but in alternative currencies, it can change according to demand.

  This property only applies to PoS systems, in which the owners of the currency can earn interest at a rate defined by the network, in exchange for retaining some currency on the network as collateral to protect the network. This rate can control inflation. If the rate is too low, it may lead to hyperinflation.

  This parameter defines how long the currency must remain unused before it becomes eligible for collateral.

  This number sets the total limit of currency that can be generated. For example, in Bitcoin, the limit is 21 million, while in Dogecoin it is infinite. This limit is fixed by the block reward and halving schedule discussed earlier.

  There are two choices for creating your own Online casino and How to find it: forking the existing established cryptocurrency source code or starting from scratch. The latter option is less popular, but the former is easier, and has allowed for the creation of many Online casino and How to find it in the past few years. Essentially, the approach is to first fork the cryptocurrency source code, then make appropriate changes at different strategic locations in the source code to effectively create a new currency. NEM coin is one of the newly created coins that were written from scratch.

  In the next section, readers will be introduced to some alternative currency projects. This chapter cannot cover all alternative currencies, but some selected coins will be discussed in the next section. The selection is based on their long-term viability, market value, and innovation. Each coin is discussed from different perspectives, such as theoretical foundation, trading, and mining.

  Namecoin is the first fork of Bitcoin’s source code. The key idea behind Namecoin is not to create an alternative currency, but to provide improved decentralized, censorship-resistant, private, secure, and faster decentralized naming. The decentralized naming service aims to address the inherent limitations of the Domain Name System (DNS) protocol used on traditional internet, such as slow and centralized control. Namecoin is also the first solution to the Zooko Triangle problem, which has been briefly discussed in Chapter 1, Blockchain 101.

  Namecoin is mainly used to provide services for registering key/value pairs. One of the main use cases of Namecoin is that it can provide a blockchain-based, distributed, and decentralized consensus-driven TLS certificate verification mechanism.

  It is based on the same technology as Bitcoin, but has its own blockchain and wallet software.

  The core source code of Namecoin can be obtained.

  In summary, Namecoin provides the following three services:

  Ensure the security of storage and transmission of the name (key)

  Attach some values to the name, up to 520 bytes of data can be appended

  生产lottery and How to find it (Namecoin)

  Namecoin 还首次引入了合并挖矿,这允许矿工同时在多个链上进行挖矿。这个想法很简单,但非常有效:矿工创建一个 Namecoin 区块并生成该区块的哈希。然后将该哈希添加到比特币区块中,并且矿工解决该区块的难度等于或大于 Namecoin 区块难度,以证明已经为解决 Namecoin 区块做出了足够的工作。

  Coinbase 交易用于在 Namecoin 的交易哈希(或任何其他山寨币,如果与该币种合并挖矿)中包含哈希。挖矿任务是解决比特币区块,其 coinbase 包含对 Namecoin(或任何其他山寨币)区块的哈希指针。如下图所示:

  

  合并挖矿可视化

  如果矿工设法以比特币区块链难度水平解决哈希,则比特币区块建立并成为比特币网络的一部分。在这种情况下,比特币区块链会忽略 Namecoin 哈希。另一方面,如果矿工以 Namecoin 区块链难度水平解决一个区块,则在 Namecoin 区块链中将创建一个新区块。该方案的核心优势在于,矿工所花费的所有计算能力都有助于保护 Namecoin 和比特币。

  截至 2018 年 3 月,Namecoin 的当前市值为 29143884 美元,可在购买和出售。可在各种交易所进行交易,例如:

  即使 Namecoin 可以独立挖矿,通常也会通过利用合并挖矿技术作为比特币的一部分进行挖矿。这样,Namecoin 可以作为比特币挖矿的副产品。正如前面所述的难度图表所表明的,独立挖矿已经不再有利可图;相反,建议使用合并挖矿,使用矿池,甚至使用加密货币交易所购买 Namecoin。

  

  Namecoin 难度如下所示:https://bitinfocharts.com/comparison/difficulty-nmc.html(自 2016 年 12 月以来)

  各种挖矿池,比如,也提供合并挖矿的选项。这允许矿工主要挖掘比特币,同时也因此获得 Namecoin。

  另一种快速获得一些 Namecoins 的方法是用你已有的硬币与 Namecoins 交换,例如,如果你已经有一些比特币或其他可以用来与 Namecoin 交换的加密货币。

  一个在线服务,,可提供此服务。该服务允许使用简单易用的界面从一种加密货币转换为另一种加密货币。

  For example, pay BTC to receive NMC as shown below:

  First, select the deposit currency, which is Bitcoin in this example, then select the currency to be received, which is Namecoin in this example. In the top edit box, enter the Namecoin address where you wish to receive the exchanged Namecoin. In the second edit box at the bottom, enter the Bitcoin refund address, where the currency will be returned to this address in case of transaction failure.

  Once the deposit and exchange currencies are selected, the exchange rate and miner fee will be calculated immediately after the selection. The exchange rate is driven by market conditions, while the miner fee is calculated based on the selected target currency and the miner fee algorithm of the target network.

  

  Bitcoin to Namecoin exchange

  After clicking ‘Start Transaction’, the transaction begins and instructs the user to send Bitcoin to a specific Bitcoin address. When the user sends the required amount, the conversion process is as shown in the following screenshot. The entire process takes a few minutes:

  

  Namecoin delivery notification

  The previous screenshot shows that after sending the deposit, the exchange occurs, and the final message “All Done!” is displayed, indicating a successful exchange.

  The page displays some other order details, such as the deposited currency and the currency received after the exchange. In this case, it is a Bitcoin to Namecoin exchange. It is worth noting that the relevant addresses are also displayed below each currency icon. There are also some other options, such as calling a receipt email to receive the transaction receipt.

  At the completion of the process, you can view the transaction in the Namecoin wallet as shown below:

  

  Namecoin wallet

  Confirmation of the transaction may take some time (usually about 1 hour), during which it is impossible to use Namecoins to manage the name. Once Namecoins are available in the wallet, you can use the ‘Manage Name’ option to generate Namecoin records.

  Namecoin records are in the form of key-value pairs. The name is a lowercase string in the form of , and the value is a case-sensitive, UTF-8 encoded JSON object with a maximum length of 520 bytes. The name should comply with the provisions of RFC1035().

  A general Namecoin name can be any binary string up to 255 bytes long, accompanied by 1024 bits of related identification information. A record on the Namecoin blockchain only needs to be updated after approximately 200 days or 36,000 blocks. Namecoin also introduces top-level domains that can be registered with Namecoin and can be browsed using a dedicated Namecoin-enabled resolver. As shown in the figure below, the Namecoin wallet software can be used to register domains.

  After entering the name, click the submit button, and you will be required to enter configuration information such as DNS, IP, or identity:

  

  Namecoin wallet: Domain configuration

  As shown in the following screenshot, it will be registered on the Namecoin blockchain as:

  

  Namecoin wallet: Display registered names

  Litecoin is a fork from the Bitcoin source code released in 2011. It uses Scrypt as PoW and was first introduced in the Tenebrix coin. Due to the faster block generation time of 2.5 minutes, Litecoin allows faster transactions than Bitcoin. In addition, due to the faster block generation time, the difficulty adjustment is performed approximately every 3.5 days. The total supply of currency is 84 million.

  Scrypt is the first sequential memory hard function to replace the SHA-256-based PoW algorithm. It was initially proposed as a password-based key derivation function (PBKDF). The key idea is that if the function requires a large amount of memory to run, then custom hardware such as ASICs will require more VLSI area, which will not be built. The Scrypt algorithm needs to save a large array of pseudo-random bits in memory and derive the key in a pseudo-random way from it.

  The algorithm is based on a phenomenon called time-memory trade-off (TMTO). If the memory requirements are relaxed, the computational cost increases. In other words, if more memory is given to the program, TMTO will shorten its running time. This trade-off makes it difficult for attackers to obtain more memory, as it is both expensive and difficult to implement on custom hardware, or if the attacker chooses not to increase memory, the algorithm runs slowly due to high processing requirements. This means that ASICs are difficult to build for this algorithm.

  Scrypt generates the derived key (Kd) using the following parameters:

  Password: This is the character string to be hashed

  Salt: This is the random string provided to the Scrypt function (usually all hash functions) to defend against brute-force dictionary attacks using rainbow tables.

  N: This is the memory/CPU cost parameter that must be a power of 2 greater than 1.

  P: This is the parallelization parameter.

  R: This is the block size parameter.

  dkLen: This is the expected length of the derived key, in bytes.

  Formally, this function can be written as:

  Kd = scrypt (P, S, N, P, R, dkLen)

  Before applying the Scrypt core function, the algorithm takes P and S as input and applies PBKDF2 and HMAC based on SHA-256. The output is then fed into an algorithm called ROMix, which internally uses the Blockmix algorithm to fill memory with the Salsa20/8 core stream cipher, requiring large memory to run, thereby achieving sequential memory hard properties.

  该算法的此步骤的输出最终再次馈送到 PBKDF2 函数中,以产生派生密钥。该过程如下图所示:

  

  Scrypt 算法

  Scrypt 在特定参数下用于莱特币挖矿,其中 N= 1024,R = 1,P=1,S = 随机 80 字节 生成 256 位输出。

  看起来,由于选择了这些参数,为莱特币挖矿的 Scrypt ASIC 的开发并不是非常困难。在用于莱特币挖矿的 ASIC 中,可以开发出一种顺序逻辑,将数据和随机数作为输入,并应用带有 HMAC-SHA256 的 PBKDF2 算法;然后将结果比特流输入到产生哈希的 SALSA20/8 函数中,该哈希再次馈入到 PBKDF2 和 HMAC-256 函数中以产生 256 位哈希输出。与比特币 PoW 的情况类似,在 Scrypt 中,如果输出哈希小于目标哈希(已在开始时作为输入传递,并存储在内存中,并在每次迭代中检查),则函数终止;否则,随机数递增,然后再次重复该过程,直到找到低于难度目标的哈希。

  

  Scrypt ASIC 设计简化流程图

  莱特币交易: 与其他货币一样,莱特币的交易可以在各种在线交易所轻松进行。莱特币的当前市值为 10448974615 美元。莱特币的当前价格(截至 2018 年 3 月)为每个莱特币 188.04 美元。

  挖矿: 莱特币的挖矿可以单独进行,也可以在矿池中进行。目前,常用于挖掘莱特币的 ASIC 可用。

  使用 CPU 进行 Litecoin 挖矿已经不再盈利,就像现在许多其他lottery and How to find it 一样。现在有在线云挖矿提供商和可用的 ASIC 挖矿机,可以用来挖掘 Litecoin。Litecoin 挖矿从 CPU 开始,经过 GPU 挖矿机的发展,最终现在已经达到了一个点,需要使用专门的 ASIC 挖矿机,例如 Ehsminer 的 ASIC Scrypt Miner Wolf,以期能够获得一些硬币。一般来说,即使使用 ASIC,也最好在矿池中进行挖矿,而不是独立挖矿,因为由于矿池采用的比例奖励方案,独立挖矿并不像在矿池中挖矿那样有盈利。这些矿工能够为 Scrypt 算法产生 2 Gh/s 的哈希速率。

  Software source code and wallet: The source code of Litecoin can be obtained from . Litecoin wallets can be downloaded from and can be used like the Bitcoin Core client software.

  Primecoin is the first on the market to introduce a useful PoW lottery and How to find it, compared to Bitcoin’s SHA256-based PoW. Primecoin uses the search for primes as PoW. Not all types of primes meet the requirements for being selected as PoW. Three types of primes (known as first-class Cunningham chains, second-class Cunningham chains, and twin chains) meet the requirements for the use of PoW algorithms in cryptocurrencies.

  The Primecoin blockchain dynamically adjusts the difficulty through a continuous difficulty assessment scheme. The efficient verification of the prime-based PoW is also very important, as if the verification speed is slow, then the PoW is not applicable. Therefore, prime chains are selected as PoW because it becomes more difficult to find prime chains as the chain grows, while the verification remains fast enough to be used as an efficient PoW algorithm.

  Once the PoW is verified on a block, it cannot be reused on another block, which is very important. In Primecoin, this is achieved by hashing the PoW certificate with the parent block header in the sub-block.

  Proof-of-Work (PoW) certificates are generated by linking prime chains to the block header hash. It also requires that the origin of the block header can be divided by the block header hash. If possible, perform the division operation and then use the quotient as the PoW certificate. Another adjustable difficulty attribute of the PoW algorithm is that difficulty adjustment is introduced for each block, rather than every 2,016 blocks like Bitcoin. This is a more stable method that can readjust in the event of a sudden increase in hashing power. In addition, the total number of coins produced is driven by the community, and there is no clear limit to the number of coins that Primecoin can generate.

  Primecoin can be traded on major online casinos and exchanges. As of the time of writing this article (March 2018), the current market value of Primecoin is $17,482,507. Although not large, due to its innovative idea and a dedicated community support, it still maintains a certain market share.

  

  A chart showing related statistical data of Primecoin

  Data source: https://coinmarketcap.com/currencies/primecoin/

  The first step is to download a wallet. Primecoin supports local mining within the wallet, just like the original Bitcoin client, but it can also mine in the cloud through various online cloud service providers.

  The following is a quick Windows guide; the Linux client can also be obtained at .

  The first step is to download the Primecoin wallet from

  Once the wallet is installed and synchronized with the network, mining can be started by following the following steps. You can open the debug window in the Primecoin wallet by clicking on the Help menu and selecting the Debug Window menu item. In the console window of the debug window, you can type to call other help that enables the Primecoin mining feature:

  

  Primecoin mining

  Once the aforementioned command is successfully executed, mining will begin in single-machine mode. If you are using a personal computer with lower configuration and a slow CPU, this may not be very fast or profitable, but since this is a cryptocurrency that uses CPU mining, miners can use personal computers equipped with powerful CPUs. Alternatively, cloud services with powerful server hardware can be used:

  

  Primecoin wallet software, synchronized with the network

  The Primecoin source code can be obtained at.

  Primecoin is a novel concept that introduces a PoW with significant scientific significance. It is still in use, with a market value of $17,034,198, but it can be seen from GitHub’s inactivity that no further development is being carried out.

  Readers can further explore Primecoin by reading the Primecoin white paper by Sunny King (pseudonym).

  Zcash was launched on October 28, 2016. It is the first currency to provide complete privacy to users using a specific type of ZKPs (known as Zero-Knowledge Succinct Non-Interactive Argument of Knowledge, ZK-SNARKs). These proofs are concise and easy to verify; however, setting up initial public parameters is a complex process. This process includes two keys: the proof key and the verification key. It requires sampling some random numbers to construct the public parameters. The problem lies in these random numbers, also known as toxic waste, which must be destroyed after parameter generation to prevent forgeries of Zcash.

  For this purpose, the Zcash team proposed a multi-party computation protocol that can collaborate from independent positions to generate the required public parameters to ensure that no toxic waste is produced. Since these public parameters need to be created by the Zcash team, this means that the participants in the ceremony are trusted. This is why the ceremony is very open and is carried out by using the multi-party computation mechanism.

  This mechanism has a property that one must destroy all participants in the ceremony to destroy the final parameters. When the ceremony is completed, all participants will destroy the devices used to generate the private key. This action eliminates any traces of the participants’ private key part on the device.

  ZK-SNARKs must satisfy the properties of completeness, accuracy, succinctness, and non-interactivity. Completeness means that there is a clear strategy that allows the prover to satisfy the verifier’s assertion of truth. On the other hand, accuracy means that no prover can convince the verifier that a false statement is true. Succinctness means that the size of the messages passed between the prover and the verifier is small.

  Finally, the non-interactive nature means that the correctness of assertions can be verified without any interaction or very little interaction. Additionally, as a zero-knowledge proof, it also needs to satisfy the zero-knowledge property (discussed in Chapter 6, public key cryptography).

  Zcash developers introduced the concept of a decentralized anonymous payment scheme (DAP scheme) that is used to achieve direct and private payments in the Zcash network. Transactions do not reveal any information about the source, destination, or amount of the payment. Zcash has two types of addresses, Z addresses and T addresses. Z addresses are based on ZKPs and provide privacy protection, while T addresses are similar to Bitcoin addresses. The following is a snapshot of various attributes of Zcash (after the initial slow start):

  

  Zcash Attribute Summary

  Zcash utilizes an efficient Proof of Work (PoW) scheme named Equihash, which is based on the general birthday problem. It allows for very efficient verification. This is a memory-hard algorithm, resistant to ASICs. Zcash introduces a novel concept (initial slow mining), which means that block rewards will gradually increase over a period of time until reaching the 20,000th block. This allows the network to perform initial expansion and early miner experimentation, and can be adjusted by Zcash developers as needed. Due to scarcity, the slow start has had an impact on the price, and therefore ZEC reached approximately 25,000 US dollars on the first day of its launch. Zcash implements a slightly modified DigiShield difficulty adjustment algorithm. The formula is as follows:

  (下一个难度) = (上一个难度) x 根号 [ (150 秒) / (上一个解决时间) ]

  Zcash 可以在 CryptoGo () 等主要lottery and How to find it 交易所购买。另一个可以购买或出售 Zcash 的交易所是 Crypto Robot 365 ()。Zcash 推出时价格非常高。如下图所示,价格一度飙升至每个 Zcash 约十个比特币。一些交易所的订单甚至高达 2,500 BTC 每个 ZEC。撰写时(2018 年 3 月)ZEC 的价格约为 311 美元:

  

  Zcash 市值和价格

  有多种方法可以挖掘 Zcash。目前,CPU 和 GPU 挖掘都是可能的。各种商业云挖矿池还提供挖掘 Zcash 的合约。要在 Ubuntu Linux 上使用 CPU 进行独立挖掘,可以按照以下步骤进行:

  第一步是使用以下命令安装先决条件:

  如果先决条件已安装,将显示一条消息,指示组件已是最新版本。如果尚未安装或版本旧于最新包,则安装将继续,将下载所需软件包,并完成安装。

  接下来,根据以下截图中所示的命令从 Git 克隆 Zcash:

  请注意,如果您是第一次运行 ,则可能需要接受一些配置更改,这些更改将自动完成,但您可能需要进行交互式操作。

  此命令将在本地克隆 Zcash Git 仓库。输出如下所示的截图:

  

  克隆 Zcash Git 仓库

  下一步是通过以下命令下载证明和验证密钥:

  此命令将产生与此处所示相似的输出:

  The failure to save external link images, the source site may have anti-hotlinking mechanisms, it is recommended to save the image directly and upload it.

  Zcash 设置获取 ZK-SNARK 参数

  运行此命令后,将下载约 911 MB 的密钥到目录中。该目录包含用于证明和验证密钥的文件:

  一旦前述命令成功完成,就可以使用以下命令构建源代码:

  这将产生非常长的输出;如果一切顺利,将产生一个二进制文件。请注意,此命令将作为参数,基本上是一个查找系统中核心或处理器数量并显示该数字的命令。如果您没有该命令,则将替换为系统中的处理器数量。

  构建完成后,下一步是配置 Zcash。这通过在目录中创建名为的配置文件来实现。

  示例配置文件如下所示:

  前述配置启用了各种功能。第一行添加了主网节点并启用了主网连接。和是 RPC 接口的用户名和密码。用于启用挖矿。是可用于挖矿的处理器数量。最后一行启用了更快的挖矿求解器;如果要使用标准 CPU 挖矿,则不需要此项。

  现在可以使用以下命令启动 Zcash:

  启动后,可以通过命令行界面与 RPC 接口进行交互。这几乎与比特币命令行界面相同。一旦 Zcash 守护进程启动并运行,可以运行各种命令来查询 Zcash 的不同属性。可以使用 CLI 或区块链浏览器在本地查看交易。

  Zcash 的区块链浏览器位于:。

  可以使用以下命令生成新的 Z 地址:

  使用带有参数运行命令会产生以下截图中显示的输出。它显示了诸如、和之类的有价值信息:

  The failure to save external link images, the source site may have anti-hotlinking mechanisms, it is recommended to save the image directly and upload it.

  显示 getinfo 输出的截图

  可以使用以下命令生成新的 T 地址:

  除了 CPU 挖矿外,还提供了 GPU 挖矿选项。目前尚无官方 GPU 矿工;然而,开源开发人员已经制作了各种概念验证和可用的矿工。Zcash 公司举办了一场公开竞赛,鼓励开发人员构建并提交 CPU 和 GPU 矿工。截至撰写时尚未宣布获奖者。

  读者可以通过访问网站获取更多信息。

  还有另一种挖矿方式:使用来自各种在线云挖矿提供商提供的云挖矿合约。云挖矿服务提供商代表客户进行挖矿。除了云挖矿合约,矿工还可以使用自己的设备通过矿池使用 stratum 或其他协议进行挖矿。一个重要的例子是 NiceHash 提供的 Zcash 矿池,链接在:。使用该矿池,矿工可以出售他们的哈希功率。

  下图显示了在 Zcash 挖矿矿池上构建并使用 CPU 矿工的示例。

  可以使用以下步骤在 Ubuntu Linux 发行版上下载和编译:

  所有步骤都成功完成后,可以使用以下命令运行:

  的版本可在以下链接下载,适用于 Windows 和 Linux 系统:

  需要多个参数,如位置()、用户名()和用于挖矿的线程数()。

  下图显示了在 Linux 上运行 Zcash 的样本。在此截图中,支付是以比特币地址进行的,用于出售哈希功率:

  

  Receiving payments for selling hash power using BTC address

  The screenshot displayed here shows a sample running situation of running on Windows and sending payments to a Zcash T address:

  

  Receiving payments for selling hash power using Zcash T address

  Zcash uses zero-knowledge proof technology in an innovative way and paves the way for future applications that require inherent privacy, such as banking, medicine, or law.

  This section introduces the introduction of Zcash; readers can explore more information about Zcash online.

  ICOs are similar to Initial Public Offerings (IPOs). Just as IPOs are launched by companies to raise funds, ICOs are launched to raise funds for startup projects. The key difference is that IPOs are regulated and belong to the category of the securities market (company shares), while ICOs are not regulated and do not belong to any strict category of established market structures.

  However, given the recent fraudulent ICO schemes launched in the past few months and the growing concerns about investor protection, some suggestions consider ICOs should be regarded as securities. Recently, the Securities and Exchange Commission (SEC) proposed that all coins, ICOs, and digital assets should be defined as securities. This means that the laws applicable to ICOs, Bitcoin, and other digital coins will be the same as those applicable to securities. In addition, formal ‘Know Your Customer’ (KYC) and ‘Anti-Money Laundering’ (AML) are also suggested to address money laundering issues. Experts suggest the Howey test as some standards for considering any ICO as a security.

  Another distinction is that ICOs typically require investors to invest in cryptocurrencies and pay returns in cryptocurrencies, most commonly in the new tokens (new cryptocurrencies) introduced by the ICO. It can also be in fiat currency, but it is most common to use cryptocurrencies. For example, in the Ethereum crowdfunding campaign, a new token Ether was introduced. The term token auction crowdfunding is also very popular, and these two terms can be used interchangeably. ICOs are also known as crowdfunding sales.

  When a new blockchain-based application or organization is launched, a new token can be issued simultaneously as a credential for accessing and using the application, and this token can be publicly exchanged for established cryptocurrencies (such as Bitcoin or Ether) or fiat currency. The advantage is that as the usage of the application or product increases, the value of the new token will also increase. This will give investors who initially invested a good incentive.

  In 2017, ICO has become the main tool for startups to raise capital. The first successful ICO was Ethereum, which raised 18 million US dollars in 2014. The most recent successful case is Tezos, which raised 232 million US dollars in a few weeks. Another example is Filecoin, which raised over 250 million US dollars.

  The process of creating new tokens on the Ethereum blockchain has been standardized, making it relatively easy to launch an ICO and exchange new tokens for Ether, Bitcoin, or other cryptocurrencies. This standard is called ERC20, which will be described in detail in the next section. It is worth noting that using ERC20 is not mandatory; one can completely create a new cryptocurrency on a new blockchain to launch an ICO, but recently, many ICOs have used ERC20, providing a relatively simple way to build tokens for ICOs.

  Recently, ICOs are also offered on platforms outside of Ethereum, such as NEM () and Stellar ().

  The ERC20 token is an interface that defines various functions and specifies the requirements for tokens. However, it does not provide implementation details, leaving it to the implementers to decide. ERC is an abbreviation for Ethereum Improvement Proposal, similar to BIPs for Bitcoin, used to propose improvements to the Ethereum blockchain.

  This is defined under EIP 20, and you can read more information here: .

  Due to the ability to create new tokens and the ERC20 standard, Ethereum is becoming the choice platform for ICOs, making it more accessible.

  The ERC20 token standard defines various functions that describe the various attributes, rules, and characteristics of new tokens. These include the total supply of currency, the total balance of holders, transfer functions, approval, and authorization functions.

  Other standards such as ERC223, ERC777, and ERC20 extensions called ERC827 are also under development.

  You can refer to the following links for more information:

  In this chapter, we introduce the entire cryptocurrency field to you. We discuss many alternative currencies in detail, especially Zcash and Namecoin. Cryptocurrency is a very active research field, especially around scalability, privacy, and security. Some research has also been conducted to invent new difficulty adjustment algorithms to prevent the centralization threat of cryptocurrencies.

  Further research is needed in the field of privacy and, particularly, the scalability of blockchain.

  Now you should be able to understand the token concept and the various motivations behind it. We also discuss some practical aspects, such as mining and launching new currency projects, which we hope will lay a solid foundation for you to further explore these areas. Tokens are an intriguing research field that opens up many possibilities for the decentralized future.

  This chapter introduces the development tools, languages, and frameworks used for Ethereum smart contract development. We will explore different methods for developing Ethereum blockchain smart contracts. We will discuss the various structures of Solidity language in detail, which is currently the most popular development language for Ethereum smart contract development.

  This chapter will introduce the following topics:

  Development tools, integrated development environments, and clients

  Remix

  Ganache

  EthereumJS

  TestRPC

  MetaMask

  Truffle

  Prerequisites

  Node

  Node package manager (NPM)

  Other tools and utilities

  There are many tools that can be used for Ethereum development. The following diagram shows the classification of various development tools, clients, integrated development environments, and development frameworks for Ethereum:

  

  Classification of components of the Ethereum development ecosystem

  The above classification does not include all the frameworks and tools used for Ethereum development. It shows the most commonly used tools and frameworks, which are also the tools and frameworks we will use in this chapter.

  There are many resources related to Ethereum development tools that can be found at the following address:.

  The main focus of this chapter will be on Geth, Remix IDE, Solidity, Ganache, MetaMask, solc, and Truffle. Other elements, such as prerequisites (Node), will also be briefly discussed.

  Smart contracts on the Ethereum blockchain can be programmed in multiple languages. There are five languages that can be used to write contracts:

  Mutan: This is a language similar to Go, which was abandoned at the beginning of 2015 and is no longer used.

  LLL: This is a low-level Lisp-like language, hence the name LLL. It is no longer used.

  Serpent: This is a simple, clean language similar to Python. It is no longer used for contract development and no longer supported by the community.

  Solidity: This language has become the standard for almost all Ethereum contracts written. This chapter will focus on this language and will be discussed in detail in subsequent chapters.

  Vyper: This language is an experimental language similar to Python, designed to bring security, simplicity, and auditability to smart contract development.

  Compilers are used to convert the advanced contract source code into a format that the Ethereum execution environment can understand. The Solidity compiler is the most commonly used one and will be discussed here.

  solc converts the advanced Solidity language to Ethereum Virtual Machine (EVM) bytecode, so that it can be executed by the EVM on the blockchain.

  solc can be installed on the Linux Ubuntu operating system using the following command:

  If the PPA has not been installed, you can install them by running the following command:

  To verify the existing version of solc and check if it is installed, you can use the following command:

  To install solc on macOS, please execute the following command:

  solc supports various features. Some examples are shown below:

  Display the contract in binary format:

  This command will generate output similar to the following. This shows the binary translation content.

  Contract code:

  

  Binary output of the Solidity compiler

  Estimate gas:

  This will produce the following output:

  

  Estimate gas using solc

  Generate ABI:

  The following is the content of

  Compile:

  Another useful command to compile and generate a binary compilation file and an ABI, as follows:

  This command will generate two files in the output directory

  : This includes the Application Binary Interface of the smart contract, represented in JSON format

  : This includes the binary representation of the smart contract code

  The output of the two files is displayed in the following screenshot:

  

  ABI and binary output of the Solidity compiler

  ABI stands for Application Binary Interface. ABI encodes information about the functions and events of smart contracts. It acts as an interface between EVM-level bytecode and high-level smart contract program code. External programs need ABI and the address of the smart contract to interact with smart contracts deployed on the Ethereum blockchain.

  solc is a very powerful command that can be used with the flag to explore more options, which will display detailed options. However, the aforementioned commands for compiling, ABI generation, and gas estimation should be sufficient for most development and deployment needs.

  There are various IDEs available for Solidity development. Most IDEs can be used online and presented through a web interface. Remix (formerly known as Browser Solidity) is the most commonly used IDE for building and debugging smart contracts. Let’s discuss it.

  Remix is a web-based environment for developing and testing contracts using Solidity. It is a feature-rich IDE that does not run on a real-time blockchain; in fact, it is a simulation environment where contracts can be deployed, tested, and debugged.

  It can be found at:

  The example interface is as follows:

  The failure to save external link images, the source site may have anti-hotlinking mechanisms, it is recommended to save the image directly and upload it.

  Remix IDE

  On the left, there is a code editor with syntax highlighting and code formatting, and on the right, there are many tools available for deployment, debugging, testing, and interacting with contracts.

  Various features can be used, such as transaction interaction, options to connect to a JavaScript VM, configuration of the execution environment, debugger, formal verification, and static analysis. They can be configured to connect to an execution environment, such as a JavaScript VM, injected Web3——Mist, MetaMask, or similar environments that provide execution environments——or Web3 providers, which allow connection to locally running Ethereum clients (such as ) via IPC or RPC over HTTP (Web3 provider endpoints).

  Remix also has a debugger for EVM, which is very powerful and can be used to perform detailed level tracing and analysis of EVM bytecode. Here is an example:

  

  Remix IDE, debugging

  The above screenshot shows different elements of the Remix IDE. The top left corner shows the source code. Below is the output log, which shows information messages and data related to the compilation and execution of contracts.

  The following screenshot shows more details of the Remix Debugger. It decodes source code into EVM instructions. Users can step through each instruction and can check the effect of the source code when executed:

  

  Remix Debugger

  There are various tools and libraries available for Ethereum. The most common are discussed here.

  In this section, we will first install the prerequisites for developing Ethereum applications. The first requirement is Node, which will be seen next.

  Since most tools and libraries require Node, you can install it using the following command:

  Sometimes, it is impossible to test on the test network, and the main network is obviously not the place to test contracts. Setting up a private network can sometimes be very time-consuming. When a quick test is needed and there is no suitable test network, EthereumJS’s TestRPC is very convenient. It simulates the behavior of the Ethereum client using EthereumJS and allows for faster development testing. TestRPC can be obtained as a Node software package.

  Before installing TestRPC, Node should already be installed, and the package manager should be available.

  You can install TestRPC using the following command:

  To start, simply issue this command and run it in the background, then open another terminal to handle contracts:

  When TestRPC is running, it will display an output similar to the following screenshot. It will automatically generate ten accounts and private keys, as well as an HD wallet. It will start listening for incoming connections on TCP ports.

  

  TestRPC

  Ganache is the latest addition to the many development tools and libraries developed for Ethereum. This is to some extent a substitute for TestRPC, using a user-friendly graphical user interface to view transactions and blocks as well as related details. It is a fully functional personal blockchain enabled with Byzantium, used to provide a local testing environment for the blockchain.

  Ganache is a JavaScript implementation of the Ethereum blockchain, with built-in block explorer and mining functionality, making it very easy to test locally on the system.

  As shown in the following screenshot, you can view transactions, blocks, and addresses in detail on the front end:

  

  Ganache, a personal Ethereum blockchain

  Ganache can be downloaded.

  MetaMask allows interaction with the Ethereum blockchain through Firefox and Chrome browsers. It injects an object into the JavaScript environment of the running website, thereby enabling immediate interface functionality for DApps. This injection allows DApps to interact directly with the blockchain.

  It can be obtained.

  MetaMask also allows account management. This acts as a verification method before any transaction is executed on the blockchain. Users will see a secure interface to review the transaction, then approve or reject it before it reaches the target blockchain.

  It can be obtained.

  

  MetaMask

  It allows connection to various Ethereum networks, as shown in the following screenshot. This is a screenshot of MetaMask that allows users to select their preferred network:

  

  MetaMask Network as shown in the MetaMask user interface

  An interesting feature worth noting is that MetaMask can also connect to any custom RPC, which allows you to run your own blockchain, such as a local or remote private network, and allows your browser to connect to it. It can also be used to connect to locally running blockchains like Ganache and TestRPC.

  MetaMask allows account management and records all transactions of these accounts. This is shown in the following screenshot:

  

  MetaMask Account and Transaction View

  Truffle (available on) is a development environment that makes testing and deploying Ethereum contracts easier and simpler. Truffle provides contract compilation and linking, as well as an automated testing framework using Mocha and Chai. It also makes it easier to deploy contracts to any private network, public network, or test network Ethereum blockchain. In addition, it provides an asset pipeline that processes all JavaScript files so that they can be used by browsers.

  Before installation, if available, you can query as shown below. If not available, you will first need to install it before you can install:

  Installation is very simple and can be completed using the following command through Node Package Manager (npm):

  This will take a few minutes; after installation, you can use the command to display the help information and verify that it is correctly installed:

  Enter in the terminal to display the usage help:

  This will display the following output:

  

  Truffle Help

  Alternatively, the repository can be found on, and it can be cloned locally to install. The following command can be used to clone the repository using Git:

  Developing and deploying contracts requires various steps. Broadly speaking, these can be divided into four steps: writing, testing, verification, and deployment. After deployment, the next optional step is to create a user interface and present it to the end user through a web server. In contracts that do not require human input or monitoring, a web interface may not be necessary, but it is usually needed to interact with the contract.

  The writing steps involve writing contract source code in Solidity. This can be done in any text editor. For Vim, Atom, and other editors, there are various plugins and add-ons available for providing syntax highlighting and formatting for Solidity contract source code.

  Visual studio code has become very popular and is commonly used for Solidity development. There is a Solidity plugin available that can provide syntax highlighting, formatting, and intelligence. It can be installed through the extension options in Visual Studio Code.

  

  Visual studio code

  Tests are usually performed through automated means. In the earlier part of this chapter, you have learned about Truffle, which uses the Mocha framework to test contracts. However, manual functional tests can also be executed by manually running functions and verifying the results using Remix.

  In the next section, you will be introduced to the Solidity language. This is a brief introduction to Solidity, which should provide the basic knowledge needed to write contracts. Its syntax is very similar to C and JavaScript, making programming quite easy.

  Solidity is the preferred domain-specific language for writing contracts on Ethereum. However, there are other available languages, such as Serpent, Mutan, and LLL, but as of the time of writing this article, Solidity is the most popular. Its syntax is closer to JavaScript and C.

  Solidity has evolved into a mature language over the past few years and is very easy to use. However, there is still a long way to go before it becomes as advanced, standardized, and feature-rich as other mature languages like Java, C, or C#. Despite this, it is still the most widely used language for writing contracts today.

  It is a statically typed language, which means that type checking in Solidity is performed at compile time. Each variable, whether a state variable or a local variable, must be assigned a type at compile time. This is beneficial in a sense because any verification and checking are completed at compile time, and certain types of errors, such as data type interpretation, can be caught early in the development cycle, rather than at runtime, which can be costly, especially in the blockchain/smart contract paradigm. Other features of the language include inheritance, libraries, and the ability to define composite data types.

  Solidity is also known as a contract-oriented language. In Solidity, a contract is analogous to the concept of classes in other object-oriented programming languages.

  Solidity has two types of data types: value types and reference types.

  These are explained in detail here:

  This data type has two possible values, or , for example:

  This statement assigns the value to .

  This data type represents integers. The following table shows various keywords used to declare integer data types:

  The keyword signed integer to , which means the keyword increases from to , for example, . Unsigned integers , ,… to represent unsigned integers from 8 bits to 256 bits. The storage requirement of the variable depends on how many bits need to be stored.

  For example, in this code snippet, note that is an alias for :

  These types can also be declared with the keyword, which means the compiler will not reserve storage slots for these variables. In this case, the actual value will be replaced each time it appears:

  State variables are declared outside of functions and remain available based on the accessibility assigned to them and the duration of the contract.

  This data type holds a value of 160 bits long (20 bytes). This type has several members that can be used to interact with and query contracts. These members are described here:

  Balance: The member returns the Wei balance of the address.

  Send: This member is used to send a certain amount of Ether to an address (an Ethereum 160-bit address) and return or based on the transaction result, for example:

  Function calls: and are used to interact with functions without ABI. Due to the impact on the type safety and security of the contract, these functions should be used with caution.

  Array value types (fixed size and dynamically sized byte arrays): Solidity has fixed size and dynamically sized byte arrays. The fixed size keyword ranges from to , while the dynamic size keywords include and . The keyword is used for raw byte data, and is used for strings encoded in UTF-8. Since these arrays are returned by value, calling them will incur gas costs. is a member of array value types and returns the length of the byte array.

  An example of a statically (fixed size) array is as follows:

  An example of a dynamically sized array is as follows:

  Use the following code to get the transaction length:

  These are used to represent fixed values. The following sections describe different types of literals.

  Integer literals are a series of decimal digits ranging from 0 to 9. An example is as follows:

  String literals specify a set of characters enclosed in double quotes or single quotes. An example is as follows:

  Hexadecimal literals are prefixed with the keyword and specified within double quotes or single quotes. An example is as follows:

  This allows the creation of user-defined types. An example is as follows:

  Enum types allow for explicit conversions to all integer types.

  There are two types of functions: internal functions and external functions.

  These can only be used in the context of the current contract.

  External functions can be called using external function calls.

  In Solidity, functions can be marked as constant. Constant functions cannot change any content in the contract; they only return values when called and do not consume any gas. This is an actual implementation of the call concept.

  The syntax for declaring a function is as follows:

  As the name suggests, these types are passed by reference and are discussed in the following sections. They are also known as complex types.

  An array represents a series of consecutive elements of the same size and type arranged at memory locations. This concept is the same as in any other programming language. Arrays have two members named and:

  These structures can be used to group a set of different types of data into a logical group. These can be used to define new types, as shown in the following example:

  Data location specifies where a specific complex data type will be stored. According to the default value or specified comments, the location can be storage or memory. This applies to arrays and structures, and can be specified using or keywords.

  Since copying between memory and storage can be quite expensive, specifying a location can sometimes help control gas consumption. Call data is another memory location used to store function parameters.

  The parameters of external functions use call data memory. By default, the parameters of the function are stored in memory, while all other local variables use storage. On the other hand, state variables need to use storage.

  Mappings are used for key-value mappings. This is a method to associate values with keys. All values in this mapping are initialized to zero, for example the following content:

  This example shows that offers are declared as a mapping. Another example makes this clearer:

  This is essentially a dictionary or hash table where string values map to integer values. A mapping named maps strings to values.

  Solidity provides some global variables that are always available in the global namespace. These variables provide information about blocks and transactions. In addition, cryptographic functions and variables related to addresses are also available.

  The available function and variable subsets displayed are as follows:

  This function is used to calculate the Keccak-256 hash value of the parameters provided to the function:

  This function returns the public key associated address of the elliptic curve signature:

  This returns the current block number.

  The control structures available in Solidity are, , , , and . They work in the same way as in other languages (such as C language or JavaScript).

  Some examples are shown here:

  if: If equal, assign the value to, otherwise assign to:

  do: Increment when greater than:

  while: Increment when greater than:

  for, break, and continue: Perform some work until less than or equal to. If so, this loop will run once, then break:

  It will continue to work similarly, but the loop will restart when the condition is met.

  return: Return is used to stop the execution of the function and return an optional value. For example:

  It will stop executing and return a value.

  Events in Solidity can be used to record certain events in the EVM logs. These events are very useful when it is necessary to notify external interfaces of changes or events. These logs are stored in the transaction logs of the blockchain. Contracts cannot access the logs, but they serve as a mechanism to notify the contract of state changes or events (satisfying conditions).

  In a simple example here, the event will return when the parameter passed to the function is equal to or greater than:

  Solidity supports inheritance. The keyword is used to derive a contract from another contract. In the following example, is derived from . The derived contract has access to all non-private members of the parent contract:

  In the previous example, if is changed to , the contract will not be able to access it. This is because now the member is declared as private and does not allow access by any other contract. The error message you will see in Remix is

  Libraries are deployed only once at a specific address, and their code is called via the EVM’s or operation codes. The key idea behind libraries is the reusability of code. They are similar to contracts and serve as base contracts for calling contracts. A library can be declared as follows:

  Then this library can be called in the contract, as shown below. First, it needs to be imported, and then it can be used anywhere in the code. A simple example is shown below:

  Libraries have some limitations; for example, they cannot have state variables, nor can they inherit or be inherited. Additionally, they cannot receive Ether; this is in contrast to contracts, which can receive Ether.

  Functions in Solidity are code modules associated with a contract. Function declarations include the name, optional parameters, access modifiers, optional keywords, and optional return type. As shown in the following example:

  In the previous example, is the keyword used to declare a function. is the function name, is an optional parameter, is the access modifier or specifier that controls external contracts’ access to this function, is an optional keyword indicating that this function does not change any content in the contract and is used only to retrieve values from the contract, and is the optional return type of the function.

  How to define a function: The syntax for defining a function is as follows:

  Function signature: In Solidity, functions are identified by their signature, which is the first four bytes of the Keccak-256 hash of their complete signature string. This can also be seen in the Remix IDE, as shown in the following screenshot. These are the first four bytes of the 32-byte Keccak-256 hash of the function named .lottery platform and The latest entrance

  

  Function hash displayed in Remix IDE

  In this example function, the signature hash of is . This information is useful for building interfaces.

  Function input parameters: Function input parameters are declared in the form of . This example illustrates the concepts of function input parameters and

  Function output parameters: Function output parameters are declared in the form of . This example shows a simple function that returns a single value:

  A function can return multiple values. In the previous example function, only one value is returned, but a function can return up to 14 values of different data types. The names of unused return parameters can be optionally omitted.

  Internal function calls: In the context of the current contract, functions within the current contract can be called directly. These calls result in simple calls at the EVM bytecode level.

  External function call: An external function call is a message call from one contract to another contract through a contract. In this case, all function parameters will be copied into memory. If the internal function is called using the keyword, it is also considered an external call. The variable is a pointer that points to the current contract. It can be explicitly converted to an address, and all members of contracts are inherited from the address.

  Fallback function: This is an unnamed function without parameters and return data in a contract. This function will execute every time ether is received. If the contract intends to receive ether, this function must be implemented within the contract; otherwise, an exception will be thrown, and ether will be returned. This function will also execute if there is no other function signature that matches in the contract. If the contract expects to receive ether, the fallback function should be declared with the payable modifier. This modifier is required; otherwise, this function will not be able to receive any ether. This function can be called using the method, for example:

  In this case, if the fallback function is called based on the aforementioned conditions, it will call , which will roll back the state to the state before the call. It can also be other constructs, such as, it can record an event that can act as an alert to the calling application’s feedback.

  Modifier functions: These functions are used to change the behavior of functions and can be called before other functions. Typically, they are used to check certain conditions or validate before executing a function. In modifier functions, the underscore (_) is used to replace the actual function body when calling the modifier. Essentially, it symbolizes a function that needs to be guarded. This concept is similar to guardian functions in other languages.

  Constructor: This is an optional function with the same name as the contract and is executed when the contract is created. The constructor cannot be called later by the user, and only one constructor is allowed in a contract. This means that no overloading feature is available.

  Function visibility modifiers (access modifiers): Functions can be defined with four access modifiers as follows:

  External: These functions can be accessed from other contracts and transactions. They cannot be called internally unless the keyword is used.

  Public: By default, functions are public. They can be called internally or through messages.

  Internal: Internal functions are visible to other derived contracts from the parent contract.

  Private: Private functions are only visible to the same contract in which they are declared.

  Function modifiers:

  Pure: This modifier prohibits access or modification of the state.

  View: This modifier prohibits any modification of the state.

  Payable: This modifier allows payment in ether by calling.

  Constants: This modifier does not allow access or modification of the state.

  Other important keywords/functions throw: Used to stop execution. Therefore, all state changes will be reverted. In this case, no gas is returned to the transaction sender because all remaining gas has been consumed.

  In the following sub-section, we will look at the components of Solidity source code files.

  To address compatibility issues that may arise with future solc versions, can be used to specify compatible compiler versions, for example:

  This will ensure that the source file will not compile with versions less than 0.5.0 and versions starting from 0.6.0.

  In Solidity, allows importing symbols from existing Solidity files into the current global scope. This is similar to the statement available in JavaScript, for example:

  Comments can be added to Solidity source code files in a manner similar to C language. Multi-line comments are enclosed with and brackets, while single-line comments start with .

  The following is a Solidity program example that shows the usage of comments:

  

  Solidity program examples displayed in Remix IDE

  This completes a brief introduction to the Solidity language. The language is very rich and is constantly being improved. Detailed documentation and coding guidelines can be viewed online: .

  This chapter starts with an introduction to Ethereum development tools such as Remix IDE. Then we discuss some frameworks, such as Truffle, as well as local blockchain solutions for development and testing, such as Ganache, EthereumJS, and TestRPC. Other tools like MetaMask were also explored. The installation of Node was introduced because most tools are based on JavaScript and Node.

  Sometimes, it is necessary for smart contracts to access data from other dapps or the global network. However, due to technical and consensus challenges, allowing smart contracts to access external data is indeed complex. Therefore, at present, Ethereum smart contracts do not have native support for accessing external data. But there are third-party solutions for Ethereum smart contracts to access some popular dapp and global network data. In this chapter, we will learn how to use Oraclize to send HTTP requests from Ethereum smart contracts to the global network to access data. We will also learn how to access files stored in IPFS, process strings using the string library, etc. We will learn all these by building a football betting smart contract and a client.

  In this chapter, we will cover the following topics:

  How does Oraclize work?

  What are the different data sources in Oraclize, and how do they work individually?

  How does consensus work in Oraclize?

  Integrate Oraclize into Ethereum smart contracts

  Use the string library to make string processing simpler.

  Build a football betting application.

  Oraclize is a service designed to enable smart contracts to obtain data from other blockchains and the global network. This service is currently live on the testnet and mainnet of Bitcoin and Ethereum. What makes Oraclize so special is that you do not need to trust it, as it provides authenticity proofs for all data provided to smart contracts.

  The goal of this chapter is to learn how Ethereum smart contracts use Oraclize services to obtain data from the global network.

  Let’s look at the process of how an Ethereum smart contract uses Oraclize to obtain data from other blockchains and the global network.

  To obtain data that exists outside the Ethereum blockchain, the Ethereum smart contract needs to send a query to Oraclize, mentioning the data source (indicating where to obtain the data) and the input of the data source (indicating what to obtain).

  Sending a query to Oraclize means sending a contract call (i.e., an internal transaction) to the Oraclize contract.

  The Oraclize server constantly searches for new queries sent to its smart contracts. Whenever it sees a new query, it retrieves the result and sends it back to your contract by calling the method of your contract.

  Here is the list of data sources that Oraclize allows smart contracts to access:

  URL: The URL data source allows you to perform HTTP GET or POST requests, that is, to obtain data from the global network.

  The data source allows you to submit queries to the knowledge engine and obtain answers.

  The data source allows you to access data from other . Possible queries that can be submitted to the data source include , , , etc.

  The data source allows you to obtain the content of the files stored in .

  The data source is a metadata source; it does not provide access to other services. It is designed to provide simple aggregation logic, so that a single query can be made based on any available data source, and a single string is generated as the result; for example:

  .

  The data source enables the given application to execute auditable transactions in a secure off-chain environment; in other words, it allows us to obtain the off-chain execution results of the application. The application must print the query results (on standard output) before exiting. The execution context must be described by a Dockerfile, where the construction and running of the application should immediately start your main application. The Dockerfile initialization plus application execution should terminate as soon as possible: the maximum execution timeout on the instance is 5 minutes. Here, we are considering the instance because this is the instance type that Oraclize will use to execute the application. Since the input of the data source is the IPFS multi-hash value of the ZIP archive containing these files (the Dockerfile plus any external file dependencies, the Dockerfile must be placed in the root directory of the archive), you should pay attention to prepare this archive and push it to IPFS.

  These data sources were available when this book was written. But in the future, there may be more data sources available.

  Although Oraclize is a trustworthy service, you may still want to check whether the data returned by Oraclize is real, that is, whether it has been manipulated during the transmission by Oraclize or others.

  Optionally, Oraclize provides TLSNotary result proofs returned from URLs, blockchains, and nested and calculated data sources. This proof is not available for and data sources. Currently, Oraclize only supports TLSNotary proofs, but in the future, they may support some other authentication methods. Currently, TLSNotary proofs need to be manually verified, but Oraclize is already working on on-chain proof verification; that is, your smart contract code can verify the TLSNotary proof while receiving data from Oraclize, so that if the proof is invalid, these data can be discarded.

  This tool () is an open-source tool provided by Oraclize for verifying TLSNotary evidence, if you wish.

  Understanding the working principle of TLSNotary is not a necessary condition for using Oraclize or verifying evidence. The tools for verifying TLSNotary evidence are open source; therefore, if any malicious code is included, it can be easily discovered, and this tool can be trusted.

  Let’s take a high-level overview of how TLSNotary works. To understand the working principle of TLSNotary, it is first necessary to understand how TLS works. The TLS protocol provides a way for clients and servers to establish an encrypted session so that others cannot read or manipulate the content transmitted between the client and server. The server first sends its certificate (issued by a trusted CA to the domain owner) to the client, which will contain the server’s public key. The client uses the CA’s public key to decrypt the certificate so that it can verify that the certificate was actually issued by the CA and obtain the server’s public key. Then, the client generates a symmetric encryption key and a MAC key, encrypts them with the server’s public key, and sends them to the server. The server can only decrypt this message because it has the private key needed to decrypt it. Now that the client and server share the same symmetric and MAC keys, and no one else knows these keys, they can start sending and receiving data to each other. The symmetric key is used to encrypt and decrypt data, while the MAC key and the symmetric key together are used to generate a signature for the encrypted message, so that the other party can know if the message is modified by an attacker.

  TLSNotary is a modified version of TLS, used by Oraclize to provide cryptographic proof that the data provided to your smart contract is indeed the data provided by the data source to Oraclize at a specific time. In fact, the TLSNotary protocol is an open-source technology developed and used by the PageSigner project.

  The working principle of TLSNotary is to divide the symmetric key and MAC key into three parties (i.e., the server, the audited party, and the auditor). The basic idea of TLSNotary is that the audited party can prove to the auditor that a specific result was returned by the server at a specific time.

  Now here is an overview of how TLSNotary achieves this goal. The auditor calculates the symmetric key and MAC key and only gives the symmetric key to the audit subject. The audit subject does not need the MAC key because the MAC signature check ensures that the TLS data transmitted from the server has not been tampered with. Using the symmetric encryption key, the audit subject can now decrypt the data from the server. Since all messages are ‘signed’ by the bank using the MAC key, and only the server and the auditor know the MAC key, the correct MAC signature can serve as proof that certain messages indeed came from the bank and were not forged by the audit subject.

  For the Oraclize service, Oraclize is the audit subject, and a locked AWS instance (a special open-source Amazon machine image) is the auditor.

  The proof data they provide is AWS instance signature authentication, proving that the TLSNotary proof actually occurred. They also provide some additional proof about the software running on the AWS instance, namely whether it has been modified since initialization.

  The first Oraclize query call from any Ethereum address is completely free. Oraclize is also free when used on the test network! This only applies to moderate use in the test environment.

  Starting from the second call, you need to pay Ether to query. When sending a query to Oraclize (i.e., making an internal transaction call), the fee is deducted by transferring Ether from the calling contract to the Oraclize contract. The amount of Ether deducted depends on the data source and the type of proof.

  Below is a table showing the amount of Ether扣除 when sending a query:

  The data source does not prove the existence of TLSNotary proof URL $0.01$0.05 blockchain $0.01$0.05 WolframAlpha $0.03$0.03 IPFS $0.01$0.01

  Therefore, if you send an HTTP request and you also want TLSNotary proof, then the contract call must have a value of $0.05 worth of Ether, otherwise an exception will be thrown.

  To use the Oraclize service, the contract needs to inherit the contract. You can find this contract .

  The contract acts as an agent for the and contracts. In fact, makes it easy to call the and contracts, that is, it provides a simpler API. If you feel comfortable, you can also call the and contracts directly. You can view the source code of these contracts to find all available APIs. We will only learn the most necessary.

  Let’s see how to set the proof type, set the proof storage location, make a query, find the cost of the query, and so on.

  Whether you need TLSNotary proof from Oraclize or not, you must specify the proof type and proof storage location before sending the query.

  If you do not need proof, then place this code in your contract:

  If you need proof, then place this code in your contract:

  Currently, is the only available proof storage location; that is, TLSNotary proofs are only stored in .

  You can execute any of these methods, for example, in the constructor or at any other time, if, for example, you only need the proof of some queries.

  To send a query to Oraclize, you need to call the function. This function requires at least two parameters, namely the data source and the input for the given data source. The data source parameter is case-insensitive.

  Here are some basic examples of the function:

  Here is how the aforementioned code works:

  If the first parameter is a string, it is assumed to be the data source, and the second parameter is assumed to be the input of the data source. In the first call, the data source was , and the search query we sent to it was .

  In the second call, we made a request to the provided by the second parameter.

  In the third call, we obtained the content of the file.

  If the two consecutive parameters following the data source are both strings, it is assumed to be a POST request. In the last call, we made a request to and the request body content was the string in the third parameter. Oraclize is smart enough to detect the content type header based on the string format.

  If you want Oraclize to execute your query at a scheduled time in the future, simply specify the delay (in seconds) as the first parameter from the current time.

  Here is an example:

  The aforementioned query will be executed by Oraclize after seconds of being received. Therefore, if the first parameter is a number, it is assumed that we are scheduling a query.

  The transaction from Oraclize to your function will cost gas, just like any other transaction. You need to pay the gas fee to Oraclize. The Ether or oraclize_query fee used to send the query is also used to provide gas when calling the function. By default, when calling the function, Oraclize provides 200,000 gas.

  The returned gas fee is actually under your control because you write the code in the method, so you can estimate it. Therefore, when querying Oraclize, you can also specify how much gas should be on the transaction. However, please note that any unused gas sent by Oraclize will be refunded to Oraclize, not to you.

  If the default value and the minimum value of 200,000 gas are not enough, you can increase it by specifying a different in this way:

  Here, you can see that if the last parameter is a number, it is assumed to be custom gas. In the previous code, Oraclize will use 500k for the callback transaction instead of 200k. Because we require more gas from Oraclize, Oraclize will deduct more Ether (depending on how much gas is needed) when calling.

  Please note that if the provided value is too low and your method is long, you may never see the callback. Also, please note that the custom gas must be over 200k.

  Once your result is ready, Oraclize will send a transaction to your contract address and call one of the following three methods:

  Either. is the unique ID of each query. This ID is returned by the method. If there are multiple calls in your contract, it is used to match the query that results in this result.

  If you request a TLS Notary proof, this is the result:

  As a last resort, if other methods do not exist, the fallback function is

  Here is an example of a function:

  The result of an HTTP request can be HTML, JSON, XML, binary, etc. In Solidity, parsing is difficult and expensive. Therefore, Oraclize provides parsing assistants to process parsing on its server, and you only get the part of the result you need.

  To have Oraclize parse the result, you need to wrap the URL in one of the following parsing assistants:

  and the assistant allows you to request that Oraclize only return the parsed part of JSON or XML; for example, see the following content:

  To obtain a complete response, you use a data source with URL parameters

  If you only want the last price field, you need to use a JSON parsing call, such as

  The assistant is very useful for HTML scraping. Just specify the XPATH you want as the parameter; for example, see the following content:

  To get the text of a specific tweet, please use.

  The assistant is very useful for getting binary files (such as certificate files):

  To get a partial content of a binary file, you can use; the first parameter is the offset, and the second parameter is the length of the fragment you want to return (in bytes).

  Example: Only get the first 300 bytes from the binary CRL. The binary assistant must be used with the slice option and only accepts binary files (unencoded).

  If the server does not respond or is inaccessible, we will send an empty response to you. You can use to test the query.

  If you want to know how much cost a query will take before performing the actual query, you can use the function to get the required wei amount. The first parameter it accepts is the data source, and the second parameter is optional, which is the custom gas.

  A common use case for this is to notify the client to add Ether to the contract if there is not enough Ether to perform the query.

  Sometimes, you may not want to reveal the data source and/or the input of the data source. For example: if there is an API key, you may not want to reveal it in the URL. Therefore, Oraclize provides a method to encrypt queries and store them in smart contracts, with only Oraclize’s server having the decryption key.

  Oraclize provides a Python tool ( ), which can be used to encrypt data sources and/or data inputs. It generates a non-deterministic encrypted string.

  The CLI command to encrypt any text string is as follows:

  The long hexadecimal string you see is the public key of the Oraclize server. Now you can use the output of the above command to replace the data source and/or the input of the data source.

  To prevent the abuse of encrypted queries (i.e., replay attacks), the first contract to use a specific encrypted query to query Oraclize will become its legitimate owner. Any other contract that repeats the exact same string will not be allowed to use it and will receive an empty result. Therefore, when redeploying contracts that use encrypted queries, always remember to generate a new encrypted string.

  There is another data source named decrypt. It is used to decrypt an encrypted string. However, this data source will not return any results; otherwise, anyone would be able to decrypt the data source and input to it.

  It is specifically designed to be used within nested data sources to achieve partial query encryption. This is its only use case.

  Oraclize provides a Web IDE where you can write, compile, and test applications based on Oraclize. You can find it here.

  If you visit the link, you will find that it looks exactly the same as the browser-based Solidity. In fact, it is just the browser-based Solidity with an additional feature. To understand what this feature is, we need to delve deeper into the browser-based Solidity.

  The browser-based Solidity not only allows us to write, compile, and generate web3.js code for our contracts, but also enables us to test these contracts within it. So far, to test our contracts, we have been setting up Ethereum nodes and sending transactions to them. However, the browser-based Solidity can execute contracts without connecting to any node, and everything happens in memory. It achieves this by using ethereumjs-vm, which is the JavaScript implementation of the Ethereum Virtual Machine. With ethereumjs-vm, you can create your own EVM and run bytecode. If necessary, we can configure the browser-based Solidity to use the URL of the Ethereum node that provides the connection. The user interface is very informative, so you can try all of this yourself.

  The special feature of the Oraclize web IDE is that it deploys the Oraclize contract in a memory execution environment, so you do not need to connect to a test network or main network node, but if you are using the browser-based Solidity, you must connect to a test network or main network node to test the Oraclize API.

  You can find more resources about integrating Oraclize at .

  Handling strings in Solidity is not as simple as in other high-level programming languages (such as JavaScript, Python, etc.). Therefore, many Solidity programmers have created various libraries and contracts to facilitate easy string handling.

  The library is the most popular string utility library. It allows us to convert strings into something called slices, thereby enabling operations such as concatenation, joining, splitting, and comparison. A slice is a structure that stores the length and address of the string. Since a slice only needs to specify an offset and length, copying and operating on slices is much cheaper than copying and operating on the strings they refer to.

  To further reduce gas costs, most slice functions that need to return slices modify the original slice instead of allocating a new one; for example, to return the text before the first , modify s to only contain the string after . In cases where you do not want to modify the original slice, you can use to copy, for example, . It is best to avoid using this convention in loops; since Solidity does not have memory management, this will result in the allocation of many short-term slices that will later be discarded.

  Functions that need to copy string data will return a string instead of a slice; if necessary, these can be converted back to slices for further processing.

  Let’s look at some examples of using the library to handle strings:

  The code mentioned above is self-explanatory.

  The function returning two slices has two versions: one is a non-allocating version that takes the second slice as a parameter and modifies it in place; the other is an allocating version that allocates and returns the second slice; for example, let’s look at the following example:
lottery local and Latest
  You can learn more about the strings library.

  In our betting application, two people can choose to bet on a football match, one supporting the home team and the other supporting the away team. Both should place the same amount of bet, and the winner will win all the money. If the match ends in a draw, both will get their money back.

  We will use the FastestLiveScores API to find match results. It provides a free API that allows us to make 100 free requests per hour. First, create an account, then generate an API key. To create an account, please visit, and once the account is created, you will see the API key. You can find the API documentation here.

  In our application, every bet between two people will deploy a betting contract. The contract will contain the match ID retrieved from the API, the wei amount that each party needs to invest, and the addresses of each party. Once both parties have invested in the contract, they will learn the result of the match. If the match has not ended, they will try to check the result every 24 hours.

  This is the contract code:

  The contract code is self-explanatory. Now use or compile the above code with browser Solidity, depending on what you are familiar with. You will not need to link libraries because all functions are set to visibility.

  In the browser Solidity, when specifying a library or contract from an HTTP URL, make sure it is hosted on GitHub; otherwise, it will not be accessible. In the GitHub file URL, make sure to remove the protocol and the dot.

  To facilitate the search for match IDs, deployment, and investment contracts, we need to build a UI client. So let’s start building a client that will have two paths, one for the home page path used for deploying contracts and betting on matches, and another path for searching the match list. We will allow users to deploy and bet using their own offline accounts, so the betting process will be decentralized and no one can cheat.

  Before we start building the client, please make sure you have synchronized the testnet, as Oraclize only runs on the Ethereum testnet/mainnet and does not run on private networks. You can switch to the testnet and start downloading the testnet blockchain by replacing the option with the option. For example, see the following content:

  In the exercise files of this chapter, you will find two directories, namely Final and Initial. Final contains the final source code of the project, while Initial contains empty source code files and libraries that can quickly start building the application.

  To test the directory, you need to run in it, and then use the command in the Final directory to run the application.

  In the directory, you will find a directory and two files named and . The file contains the backend dependencies for our application, while the file is where you will place the backend source code.

  The directory contains files related to the frontend. In the directory, you will find the file, which is the bootstrap library. In the directory, you will find the and files, where you will place the HTML code for our application, and in the directory, you will find the and js files. In the directory, you will also find a file, where you will place the frontend JS code for our application. You will also find the Oraclize Python tool to encrypt queries.

  Let’s first build the backend of the application. First, run in the initial directory to install the dependencies required for our backend.

  Here is the backend code that runs the express service, provides the file and static files, and sets the view engine:

  The code above is self-explanatory. Now let’s continue. Our application will have another page that will display the list of recent match IDs and results (if the match has ended). Here is the code for the endpoint:

  Here, we are making an API request to get the list of recent matches, and then passing the results to the file so that it can present the results in a user-friendly interface. The API results provide the start time of the match in the form of a timestamp; therefore, we use moment to convert it to a human-readable format. We make this request from the backend rather than the frontend to avoid exposing the API key to the user.

  Our backend will provide an API for the frontend, through which the frontend can encrypt queries before deploying the contract. Our application will not prompt users to create an API key, as this would be a poor user experience practice. Developers controlling the API key will not cause any harm, as developers cannot modify the results from the API server; therefore, even if the developers of the application know the API key, users will still trust the application.

  Here is the code for the encrypted endpoint:

  We have seen how to use this tool. To successfully run this endpoint, make sure Python is installed on your system. Even if Python is already installed, the endpoint may still show errors indicating that the Python encryption and base58 modules are not installed. Therefore, if the tool prompts you to install these modules, make sure you have installed them.

  Now let’s build the frontend of the application. Our frontend will allow users to view the list of recent matches, deploy betting contracts, bet on matches, and view information about betting contracts.

  Firstly, we will implement the file, which will display the list of recent matches. Here is the code for this file:

  The previous code is self-explanatory. Now let’s write the HTML code for the homepage. Our homepage will display three forms. The first form is for deploying the betting contract, the second form is for investing in the betting contract, and the third form is for displaying the information of the deployed betting contract.

  This is the HTML code for the homepage. Place this code in the page.

  The previous code is self-explanatory. Now let’s write the JavaScript code for actually deploying the contract, investing in the contract, and displaying contract information. Here is the code for all of these.

  The working principle of the previous code is as follows:

  Firstly, we store the bytecode and ABI of the contract separately in the variables and .

  Then, we create an instance connected to the testnet node.

  Next, we have a function (a cross-browser compatible function) that returns an AJAX object.

  Then, we attach an event listener to the first form used for deploying contracts. In the callback of the event listener, we send a request to the endpoint by passing to obtain the encrypted query string. Then, we generate the data for deploying the contract. Next, we find the required . We use the function object’s estimateGas method to calculate the required gas, but you can also use the web3.eth.estimateGas method. They differ in parameters; that is, in the former case, you do not need to pass transaction data. Remember, if the function call throws an exception, it will return the block gas limit. Then, we calculate the random number. Here, we just use the method, rather than the actual process we learned before. This is done just to simplify the code. Then, we create the original transaction, sign it, and broadcast it. Once the transaction is mined, we display the contract address.

  Then, we attached an event listener to the second table for the investment contract. Here, we generated the part of the transaction, calculated the required gas, created the original transaction, signed it, and broadcasted. When calculating the gas required for the transaction, we passed the value of the contract address from the account address and the value object properties, because this is a function call, and the gas depends on the value, from address, and contract address. Remember, when looking for the gas required to call the contract function, you can pass the and properties, because the gas depends on these values.

  Finally, we added an event listener to the third form, which displays the information of the deployed betting contract.

  Now that we have completed the construction of our betting platform, it is time to test it. Before testing, make sure that the testnet blockchain is fully downloaded and is looking for new blocks.

  Now use the wallet service we established earlier to generate three accounts. Add one ether to each account.

  Then, run in the directory, and visit, and you will see the content shown in the following screenshot:

  

  Here, you can copy any match ID. Suppose you want to test the first match, which is 123945. Now visit, and you will see the content shown in the following screenshot:

  

  Now deploy the contract by filling in the input fields of the first table and clicking the ‘Deploy’ button, as shown in the figure. Use your first account to deploy the contract.

  

  Now bet on the main team of the contract from the second account, and bet from the third account, as shown in the following screenshot:

  The failure to save external link images, the source site may have anti-hotlinking mechanisms, it is recommended to save the image directly and upload it.

  Now place the contract address on the third table and then click the ‘Find’ button to view the details of the contract. You will see content similar to the following screenshot:

  

  Once both transactions have been mined, check the contract details again, and you will see content similar to the following screenshot:

  The failure to save external link images, the source site may have anti-hotlinking mechanisms, it is recommended to save the image directly and upload it.

  Here, you can see that there are no ether in the contract, all ether have been transferred to the account of the betting main team.

  In this chapter, we have deeply studied about Oraclize and the library. We have combined them to build a decentralized betting platform. Now, you can proceed and customize contracts and clients according to your needs. To enhance the application, you can add events to the contract and display notifications on the client. Our goal is to understand the basic architecture of decentralized betting applications.