Shock! I actually got started with blockchain on MOOC.com~

Shock! I actually got started with blockchain on MOOC.com~

The history of blockchain

Underground organization: Cypherpunk

What are we talking about? Mathematics, encryption technology, computer, digital currency

  • Assange, the founder of WikiLeaks
  • Bram Cohen, the author of BT downloads
  • Tim Berners-Lee, inventor of the WWW
  • The proponent of the smart contract concept: Nick Sabo
  • Facebook founder: Sean Parker
  • Satoshi Nakamoto
  • Adam Back invented Hashcash and used POW
  • Haber/Stornetta proposes a time stamp method to ensure the security of digital files
  • Dai Wei invented B-money, emphasizing peer-to-peer transactions and unchangeable records
  • Hal Finney launched "crypto cash"
  • 2008 Satoshi Nakamoto "Bitcoin: A Peer-to-Peer Electronic Cash System"
  • Application scenarios
    • Assets: digital asset issuance, payment (cross-border payment), transaction, settlement
    • Bookkeeping: equity transactions, supply chain finance, business points
    • Cannot be tampered with: traceability, crowdfunding, medical certification, proof of existence
    • Peer to Peer: Sharing Economy, Internet of Things
    • Privacy: anonymous transactions
  • Advantages
    -property only controlled by oneself
    -no inflation
    -no counterfeit banknotes
    -good liquidity

How to verify the ledger?

  • Hash function: Hash (original information) = summary information
  • The same original information can always get the same summary information with the same hash function
  • Any slight change in the original information will hash out an unrecognizable summary information
  • The original information cannot be deduced backwards from the summary information

Account ownership issues

Password->Private key asymmetric encryption technology (transaction signature)
Signature and verification are inverse operations: the payment address is the public key, the signature encrypts the digest, and verification is the process of decryption (decryption with the payer's address and signature information), and then get Trading Summary

Supplement: There is no personal privacy, so privacy cannot be disclosed. Security (Do not reveal the private key)

Why bookkeeping?

  • Bookkeeping: Hash packaging process
  • Consume resources
  • reward

Consensus mechanism

Two nodes complete the proof of work at the same time, whose block is used?

  • No arbitration award
  • Said to use my block

Why abide by the agreement?

  • Node workload is only valid when other nodes agree
  • The blockchain with the largest cumulative workload (independent, extending the longest chain)
  • Proof of Work + Longest Chain = Use Block

POW: Proof of Work

Myth after class?

  • In the Bitcoin P2P network, how do the various nodes communicate (peer-to-peer)?
  • Block structure Merkle tree
  • Bitcoin UTXO and transaction script (Unspent Transaction Output unspent transaction output)
  • Bitcoin white paper

Realization of the core principles of blockchain technology

I won t repeat it, everyone can watch the video while watching the lecturer s blog https://learnblockchain.cn/2017/10/27/build_blockchain_by_python/

Smart contract programming language-solidity

File structure

pragma solidity ^0.4.20;

contract MyToken {
    mapping (address => uint256) public balanceOf;

    constructor(uint256 initialSupply) public {
        balanceOf[msg.sender] = initialSupply;             //Give the creator all initial tokens
    }

    function transfer(address _to, uint256 _value) public {
        require(balanceOf[msg.sender] >= _value);          //Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]);//Check for overflows
        balanceOf[msg.sender] -= _value;                   //Subtract from the sender
        balanceOf[_to] += _value;                          //Add the same to the recipient
    }
}

 

type of data

  • State variable unsigned integer uint
  • function function setA(uint x) public { a = x; }
  • Event event Set_A(uint a); call event emit Set_A(x);
  • structure struct Pos { int lat; int lng;}
  • Function modifier modifier owner () {}modified function function mine() public owner{}performs content owner in the mine before the function is executed

Value Type

Reference Types

Global variables and functions

  • About blocks and transactions
    • msg.sender(address)
    • msg.value(uint)
    • block.coinbase(address)
    • block.difficulty(uint)
    • block.number(uint)
    • block.timestamp(uint)
    • now(uint)
    • tx.gasprice(uint)
  • About error handling
  • About digital and encryption functions
  • Related addresses and contracts

Error handling

The processing method when the program error occurs: Solidity processing method is the fallback state
Related functions: assert (internal logic error), require (external error)

 
pragma solidity A0.4.20 

contract Sharer{

function sendHalf(address addr)public payable returns (uint balance {

require(msg.value %2==0) 

uint balanceBeforeTranfer=this.balance 

addr.transfer(msg.value/2) 

assert(this.balance==balanceBeforeTranfer-msg.value/2) 

return this.balance 

}


 

parameter

  • Input parameters
  • Output parameters
  • Named parameters {} similar to python
  • The value of the parameter destructuring element can be assigned to multiple variables
contract Test{

function simpleInput(uint a,uint b)

public constant returns (uint sum,uint mul){

sum=a+b 

mul=a*b 

function testSimpleInput()

public constant returns (uint sum,uint mul){

(sum,mul)=simpleInput({ b:3,a:1}) 

function f()public constant returns (uint,bool,uint){

return  7,true,2) 

function g) public {
	var (x,y,z) = f();
	(x,z) = (z,x);
	 y z 
	(,y,z) = f();
	(x,) = (1,);
}

 

Control structure

No switch goto, everything else

Visibility

public

Public functions are part of the contract interface and can be called internally or through messages. For public state variables, an accessor is automatically created. Function default visibility public

private

Private functions and state variables can only be accessed in the current contract, and cannot be accessed in the inherited contract.

external

External functions are part of the contract interface and can only be called by message.
In the same contract, this (message call) can be used to call.
If we only receive external calls, we should use external
internal
functions and state variables can only be accessed internally. Such as calling in the current contract or in an inherited contract. The default visibility of state variables is that internal
cannot be called in other contracts

function

  • Constructor
  • View function (constant/view (priority)) does not modify state variables
  • Pure function (pure) does not read or modify variables
  • Unnamed function, rollback function, passive call function
  • In fact, public is also a function, because an accessor is automatically created
contract Test{

uint internal data 

constructor (uint a)public{

data=a 

event EVENTA(uint a) 

function testView()public view returns(uint){
	//data=1 
	//emit EVENTA(1) 
	return data 
	}

function f()public pure returns(uint){
	return 1*2 
	}

 Test callback 
function ()public payablel{
	}
}
contract Caller {
	function callTest(Test test) public {
	 test.send(ether);
	 }
 }


 

Blockchain decentralized application development

Simple token contract

pragma solidity ^0.4.20;

contract MyToken {
	 
    mapping (address => uint256) public balanceOf;

    constructor(uint256 initialSupply) public {
	     
        balanceOf[msg.sender] = initialSupply;             //Give the creator all initial tokens
    }
	 
    function transfer(address _to, uint256 _value) public {
        require(balanceOf[msg.sender] >= _value);          //Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]);//Check for overflows
        balanceOf[msg.sender] -= _value;                   //Subtract from the sender
        balanceOf[_to] += _value;                          //Add the same to the recipient
    }
}

 

Standard token contract

This is based on version 20, which was the latest version at the time, and has now been updated to

pragma solidity ^0.4.20;

contract ERC20Interface {
  string public name;
  string public symbol;
  uint8 public  decimals;
  uint public totalSupply;


  function transfer(address _to, uint256 _value) returns (bool success);
  function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
  function approve(address _spender, uint256 _value) returns (bool success);
  function allowance(address _owner, address _spender) view returns (uint256 remaining);
 
  event Transfer(address indexed _from, address indexed _to, uint256 _value);
   
  event Approval(address indexed _owner, address indexed _spender, uint256 _value);

}

contract ERC20 is ERC20Interface {

    mapping (address => uint256) public balanceOf;
    mapping (address => mapping (address => uint256)) internal allowed;

    constructor() public {
        totalSupply = 100000000;
        name = "MUKE Token";
        symbol = "IMOOC";
        decimals = 0;
        balanceOf[msg.sender] = totalSupply;
    }

  function balanceOf(address _owner) view returns (uint256 balance) {
      return balanceOf[_owner];
  }

    function transfer(address _to, uint _value) public returns (bool success) {
        require(_to != address(0));
        require(_value <= balanceOf[msg.sender]);
        require(balanceOf[_to] + _value >= balanceOf[_to]);

        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;
        emit Transfer(msg.sender, _to, _value);
        return true;
    }

      function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
        require(_to != address(0));
        require(_value <= balanceOf[_from]);
        require(_value <= allowed[_from][msg.sender]);
        require(balanceOf[_to] + _value >= balanceOf[_to]);

        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;

        allowed[_from][msg.sender] -= _value;
        emit Transfer(_from, _to, _value);
        return true;
      }
   	
  function approve(address _spender, uint256 _value) returns (bool success) {
          allowed[msg.sender][_spender] = _value;
    emit Approval(msg.sender, _spender, _value);
    return true;
  }
   
  function allowance(address _owner, address _spender) view returns (uint256 remaining) {
      return allowed[_owner][_spender];
  }

}

 
 npm i -g truffle
 truffle init
 
 

Contract deployment

var Adoption = artifacts.require("Adoption");

module.exports = function(deployer) {
  deployer.deploy(Adoption);
};

 truffle
  truffle migrate
 

Contract test cases

pragma solidity ^0.4.17;

import 'truffle/Assert.sol';
import 'truffle/DeployedAddresses.sol';
import '../contracts/Adoption.sol';

contract TestAdoption {
     
    Adoption adoption = Adoption(DeployedAddresses.Adoption());
	 
    function testUserCanAdoptPet() public {
        uint returnedId = adoption.adopt(8);
        uint expected = 8;
        Assert.equal(returnedId, expected, "Aoption of pet Id 8 should be recorded.");
    }
	// 
    function testGetAdopterAddressByPetid() public {
        address expected = this;
        address adopter = adoption.adopters(8);

        Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded.");
    }
   // 
    function testGetAdopterAddressByPetIdInArray() public {

        address expected = this;

        address[16] memory adopters = adoption.getAdopters();
        Assert.equal(adopters[8], expected, "Owner of Pet Id 8 should be recoded.");
    }
}