What should we build a blockchain?

The whole history of mankind is a continuous getting rid of chains and the creation of new, even stronger ones. (Anonymous author)

Analyzing numerous blockchain projects (Bitshares, Hyperledger, Exonum, Ethereum, Bitcoin, etc.), I understand that from a technical point of view, they are all built on the same principles. Blockchains are like houses that, with all the variety of designs, decor and purposes, have a foundation, walls, roof, windows, doors that are connected to each other in certain ways. And if you understand the basic principles of building design, know the properties of the materials used, then you can determine the purpose of a particular house. Currently, a situation has arisen with the blockchain that everyone has heard about it, but few understand the architecture and principles of work. Therefore, there is a misunderstanding for what and how it makes sense to use blockchain technologies.

In this article, we will analyze the properties and principles common to all blockchains. Next, let's look at the tasks that can be solved using the blockchain and to consolidate the material, we will build a small but real blockchain on our virtual site!

So, let's remember what problems the blockchain initially solved.

I am sure that many will say about a distributed, decentralized, public and immutable database. But why was all this necessary?

I prefer to start learning any technology by reading the standards, since it is on them that all articles and books on the topic under study are based. But there are currently no blockchain standards, only ISO has created committees for their development. At the moment, each public blockchain project has its own White paper, which is essentially a technical task. The first well-known blockchain project is the Bitcoin network. We go to the official website of the network and look how it all began

Blockchain Challenge

So, the task that blockchain solved in the Bitcoin pioneer network is to make a trust transfer of ownership of digital assets (assets) in a non-trusted environment without intermediaries. For example, in the Bitcoin network, a digital asset is bitcoin digital coins. And all the technical solutions of Bitcoin and other blockchains come down to solving this problem.

Problems that blockchain solves

Suppose a certain financial institution says that it has built a network around the world with which you can transfer money to anyone. Will you believe her? If this organization is Visa or MasterCard, you will most likely believe it, and if, relatively speaking, AnonymousWorldMoney, you probably won't. Why? But because we know perfectly well how distributed systems are made by private companies, for what purposes, and what it can lead to. Let us consider in more detail the problems of such systems, and how they can be solved using blockchain technologies.

Let's say there are servers with databases in the conditional AnonymousWorldMoney, and it's good if there are several of them in different data centers. When the sender transfers money, a transaction is registered, which is replicated to all servers, and the money reaches the recipient.

What should we build a blockchain?

In an ideal world, this scheme works fine, but in ours, the following problems arise:

  1. The problem of identifying participants on the one hand and the need for anonymity of transactions on the other. Those. it is necessary to transfer money to a specific recipient and in such a way that no one knows about this transaction, except for the participants in the transaction. Banks have account numbers and bank cards associated with a specific individual or legal entity, and banking secrecy protects information about transactions. And who guarantees that the conditional AnonymousWorldMoney does not use personal data and information about transactions for its own purposes?
  2. How to make sure that the recipient received exactly the amount that was transferred to him? Relatively speaking, the sender transferred $100, and the recipient received $10. The sender comes to the AnonymousWorldMoney office with his receipt, and the clerk shows his version, which says that the sender transferred only $10.
  3. The problem of a non-trusted environment, such as a scam called double-spending. An unscrupulous participant can spend his balance several times until the payment is replicated to all servers. CAP theorem, of course, no one has canceled, and agreement will eventually be reached, but someone will not receive money for the services or goods provided. Therefore, if there is no complete trust in the payment organization or participants in transactions, then it is necessary to build a network based not on trust, but on cryptography.
  4. The conditional AnonymousWorldMoney has a finite number of servers that can become inaccessible unintentionally or through malicious intent.
  5. AnonymousWorldMoney will take its sizeable commission.
  6. Possibility of management. During the operation of Bitcoin, it turned out that people want not only to transfer coins to each other, but also to check the various conditions for passing a transaction, program work scenarios, automatically perform actions depending on the conditions, etc.

How blockchain solves these problems

  1. Participants are identified using a pair of keys: private and public, and the digital signature algorithm uniquely identifies the sender and recipient, leaving their identities anonymous.
  2. Transactions are collected into blocks, the hash of the block is calculated, which is written to the next block. This sequence of recording hashes in blocks gave the name to the blockchain technology, and it also makes it impossible to imperceptibly change / delete blocks or individual transactions from blocks. Thus, if a transaction hit the blockchain, then you can be sure that its data will remain unchanged.
  3. Double-spending fraud is prevented by reaching a consensus on the network about which data to accept as valid and which to discard. In the Bitcoin network, consensus is achieved by PoW (Proof-of-Work).
  4. The reliability of the network is achieved by the fact that the blockchain is public, where each participant can run his own node, get a complete copy of the blockchain, and, moreover, independently begin to check transactions for correctness. It should be noted that modern blockchains allow building not only public (open) but also private (closed) blockchains, as well as using combined schemes.
  5. It will not completely get rid of the commission in the blockchain, because. you have to pay people to maintain the network, but in the blockchain, the need for a commission is proved so convincingly that there is no doubt about its necessity.
  6. Modern blockchains have the ability to implement business logic, which in the blockchain is called Smart Contracts. Smart contract logic is implemented in various high-level languages.

Let's take a closer look at these solutions.

Blockchain architecture

Components of the blockchain

Each participant can run their own node with a full copy of the blockchain (full node). Full nodes that can write transactions to the blockchain are called consensus nodes (witness) or miners (miner). Full nodes that only check the correctness of transactions are called audit nodes (audit). Light Clients (light clients) do not store full copies of the blockchain, but interact with the network using full nodes.
Most users use light clients or web wallets to make transactions. All nodes are connected to each other. With this set of elements, the network architecture becomes more stable:

What should we build a blockchain?

Transaction lifecycle

Let's look at the life cycle of a transaction and break it down piece by piece:

What should we build a blockchain?

Blockchain technologies

Let us dwell in more detail on technical solutions and their relationships with each other.

Identification

Every blockchain transaction must be digitally signed. Therefore, to complete a transaction, each participant must have a pair of keys: private / public. Sometimes a pair of keys is called a wallet (wallet), because. the keys are uniquely linked to a unique digital address and a member's balance. In reality, keys and addresses are just strings of numbers in different number systems. Examples of keys and wallet address:

Private key: 0a78194a8a893b8baac7c09b6a4a4b4b161b2f80a126cbb79bde231a4567420f
Public key: 0579b478952214d7cddac32ac9dc522c821a4489bc10aac3a81b9d1cd7a92e57ba
Address: 0x3814JnJpGnt5tB2GD1qfKP709W3KbRdfb27V

To create a digital signature in blockchains, an algorithm based on elliptic curves is used: Elliptic Curve Digital Signature Algorithm (ECDSA). For its operation, the private key (256 bit number) is usually taken at random. The number of key options is 2 to the power of 256, so we can talk about the practical impossibility of matching private key values.

Further, the public key is obtained from the private key by multiplying its value by the coordinates of a point located on an elliptic curve, resulting in the coordinates of a new point on the same curve. This action ensures that a key pair is obtained that is suitable for digitally signing transactions. Finally, the wallet address is uniquely calculated from the public key.

There are tons of articles detailing the cryptography used in the blockchain, such as: Bitcoin in a Nutshell

The private key must be strictly secret and kept secure. The public key is known to everyone. If the private key is lost, access to the asset (coins) cannot be restored and the money will be lost forever. Therefore, the task of secure storage of private keys is extremely relevant, because. this is not a bank where you can always come with a passport and restore your account. There is a whole industry for the production of so-called cold crypto wallets, similar to flash drives:

What should we build a blockchain?

or you can use more reliable methods, for example, knock out the value of the private key on the tokens:

What should we build a blockchain?

  Transactions

More details about the transaction structure can be found in the article. Bitcoin in a Nutshellβ€”Transaction. It is important for us to understand that each transaction has at least the following data:

From: 0x48C89c341C5960Ca2Bf3732D6D8a0F4f89Cc4368 - Ρ†ΠΈΡ„Ρ€ΠΎΠ²ΠΎΠΉ адрСс отправитСля
To: 0x367adb7894334678b90Π°fe7882a5b06f7fbc783a - Ρ†ΠΈΡ„Ρ€ΠΎΠ²ΠΎΠΉ адрСс получатСля
Value: 0.0001 - сумма Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ
Transaction Hash: 0x617ede331e8a99f46a363b32b239542bb4006e4fa9a2727a6636ffe3eb095cef - Ρ…ΡΡˆ Ρ‚Ρ€Π°Π½Π·Π°ΠΊΡ†ΠΈΠΈ

Further, the transaction is signed with a private key and sent out (see details on the operation of the protocol Bitcoin in a nutshell-Protocol) to all nodes in the blockchain that check transactions for validity. The transaction verification algorithm is non-trivial and includes two dozen steps.

Transaction blocks

After checking the validity of transactions, the nodes form blocks from them. In addition to transactions, the hash of the previous block, the number (Nonce counter) is written to the block, and the hash of the current block is calculated using the SHA-256 algorithm. The hash must have the specified complexity conditions. For example, in the Bitcoin network, the hash difficulty automatically changes once every 2 weeks, depending on the power of the network, so that a block is generated approximately once every 10 minutes. The difficulty is determined by the following condition: the found hash must be less than a predetermined number. If this condition is not met, then 1 is added to the Nonce, and the hash calculation is repeated. To select a hash, the Nonce field is used, because this is the only data in the block that can be changed, the rest must remain unchanged. A valid hash must have a certain number of leading zeros, such as one of the real hashes:

000000000000000000000bf03212e7dd1176f52f816fa395fc9b93c44bc11f91

Successfully finding the hash is proof of work (Proof-of-Work, PoW) for Bitcoin or Ethereum networks. The process of finding hashes is called mining, similar to gold mining. The name quite accurately defines the essence of the process, because. there is a simple enumeration of options, and if someone has found a suitable hash, then this is really good luck. It's like finding a real gold nugget in tons of waste rock. The block reward is now 12.5 BTC, and if you multiply by the current $3900 bitcoin rate, you get more than a kilogram of pure gold. There is something to fight for!

After successfully finding the hash, the block and the found hash itself are written to the blockchain as the next block. More details on the structure of blocks can be found in the article. Bitcoin in a Nutshell-Blockchainand below is a simplified diagram:

What should we build a blockchain?

The blockchain starts with a block that does not yet have the hash of the previous block. There is only one such block in the blockchain and it has its own name Genesis block. The remaining blocks have the same structure and differ only in the number of transactions. Real transactions and blocks currently being created in Bitcoin or Ethereum can be viewed in Block Explorer.

The size of blocks in Bitcoin is limited to 1Mb, and with a minimum amount of information in a transaction of about 200 bytes, the maximum amount in a block can be about 6000 transactions. From here, by the way, follows the performance of Bitcoin, which everyone laughs at: a block is generated approximately once every 10 minutes * 60 seconds = 600 seconds, which gives a formal performance of about 10 TPS. Although in fact - this is not performance, but a consciously implemented algorithm of work. In Ethereum, for competition, they simply made the block generation time 15 seconds. and productivity formally soared. Therefore, in blockchains using PoW as a consensus, it is generally pointless to compare performance, because it directly depends on the complexity of the cache calculation, which can be assigned to any.

Forks

But what happens if, for example, several nodes have found hashes that satisfy the complexity conditions, but are different in meaning (in other words, they have come to different consensuses) and write the blocks to the blockchain? Let's see how the blockchain protects itself from this situation. In this case, the so-called fork ('fork') occurs, and the blockchain has two versions of the chain:

What should we build a blockchain?

What happens next? Next, part of the network starts working on block N + 2 from one chain, and part from another:

What should we build a blockchain?

Some of these blocks will be found earlier and sent to the blockchain, and then, according to the rules, the blockchain will have to switch to a longer chain and cancel all transactions from the alternative block:

What should we build a blockchain?

At the same time, a situation may arise when the participant’s transaction was in only one of the fork blocks, which was canceled. Therefore, in order to be sure that the desired transaction is written to the blockchain, there is a general recommendation - before trusting the transaction, you must wait until the next few blocks are added to the blockchain. Recommendations for how many blocks to wait for different blockchains vary. For example, for the Bitcoin network, the minimum is 2 blocks, the maximum is 6.

The same picture with the fork of blocks will be observed during the so-called 51% attack - this is when a group of miners will try to grow an alternative chain of blocks, seeking to cancel the chain with their fraudulent transactions. Although at present, instead of fraud, it is more profitable to spend your power on honest mining.

Consensus

To write a block to the blockchain, the network must reach a consensus. Let's remember the task of reaching consensus in computer communication networks. The problem is formulated as the task of the Byzantine generals BFT (Byzantine fault tolerance). Omitting a picturesque description of the problems of the Byzantine army, the problem can be formulated as follows: how can the nodes of the network come to a common result if some of the nodes of the network can deliberately distort them. Existing algorithms for solving the BFT problem show that the network can function correctly if there are less than 1/3 of fraudsters. Why has BFT consensus not been implemented in the Bitcoin network? Why was it necessary to use PoW? There are several reasons:

  • BFT works well with a small fixed set of nodes, but on a public blockchain, the number of nodes is unpredictable and, moreover, nodes can turn on and off randomly.
  • It is necessary to motivate people to run blockchain nodes. For this, people should be rewarded. In BFT, there is formally nothing to receive a reward for, but what the reward is for in PoW is clear to everyone on an intuitive level: for the electricity consumed by the processor in the process of finding the block hash.

In addition to PoW, there are several other consensuses that are used in modern blockchains, for example:

  • PoS (Proof-of-Stake) - in the blockchain Hyperledger
  • DPoS (Delegated Proof-of-Stake) - on the blockchain BitShares
  • BFT modifications: SBFT (Simplified BFT) and PBFT (Practical BFT), for example, in the blockchain Exonum

Let's dwell on the PoS consensus for a bit, because. it is PoS and its varieties that are most widely used in private blockchains. Why in private? On the one hand, the characteristics of PoS are better than those of PoW, as to achieve consensus, less computing resources are needed, which means that the speed of writing data to the blockchain increases. But on the other hand, there are more opportunities for fraud in PoS, therefore, in order to neutralize this, all participants in the blockchain must be known.

The PoS consensus is based on the choice of a node that can write a block with transactions to the blockchain, depending on the amount of funds in the account, or rather, not in the account, but in pledge, i.e. the more funds you have in pledge, the more likely the network will choose your node to write the block. The deposit will not be returned if the block is invalid. Thus, protection against fraud is implemented. There are the following variations of PoS:

  • Delegated PoS (DPoS) consensus divides participants into β€œvoters” and β€œvalidators”. Coin holders (voting participants) delegate their right to verify and record transactions in the blockchain to other participants. Thus, the validators do all the computing work and get rewarded for it, and the presence of voting participants guarantees the honesty of the validators, because. they can be changed at any time.
  • LPoS (Leased Proof-of-Stake) consensus allows you to lease your funds to other nodes so that they have a better chance of validating blocks. That. you can receive a commission for transactions, while not participating in the transaction verification itself and block mining.

There are a number of consensuses that have not yet become widespread, I will simply list them here for information, and an overview of the consensus algorithms themselves can be found, for example, in the article: Blockchain Consensus Algorithms.

  • PoET (Proof-of-Elapsed Time)
  • PoC (Proof-of-Capacity)
  • PoB (Proof-of-Burn)
  • PoWeight (Proof-of-Weight)
  • PoA ( Proof-of-Activity ) - PoW + PoS
  • PoI (Proof-of-Importans)

Reliability and blockchain deployment models

Public blockchain

Stability Public or other name permissionless blockchain is achieved by the fact that everyone can connect and view information or even connect their own node, and trust is built on PoW consensus.

Private blockchain

Private or Private Permission Blockchain. In these blockchains, only a certain group of participants (organizations or people) has access to information. Such blockchains are built by organizations in order to increase the overall benefit or efficiency. Their reliability is ensured by the common goals of the participants and the PoS and BFT consensus algorithms.

Blockchain Consortium

Exist Consortium or public permission blockchain. These are blockchains to which anyone can connect to view, but a participant can add information or connect his node only with the permission of other participants. Such blockchains are built by organizations in order to increase trust from customers or consumers of products or society as a whole. Here reliability is also achieved by the presence of trust between the participants and the same PoS and BFT consensus algorithms.

Smart Contracts

In the blockchains implemented after Bitcoin, the ability to execute smart contracts has been added to one degree or another. In essence, a smart contract is a transaction in which a program code is placed for execution. Smart contracts on the Ethereum network run on the EVM (Ethereum Virtual Machine). To start executing a smart contract, it must be explicitly launched by another transaction, or the preconditions for execution must be met. The results of the execution of the smart contract will also be recorded in the blockchain. Getting data from outside the blockchain is possible, but extremely limited.

What business logic can be implemented using a smart contract? In fact, not so much, for example, checking conditions against data from the blockchain, changing the owners of digital assets depending on these conditions, writing data to permanent storage within the blockchain. The logic is implemented in a special high-level language Solidity.

A classic example of the functionality that is implemented using smart contracts is the release of tokens for ICO. For example, I implemented a smart contract to issue a modest 500 AlexTokens. By link in Etherscan is

smart contract source code in Solidity language

pragma solidity ^0.4.23;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
**/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
**/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
**/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
**/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
**/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
**/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
**/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
**/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic interface
* @dev Basic ERC20 interface
**/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
**/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
**/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
**/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
**/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
**/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
**/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
**/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
**/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
**/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
**/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Configurable
* @dev Configurable varriables of the contract
**/
contract Configurable {
uint256 public constant cap = 1000000000*10**18;
uint256 public constant basePrice = 100*10**18; // tokens per 1 ether
uint256 public tokensSold = 0;
uint256 public constant tokenReserve = 500000000*10**18;
uint256 public remainingTokens = 0;
}
/**
* @title CrowdsaleToken 
* @dev Contract to preform crowd sale with token
**/
contract CrowdsaleToken is StandardToken, Configurable, Ownable {
/**
* @dev enum of current crowd sale state
**/
enum Stages {
none,
icoStart, 
icoEnd
}
Stages currentStage;
/**
* @dev constructor of CrowdsaleToken
**/
constructor() public {
currentStage = Stages.none;
balances[owner] = balances[owner].add(tokenReserve);
totalSupply_ = totalSupply_.add(tokenReserve);
remainingTokens = cap;
emit Transfer(address(this), owner, tokenReserve);
}
/**
* @dev fallback function to send ether to for Crowd sale
**/
function () public payable {
require(currentStage == Stages.icoStart);
require(msg.value > 0);
require(remainingTokens > 0);
uint256 weiAmount = msg.value; // Calculate tokens to sell
uint256 tokens = weiAmount.mul(basePrice).div(1 ether);
uint256 returnWei = 0;
if(tokensSold.add(tokens) > cap){
uint256 newTokens = cap.sub(tokensSold);
uint256 newWei = newTokens.div(basePrice).mul(1 ether);
returnWei = weiAmount.sub(newWei);
weiAmount = newWei;
tokens = newTokens;
}
tokensSold = tokensSold.add(tokens); // Increment raised amount
remainingTokens = cap.sub(tokensSold);
if(returnWei > 0){
msg.sender.transfer(returnWei);
emit Transfer(address(this), msg.sender, returnWei);
}
balances[msg.sender] = balances[msg.sender].add(tokens);
emit Transfer(address(this), msg.sender, tokens);
totalSupply_ = totalSupply_.add(tokens);
owner.transfer(weiAmount);// Send money to owner
}
/**
* @dev startIco starts the public ICO
**/
function startIco() public onlyOwner {
require(currentStage != Stages.icoEnd);
currentStage = Stages.icoStart;
}
/**
* @dev endIco closes down the ICO 
**/
function endIco() internal {
currentStage = Stages.icoEnd;
// Transfer any remaining tokens
if(remainingTokens > 0)
balances[owner] = balances[owner].add(remainingTokens);
// transfer any remaining ETH balance in the contract to the owner
owner.transfer(address(this).balance); 
}
/**
* @dev finalizeIco closes down the ICO and sets needed varriables
**/
function finalizeIco() public onlyOwner {
require(currentStage != Stages.icoEnd);
endIco();
}
}
/**
* @title LavevelToken 
* @dev Contract to create the Lavevel Token
**/
contract AlexToken is CrowdsaleToken {
string public constant name = "AlexToken";
string public constant symbol = "ALT";
uint32 public constant decimals = 18;
}

and the binary representation as the network sees it

60806040526000600355600060045533600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600560146101000a81548160ff021916908360028111156200006f57fe5b0217905550620001036b019d971e4fe8401e74000000600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546200024a6401000000000262000b1d179091906401000000009004565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550620001986b019d971e4fe8401e740000006001546200024a6401000000000262000b1d179091906401000000009004565b6001819055506b033b2e3c9fd0803ce8000000600481905550600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef6b019d971e4fe8401e740000006040518082815260200191505060405180910390a362000267565b600081830190508281101515156200025e57fe5b80905092915050565b611cb880620002776000396000f300608060405260043610610112576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146104c7578063095ea7b31461055757806318160ddd146105bc57806323b872dd146105e7578063313ce5671461066c578063355274ea146106a3578063518ab2a8146106ce57806366188463146106f957806370a082311461075e57806389311e6f146107b55780638da5cb5b146107cc578063903a3ef61461082357806395d89b411461083a578063a9059cbb146108ca578063bf5839031461092f578063c7876ea41461095a578063cbcb317114610985578063d73dd623146109b0578063dd62ed3e14610a15578063f2fde38b14610a8c575b60008060008060006001600281111561012757fe5b600560149054906101000a900460ff16600281111561014257fe5b14151561014e57600080fd5b60003411151561015d57600080fd5b600060045411151561016e57600080fd5b3494506101a7670de0b6b3a764000061019968056bc75e2d6310000088610acf90919063ffffffff16565b610b0790919063ffffffff16565b9350600092506b033b2e3c9fd0803ce80000006101cf85600354610b1d90919063ffffffff16565b111561024c576101f66003546b033b2e3c9fd0803ce8000000610b3990919063ffffffff16565b915061022e670de0b6b3a764000061022068056bc75e2d6310000085610b0790919063ffffffff16565b610acf90919063ffffffff16565b90506102438186610b3990919063ffffffff16565b92508094508193505b61026184600354610b1d90919063ffffffff16565b6003819055506102886003546b033b2e3c9fd0803ce8000000610b3990919063ffffffff16565b6004819055506000831115610344573373ffffffffffffffffffffffffffffffffffffffff166108fc849081150290604051600060405180830381858888f193505050501580156102dd573d6000803e3d6000fd5b503373ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a35b610395846000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b1d90919063ffffffff16565b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055503373ffffffffffffffffffffffffffffffffffffffff163073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef866040518082815260200191505060405180910390a361045184600154610b1d90919063ffffffff16565b600181905550600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc869081150290604051600060405180830381858888f193505050501580156104bf573d6000803e3d6000fd5b505050505050005b3480156104d357600080fd5b506104dc610b52565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561051c578082015181840152602081019050610501565b50505050905090810190601f1680156105495780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561056357600080fd5b506105a2600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610b8b565b604051808215151515815260200191505060405180910390f35b3480156105c857600080fd5b506105d1610c7d565b6040518082815260200191505060405180910390f35b3480156105f357600080fd5b50610652600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c87565b604051808215151515815260200191505060405180910390f35b34801561067857600080fd5b50610681611041565b604051808263ffffffff1663ffffffff16815260200191505060405180910390f35b3480156106af57600080fd5b506106b8611046565b6040518082815260200191505060405180910390f35b3480156106da57600080fd5b506106e3611056565b6040518082815260200191505060405180910390f35b34801561070557600080fd5b50610744600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061105c565b604051808215151515815260200191505060405180910390f35b34801561076a57600080fd5b5061079f600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506112ed565b6040518082815260200191505060405180910390f35b3480156107c157600080fd5b506107ca611335565b005b3480156107d857600080fd5b506107e16113eb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561082f57600080fd5b50610838611411565b005b34801561084657600080fd5b5061084f6114ab565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561088f578082015181840152602081019050610874565b50505050905090810190601f1680156108bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156108d657600080fd5b50610915600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506114e4565b604051808215151515815260200191505060405180910390f35b34801561093b57600080fd5b50610944611703565b6040518082815260200191505060405180910390f35b34801561096657600080fd5b5061096f611709565b6040518082815260200191505060405180910390f35b34801561099157600080fd5b5061099a611716565b6040518082815260200191505060405180910390f35b3480156109bc57600080fd5b506109fb600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611726565b604051808215151515815260200191505060405180910390f35b348015610a2157600080fd5b50610a76600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611922565b6040518082815260200191505060405180910390f35b348015610a9857600080fd5b50610acd600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506119a9565b005b600080831415610ae25760009050610b01565b8183029050818382811515610af357fe5b04141515610afd57fe5b8090505b92915050565b60008183811515610b1457fe5b04905092915050565b60008183019050828110151515610b3057fe5b80905092915050565b6000828211151515610b4757fe5b818303905092915050565b6040805190810160405280600981526020017f416c6578546f6b656e000000000000000000000000000000000000000000000081525081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600154905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610cc457600080fd5b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515610d1157600080fd5b600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515610d9c57600080fd5b610ded826000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b3990919063ffffffff16565b6000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610e80826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b1d90919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610f5182600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b3990919063ffffffff16565b600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190509392505050565b601281565b6b033b2e3c9fd0803ce800000081565b60035481565b600080600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490508083111561116d576000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611201565b6111808382610b3990919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b8373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a3600191505092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561139157600080fd5b60028081111561139d57fe5b600560149054906101000a900460ff1660028111156113b857fe5b141515156113c557600080fd5b6001600560146101000a81548160ff021916908360028111156113e457fe5b0217905550565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561146d57600080fd5b60028081111561147957fe5b600560149054906101000a900460ff16600281111561149457fe5b141515156114a157600080fd5b6114a9611b01565b565b6040805190810160405280600381526020017f414c54000000000000000000000000000000000000000000000000000000000081525081565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561152157600080fd5b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054821115151561156e57600080fd5b6115bf826000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b3990919063ffffffff16565b6000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611652826000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b1d90919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b60045481565b68056bc75e2d6310000081565b6b019d971e4fe8401e7400000081565b60006117b782600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b1d90919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515611a0557600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151515611a4157600080fd5b8073ffffffffffffffffffffffffffffffffffffffff16600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a380600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6002600560146101000a81548160ff02191690836002811115611b2057fe5b021790555060006004541115611c0a57611ba5600454600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b1d90919063ffffffff16565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc3073ffffffffffffffffffffffffffffffffffffffff16319081150290604051600060405180830381858888f19350505050158015611c89573d6000803e3d6000fd5b505600a165627a7a723058205bbef016cc7699572f944871cb6f05e69915ada3a92a1d9f03a3fb434aac0c2b0029

More details about smart contracts can be found in the article: What are smart contracts in Ethereum.

Conclusion

We have listed the technologies on which modern blockchains are built and how they are related to each other. Now let's formulate which tasks can be solved using the blockchain, and which solutions will be, at best, inefficient. So, the use of blockchain is not necessary if:

  • Transactions are made in a trusted environment;
  • The presence of a commission of intermediaries does not worsen the life of the participants;
  • Participants do not have property that can be represented as digital assets;
  • There is no distribution in digital assets, i.e. value is owned or supplied by only one participant.

What is the future of blockchain? Now we can only assume the possible ways of development of blockchain technologies:

  • Blockchain will become the same conventional database technology as, for example, SQL or NoSQL for solving its own specific range of tasks;
  • Blockchain will become a widespread protocol, like HTTP for the Internet;
  • Blockchain will become the basis for the new financial and political system of the planet!

In the next part, we will see what blockchains currently exist and what they are used for in different industries.

This is just the beginning!

Source: habr.com

Add a comment