Where is it from:https://jysperm.me/2016/05/blockchain-slides/
This article is a compilation of my technical sharing on LeanCloud at the end of March, assuming that the reader already has some basic knowledge of cryptography and a preliminary understanding of the implementation of Bitcoin.
Blockchain, also known as blockchain, can be thought of as a HashTree, which is why it has some of the same properties as HashTree:
The image is fromhttp://happypeter.github.io/bitcoin_basics/book/017_merkle_tree.html
That is, in a tree structure, each terminal node has a hash value, whereas the hash values of non-terminal nodes are derived from the hash values of all of its direct sub-nodes, so each node contains information from all of its sub-nodes directly or indirectly. Thus, as long as the hash values of any terminal node change, the hash values of all of its parent nodes must also change.
I can cite an application of HashTree: "100% proof of reserve", it belongs to the category of "zero-knowledge proofs". We can consider a scenario in which the owner of Bitcion needs to send Bitcoin to an exchange in order to make a transaction, and the exchange can theoretically move the money (the balance of all users' accounts) to use it, which users do not want to see, and the exchange wants to clear its name: the exchange first publishes a Bitcoin address that it holds, and everyone confirms that the transaction actually holds so much Bitcoin as a reserve, but how can the money be proven to be greater than the sum of all users?
The image is fromhttp://blog.bifubao.com/2014/03/16/proof-of-reserves
We can construct a HashTree where all the end nodes represent one user and contain the user balance.Σ
) and a string of user IDs (e.g. email address)h
), whereas the parent node contains the sum of the residuals of its child nodes.sum
) and a hash of all sub-node informationhash
For each user, just show him his own terminal and sister nodes, all of his parent nodes and the sister nodes of the parent nodes, because this user can confirm his balance is included in the parent node, and finally included in the root node, by gradually tracing the parent node.
In this way, the information shown to each user is only its own information and some information that has been aggregated, and each user can confirm that their balance is contained in the root node without knowing the other usable balance.h
For thee4df9d12
The node should not be an endpoint representing the user, but rather an aggregated information node (which can contain a user with 3333 balances, and a fictitious user with 0 balances) to avoid leaking a user's privacy information.
Now let's look at Git, which is actually a very typical blockchain application:
The image is fromhttp://gitbook.liuhui998.com/1_2.html (GPL v2)
In Git, a hash is defined by its content, if two objects have the same content, then the hash is the same. In Git, the history of the entire repository is a blockchain, each commit is equivalent to a block, the commit contains the hash of the previous commit and the hash of the modified related object, the hash of the commit itself is determined by its content and these metadata.
Git uses the Blockchain to determine a unique history for the repository. Well, if a Commit is modified, all the Hashes of the Commits after it change. Of course, since Git is just a version control tool, it doesn't stop you from modifying the history (you can rebase it after all).push --force
This change is noticeable to all co-authors.
Another classic application of Blockchain is Bitcoin, which is where the word Blockchain (which has been around for a long time) was popularized:
The image is fromhttps://commons.wikimedia.org/wiki/File:Bitcoin_Block_Data.png(CC-BY-SA-3.0)
In Bitcoin, each block contains a series of Transactions and the Hash of the previous block, while the entire blockchain forms a decentralized single ledger. Since a new block is generated every ten minutes, and once a block is generated, it stays on the blockchain forever, so the blockchain fixes the order in which transactions occur, maintains the order in which transactions occur, and then determines whether an account has enough balance to initiate a transaction.
The first part of this post is a simple review of Bitcoin.
The creation of a block in Bitcoin is accomplished through a "proof of workload", whereby all the "miners" involved in "mining" perform a computationally related, randomized hashing until a random number that meets certain conditions is calculated and the right to publish a block is obtained.
By default, each miner will always trust the "longest chain" to calculate the next block based on the longest known chain that meets the rules, otherwise your computing power will be wasted.
Bitcoin is designed to generate a new block every 10 minutes, which is achieved by collectively adjusting the difficulty of generating the next block by observing the intervals between the last few blocks. When the last few blocks are generated faster than expected, people assume that the next block should be generated with a higher difficulty.
Normally, each Bitcoin node needs to store the complete Blockchain data to confirm that a transaction is legitimate. It is important to know whether the originator of the transaction has enough balance to initiate the transaction. But now the complete blockchain has 66G, and is growing at a rate of about 0.1G per day. If the requirement of each Bitcoin user to store the complete blockchain is not too demanding, so Bitcoin has a "Simplified Verification SPV, Simplified payment verification" mechanism, the so-called "lightweight client" can choose not to store the entire blockchain, but attached to one or several complete nodes, storing only all the information (Hash, contains the amount of transactions, works), and then verify the workload of each block, verify each time it is necessary to verify the transaction at the transaction point, and then check if the entire information is stored in the Hash Block.
The image is fromhttps://github.com/ethereum/wiki/wiki/White-Paper
In fact, we can imagine the Bitcoin blockchain as a "state machine", where the entire blockchain is a stateful "book" that stores records of every transaction, and from these records we can deduce the "state" of the entire blockchain at any given time, i.e. how much each account in the Bitcoin network has in its balance. Each transaction is a change in the state, and each block is a "consensus" of miners on the current state of the entire Bitcoin network, because Bitcoin generates a new block every 10 minutes, which is equivalent to everyone reaching a consensus on the balance of all accounts every 10 minutes, and in between these ten minutes, the state of the account is actually a "chaos state".
A number of other crypto currencies have also been derived from Bitcoin, often referred to as "Alt Coin", which usually have two implementations:
The first is that it uses its own network, which is independent of Bitcoin. The advantage of this is that it can design its own protocols and rules very flexibly, but the defense against malicious attacks will be very weak because the number of users is difficult to reach the same level as Bitcoin.
The second is to use Bitcoin's network to implement "metaprocessors" that implement their own logic by attaching customized information on top of Bitcoin's Transaction. The advantage is that the computational scale of Bitcoin can be used to defend against attacks, but at the same time, because not all miners are attached to the Bitcoin network, not all miners follow the rules of the coin, so it is not possible to prevent non-compliant blocks from entering the Blockchain, only to filter out non-compliant transactions on the client, and not to take advantage of the simplified confirmation function provided by Bitcoin mentioned above.
For these coins, Bitcoin can provide a blockchain with a large number of miners, which can withstand large-scale malicious attacks, while Bitcoin's Transaction can also carry custom data, leaving some space for the implementation of the coin.
Bitocin also provides aBitcoin ScriptIt is used to implement more complex Transactions, but because this is not the core function of Bitcoin, it can only perform relatively simple operations, read only very limited data on the Blockchain, and write general, Turing-complete logic because of the lack of loop mechanisms.
The image is fromhttps://www.ethereum.org/assets (CC 3.0)
Ethereum (Ethereum) is a blockchain-based, decentralized application platform that builds Bitcoin's infrastructure and cryptographically based blockchain technology into a universal platform and fills in some of the missing features of the Bitcoin network so that developers can run their own decentralized applications on the Blockchain.
Before I go into the details of Ethereum, I'll introduce two of the foundations of what I think are decentralized networks: cryptography and gambling. Cryptography, of course, is nothing more than a mathematical guarantee of security through public-key encryption, digital signatures, hashing and abstraction algorithms; while gambling is about a decentralized network in which anyone, including those who want to maliciously attack the network, can participate, and when designing a decentralized network, it is necessary to think about the interests of each participant from the point of view of each participant, ensuring that compliance with the rules maximizes the interests, and that violation of the rules causes losses or risks.
However, in the digital world, the release of a piece of data is cost-free, there are no "profits" and "losses", so it is necessary to establish some connection to the physical world in order to define "profits". For example, in the Bitcoin network, if an attacker wants to artificially change the direction of the Blcokchain, it is necessary to have higher computing power than all other miners, while in the physical world, computing power is required to be provided by the computing equipment, and the computing equipment is required to be purchased from the physical world.
So in a decentralized network, not all problems are solved by "technology", and where technology is not available, it must be solved through profit, through economic incentives. Also, because of the need for "economic incentives", Ethereum also has a wallet system (the unit of currency is called "Ether") where each user has a wallet address as its unique identifier, which is similar to Bitcion in this respect.
Contract is the most important concept introduced by Ethereum. In Bitcoin, all addresses belong to a user. When we say "user", we mean a pair of public and private keys. But in Ethereum, in addition to the address owned by a key, there is also an address owned by "code", Contract.
To start with, an example of a "multi-user wallet" is a feature in Ethereum's official client that creates a multi-user wallet:
As shown in the figure, this feature allows you to create a wallet address shared with 2 other people, each using up to 100 Ether per day, and if this limit is exceeded, the other person must agree.
This function actually creates a Contract, and the above logic is described by the code in the Contract. When you want to spend money from this shared wallet, you need to send a message to this shared wallet (a transaction is a message, the transaction amount can be zero, carry only data), and then the code in the shared wallet will be executed, if the spending request meets the above logic, initiating a real spending transaction, otherwise the spending request will be rejected without a real spending item.
Another example is "hedging contracts", where it has been said that Bitcoin as a digital currency is unstable in its value (and the exchange rate of fiat currency) and that it often rises or falls twice in value over the course of a day, but this problem can be solved to some extent if a hedging contract is implemented with Contract.
We'll call the person who wants to keep the currency unchanged "the risk-avoider", and the other person who is willing to take the risk of currency fluctuations and profit from it "the risk taker", so they can agree on an amount (e.g. 1000 CNY) and a time window (e.g. a month) and create a Contract that executes the following logic:
If the value of Ether increases, the risk-taker gains, if the value of Ether decreases, the risk-taker loses, but the risk-avoidant always wins. Of course, the risk-avoidant and the risk-taker can agree in advance on a "insurance fee" that the risk-avoidant will have to pay, or the risk-taker will need to provide a guarantee of several times the CNY 1000 ("the higher the multiplier, the greater the risk can be taken").
In the above example, there is also a problem that is not very well solved, namely how to determine the exchange rate between Ether and fiat currency, as we mentioned earlier, Contract can only access data on the blockchain, while fiat currency is data that exists in the physical world and not in the cryptographic world, and we need to introduce this kind of "data from the non-cryptographic world" into the blockchain through some mechanism.
We can design another Contract to specify this logic to collect the exchange rate between Ether and fiat currency from the physical world, in each time window (e.g. one hour):
For any one participant, submitting a genuine exchange rate is more likely to be rewarded because he does not know the other's bid, whereas submitting a very bizarre exchange rate will have a high chance of losing the collateral.
Of course, there are a few loopholes in this rule, such as if a person has a very large amount of collateral, he can pull the average to a price that is higher or lower than the real exchange rate, while getting a reward, and make some other people who provide the correct exchange rate lose the collateral. But the same is true in the real world, if you have a very large amount of money, you can also raise or lower the price of a commodity, only compared to the physical world, the volume of electronic money is small and it does not take much money to do it; but in fact, it is also very risky to raise or lower the exchange rate maliciously, because you are not sure if the collateral you pay is enough, and if you fail, you will lose all the collateral.
Another vulnerability is that "anyone can deposit a security to the Contract and provide a currency". This step is done by creating a transaction, and all transactions are written to the Blockchain, so the currency you submit is actually visible to others, further creating opportunities for malicious attackers.
We mentioned earlier that contracts can read data on the blockchain, but the data on the blockchain is definite, so if we want to implement a gambling-like application, where do we get a random number from?
One random number source that can be thought of is the Hash of the next block, and in most cases this degree of randomness is sufficient. But the fact is that the miner can manipulate this random number to some extent, assuming that a miner participates in a gamble and the gamble yields more than the gain of mining a block, then if the miner digs a block that will make him lose the gamble, then obviously the more the miner chooses not to publish the new block, this becomes more apparent in the case of the computational strength of the individual miner.
So we need to introduce a mechanism similar to a call exchange rate to collect random numbers of seeds and then use those seeds to calculate a random number of couples at the end of each time window. But just like call exchange, since participants are committed to submitting exchange rates by creating a transaction, so between one time window, the random numbers submitted by each person are visible to everyone else, so a person who has already participated in a gamble can carefully select a random number of seeds so that the seeds that others have submitted plus the random new ones produced match exactly his expectations.
So it is necessary to divide the seed collection window into two parts to get a random number that nobody can predict and intervene in:
In the first stage you only know the serial value of the seeds submitted by others, without knowing the actual seeds, so you cannot carefully construct a seed to intervene in the outcome; in the second stage, everyone only confirms the seeds submitted in the first stage, without submitting a new one, nor can you prevent others from submitting seeds.
We mentioned earlier that Bitcoin Script does not provide the ability to loop, reverse, jump, etc. Perhaps Bitcoin is for the sake of controlling the execution time of Bitcoin Script, because according to Turing's "stopping theorem", programs written by Turing-complete programming languages cannot always be judged from a static analysis perspective alone whether they will end after a limited number of steps, so that malicious attackers can construct a Transaction that will cause a dead loop to disrupt the normal work of miners.
Ethereum again bypasses this problem with "economic incentives", the Contract runs in the form of opcode (operating code) on a virtual machine called EVM (Ethereum Virtual Machine), which is a virtual machine with its own "charging", in the EVM's standard, the Gas consumed by each opcode is defined according to the memory and CPU time required for the operation, which is a computing resource purchased by Ether. As mentioned earlier, when the target of a transaction is a Contract, the Contract's code is executed, the originator of the transaction needs to pay for the Gas consumed in the process of executing the Contract, while declaring "the maximum amount of Gas Gas he is willing to pay", and if the middle way runs out, the Contract will stop executing.
Then we come back to the issue of "consensus interval", mentioned earlier that Bitcoin has a new block every 10 minutes, that is, the entire network reaches a "consensus" every 10 minutes, so it usually takes a few minutes for a Bitcoin transaction to be confirmed, and it may take an hour (six blocks) before everyone considers the transaction to be reliable.
Obviously, shorter consensus times will have a better experience for users, so why not shorten the block time? This is because faster consensus intervals will increase the advantages of the "centralized mining pool" to some extent. The so-called "mining pool" refers to Bitcoin miners coming together to mine, miners unconditionally obeying the instructions of the mine, and finally agreeing with the mine to share the profits, obviously Bitcoin as a decentralized system does not want this centralized mining pool to have the additional advantages.
When a miner A digs a new block, he broadcasts the block, and the others immediately start working on the new block once they receive the message; while others calculate the time between "A digs the new block" and "A receives the broadcast message", which is actually wasted, the other miners in the centralized pool do not have this problem, because they can get information about the newly generated block faster and start working on the new block immediately.
This broadcast may take a dozen seconds, which is not very important for 10 minutes, but if the consensus interval is shortened, the advantages of centralized mining pools will become increasingly apparent. But Ethereum solved this problem by introducing the concept of "Uncle Block", reducing the consensus interval to 15 seconds, which is a big boost compared to Bitcoin in terms of payment confirmation speed.
In Bitcoin's blockchain, a block can have only one parent block and only one subblock. But in Ethereum, a newly generated block can have both a parent block and several uncles. Going back to the example above, if a new block is mined in A but no one else has received the broadcast yet, if someone mines a new block during the time of the broadcast, but because the broadcast is not accepted by everyone, then this block has the potential to become the "uncle" of the next block. The amount of work represented by this block will prove to be considered part of the next block (i.e. the difficulty of this person to mine the next block is reduced), and the block only provides a proof of work, which contains transactions that are invalid.
The image is fromhttps://blog.ethereum.org/2014/07/11/toward-a-12-second-block-time
In the next section, I'm going to show you some of the problems that Ethereum has yet to solve.
The first is that Ethereum's current consensus is still that, like Bitcoin, POW (proof of work) is guaranteed, and that only nodes that have completed a certain amount of work can participate in the work of creating a block. The problem with proof of work is that it will waste a lot of computing power to ensure the security of the network, although this is also based on the "economic incentive" idea we mentioned earlier, but it can be improved. Ehtereum believes that a better way is to replace POS (proof of ownership) with proof of work, which can greatly improve the efficiency of this network.
Since Ether itself is valuable, why not use it as an economic incentive? A POS is a guarantee that each node that wants to participate in the creation of a block (in the traditional sense of mining) will be required to pay a security deposit to the system (this system refers to a protocol in which all nodes consider that the security has been "frozen") and then everyone will use their own security deposit to bet on a possible next block (an important premise of the so-called "probability" is that this block must be stipulated by the protocol), if this block is truly a block, then all nodes betting will be rewarded, otherwise the security deposit will be penalised.
The pattern is very similar to POW, in which miners "bet" with their own computing power, and if once there is a longer chain, it is necessary to switch to this chain to continue mining. Well, because the more people involved in the chain, the more likely it is to be the right chain, and eventually a consensus is reached.
POS is bound to increase the throughput of the entire network. The consensus will no longer need to be reached through a large number of meaningless calculations, and the amount of processing per node will be closer to the amount of computation required to execute the code in the contract and perform data verification.
Of course, the reason why POS has not been adopted yet is because there are still some unresolved problems, one of which is the 51% attack problem like POW, where the 51% computing power of the entire network is concentrated in POW is physically limited. The computing power is required to provide the computing equipment; in contrast, collecting 51% of the entire network Ether in POS is relatively easy, as long as you have enough money. POS is naturally less complex than POW, to achieve the above working logic, it is necessary to deal with, for example, maintaining an effective list of verifiers, fines for collateral, non-returns, proposed blocks and betting blocks, preventing alliances between verifiers attacks, recovery after network separation, etc.
Another topic is "slicing", where both Bitcoin and Ethereum are currently confirming all transactions on the same blockchain, which greatly limits the computing power of a distributed network. Well, each node needs to receive, store and validate each transaction, and the processing power of the entire network is actually equal to the processing power of one node.
Therefore, Ethereum hopes to introduce a "slicing" mechanism in the future to separate the entire network into several parts, and verify transactions independently between them. However, between the chunks, the data of other chunks will be referenced through the structure of the pointers, through asynchronous calls to affect other chunks, so the entire network will still be one in the eyes of the user, but the processing capacity of the entire network will be very strongly scalable.
In this section I will show you some actual, working Contract code. Contracts can be written in many different paradigm languages, and eventually they will all be compiled into opcode executed on EVM, and today we're going to use Solidity as an example of JavaScript, which is one of the best maintained EVM languages at the moment.
contract Test {
uint storedData; // State variable
struct Voter { // Struct
uint weight;
bool voted;
address delegate;
uint vote;
}
event HighestBidIncreased(address bidder, uint amount); // Event
function func() { // Function
if (msg.sender.balance < 10 finney) {
msg.sender.send(10 finney);
}
sha256("...");
address nameServer = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2;
nameServer.delegatecall("isAvailable", "MyName");
nameServer.call("register", "MyName");
}
}
Here is a demonstration of some of the core syntax that you can use to declare state variables in Solidity.uint storedData;
The value of these variables is stored forever on the blockchain.struct
It can also define functions that are executed when a transaction is received, and the originator of the transaction can choose which functions to execute, so a Contract can provide several functions within the function to make logical judgments, loop, and change the value of modifications.
The language has some very handy little features built in, such as the common cryptographic algorithm ((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((())))))))))))sha256
) ⋅ unit conversion10 finney
I'm going to write the address of my wallet.0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2
(Laughter)msg
A contract is a built-in global variable from which information related to the transaction can be read, such as the originator, amount, etc. Contract can call code from other contracts in one of two ways.delegatecall
This is equivalent to placing the code of another Contract into the current context of execution, as if introducing a library function;call
The logic is to initiate a new transaction to trigger another Contract.
This complicated task is abstracted for "state variables", where the stored data is a state variable. In fact, changes to the state variables during contract execution are not saved to the blockchain because the contract is a deterministic computation. The execution of the contract is triggered by a transaction, and the execution only reads the data already on the blockchain, so as long as we know the history of each transaction associated with this contract, we can always infer the value of each state variable in a contract at a certain point in time.
Next, I'll show you a really useful contract bucket for issuing your own token based on the Ethereum network:
contract Coin {
// The keyword "public" makes those variables
// readable from outside.
address public minter;
mapping (address => uint) public balances;
// Events allow light clients to react on
// changes efficiently.
event Sent(address from, address to, uint amount);
// This is the constructor whose code is
// run only when the contract is created.
function Coin() {
minter = msg.sender;
}
function mint(address receiver, uint amount) {
if (msg.sender != minter) return;
balances[receiver] += amount;
}
function send(address receiver, uint amount) {
if (balances[msg.sender] < amount) return;
balances[msg.sender] -= amount;
balances[receiver] += amount;
Sent(msg.sender, receiver, amount);
}
}
The code comes fromhttp://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#subcurrency-example (MIT)
This contract, called Coin, declares two state variables, and the first one is called a "Coin".minter
The creator of this token, which is used to store this token, is in the process of constructing a function.function Coin()
It assigns the initiator value of the first transaction used to create the Contract to this variable; it also declares a wallet address-to-number mapping.balances
This is the amount of money in the account, which is used to represent the balance of the address of each holder of the token.
mint
This function first determines whether the initiator of the transaction is the creator of the token, and if so, adds a certain number of tokens to the specified address according to the function's parameters.send
This function, which can be called by anyone, subtracts a certain amount of balance (if there is enough balance) from the address of the originator of the transaction and adds it to the destination address, which is equivalent to a transfer function.
We have also announced a new initiative calledSent
In the future, it will also be easier to implement lightweight clients (lightweight clients only accept events and do not actually execute contracts).
Ethereum provides an IDE called Mix to debug this code, and on the right side of Mix you can create blocks and accounts to test your Contract, and see how the value of each state variable changes during execution. It is worth mentioning that Contract cannot be modified once it is released, and its subsequent operation is triggered entirely by other people's transactions, which is very unpleasant for programmers who write bugs every day, but the semantics of Contract is "contract", otherwise who will trust your contract once you publish a contract that cannot be modified naturally.
Once the code is written, we can use the Ethereum wallet to publish this contract on the web:
You can follow this Contract after it is published, and always refer to the Contract's detailed interface:
On the left you can see the values of the two state variables.minter
The value is my own address.balances
Since it is a chart, you can enter an address to query its balance. On the right side you can initiate a new transaction to this Contract and there is a drop-down menu to choose from.send
Ormint
You can fill in the parameter to pass to Contract. Since the purpose of sending a transaction here is to pass a message, not to pass Ether, we don't have to set the amount of the transaction.
I'm going to introduce you to a very interesting Contract, which has a "Ponzi scam" effect, where you pay 1 Ether for this Contract to join the game, and then for every 3 people who join, 3 Ether is paid to the first person who joins in order:
contract Pyramid {
struct Participant {
address etherAddress;
}
Participant[] public participants;
uint public payoutIdx = 0;
// events make it easier to interface with the contract
event NewParticipant(uint indexed idx);
// fallback function - simple transactions trigger this
function() {
enter();
}
function enter() {
if (msg.value < 1 ether) {
msg.sender.send(msg.value);
return;
}
if (msg.value > 1 ether) {
msg.sender.send(msg.value - 1 ether);
}
uint idx = participants.length;
participants.length += 1;
participants[idx].etherAddress = msg.sender;
NewParticipant(idx);
// for every three new participants we can
// pay out to an earlier participant
if (idx != 0 && idx % 3 == 0) {
// payout is triple, minus 10 % fee
uint amount = 3 ether;
participants[payoutIdx].etherAddress.send(amount);
payoutIdx += 1;
}
}
function getNumberOfParticipants() constant returns (uint n) {
return participants.length;
}
}
The code is simplified fromhttps://ethereumpyramid.com/contract.html
The code is simple, the contract declares one.participants
The array is used to store the wallet addresses of all participants in order, or to declare apayoutIdx
This is used to record how many participants have already received 3 Ether back.enter
The main function of implementing this Contract is to first check some parameters, ensure that each participant is paid 1 Ether, and then put new participants on the contract.participants
At the end of the array, finally if the previous participant's number is a multiple of 3, send 3 Ether to the next participant.payoutIdx
The participants will be able to share their experiences.payoutIdx
This is the first time I've seen this post.
HashTree:
Bitcoin:
Halting Problem:
Ethereum:
Ethereum Network:
Next of Ethereum:
Contract:
Contract IDE:
Inventors quantify - small dreamsI've seen it all, I can only understand a little bit, I know too little.
xuanxuanIt turns out that the boss went to study BTC and ETH.
momoxI don't know.