The history of blockchain
Underground Organization: Cypherpunk
What are we talking about? Math, cryptography, computers, digital currencies
- Wikileaks founder Julian Assange
- Bittorrent download by Brem Cohen
- Tim Berners-Lee, the inventor of the WWW
- The man behind the smart contract concept: Nick Saab
- Facebook founder: Sean Parker
- In the hearing
- Adam Back invented Hashcash using POW
- Haber/Stornetta proposed a time-stamp method to ensure the security of digital files
- Dai Wei invented B-Money, with its emphasis on peer-to-peer transactions and immutable records
- Hal Finney launches’ crypto Cash ‘
- Bitcoin: A Peer-to-peer Electronic Cash System by Satoshi Nakamoto, 2008
- Application scenarios
- Assets: digital asset issuance, payment (cross-border payment), transaction and settlement
- Bookkeeping: Equity transaction, supply chain finance, business points
- Do not tamper with: traceability, crowdfunding, medical proof, proof of existence
- Peer-to-peer: sharing economy, Internet of Things
- Privacy: Anonymous transactions
- Advantages – property under your own control – no inflation – no counterfeit money – good liquidity
How are the accounts verified?
- Hash function: Hash(original information) = summary information
- The same original information and the same hash function always get the same summary information
- Any slight change to the original information hashes out an unrecognizable summary of the information
- The original information cannot be back-inferred from the abstract information
Account Ownership
Password -> Private key asymmetric encryption (transaction signature) Signing and verification are inverse operations: the payment address is a public key, the signature encrypts the digest, and verification is the process of decryption (decrypted with the payer’s address and signature information), and then the transaction digest is obtained
P.S. there is no privacy, so there is no privacy. Security (do not disclose private keys)
Why do you keep the books?
- Billing: Hash packaging process
- Consume resources
- reward
Consensus mechanism
Two nodes complete the proof of work at the same time, whose block is used?
- No arbitral award
- They said to use my block
Why abide by the agreement?
- A node workload is only valid if other nodes agree on it
- Blockchain with the largest cumulative workload (standalone, longest extended chain)
- Proof of work + longest chain = block used
POW: Proof of work
After-class myth?
- Bitcoin P2P network, how does each node communicate (point to point)?
- Block structure Merkle tree
- Unspent Transaction Output
- Bitcoin White Paper
Implementation of core principles of blockchain technology
Don’t repeat, everyone can watch the video while watching lecturer 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 } }Copy the code
The data type
- State variable unsigned integer uint
- function
function setA(uint x) public { a = x; }
- Event Set_A(uint a); Emit Set_A(x);
- structure
struct Pos { int lat; int lng; }
- Function modifier
modifier owner () {}
Modify functionsfunction mine() public owner{}
Execute the contents of owner before executing the mine function
Value Type 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
- On digital and encryption functions
- Address and contract
Error handling
State related functions: Assert (internal logic errors),require(external errors)
Send half of the values pragma solidity A0.4.20; Contract Sharer{function sendHalf(address addr)public payable returns (uint balance) {require(MSG. Value %2==0); Uint balanceBeforeTranfer = this. The balance; Addr. Transfer (MSG. The value / 2); Assert (enclosing the balance = = balanceBeforeTranfer - MSG. The value / 2); Return this. The balance; }Copy the code
parameter
- The input parameters
- Output parameters
- The named parameter {} is similar to Python
- The value of a parameter destruct 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; The mul = a * b; Function testSimpleInput() public constant returns (uint sum,uint mul){(sum,mul)=simpleInput({b:3,a:1}); 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); Only the values of y and z (,y,z) = f(); (x,) = (1,); }Copy the code
Control structure
No Switch goto, everything else
visibility
public
A public function is part of a contract interface and can be invoked internally, or via a message. For state variables of type public, an accessor is automatically created. Function default visibility public
private
Private functions and state variables are accessible only in the current contract, not in the inherited contract.
external
External functions are part of the contract interface and can only be called with message calls. In the same contract, we can call with this (message call). If we only receive external calls, we should use external internal functions and state variables that can only be accessed internally. As 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
- The constructor
- The view function (constant/view (priority)) does not modify state variables
- Pure functions do not read variables and do not modify them
- Rollback function nameless function, passive call function
- Public is also a function, since an accessor is automatically created
Contract Test{uint internal data; Constructor (uint a)public{data=a; The event EVENTA (uint a); Function testView()public view returns(uint){//data=1; / / emit EVENTA (1); Return the data. } function f()public pure returns(uint){return 1*2; } there is another contract to transfer to Test contract, Function ()public payablel{} contract Caller {function callTest(Test Test)public { test.send(ether); }}Copy the code
Blockchain decentralized application development
Simple token contracts
Pragma solidity ^ 0.4.20; Contract MyToken {store the balanceOf each account mapping (address => uint256) public balanceOf; Constructor (uint256 initialSupply) public {} // Give the creator all initial tokens} 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 } }Copy the code
Standard token contracts
This is based on version 20, which was the latest version, and has 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]; }}Copy the code
npm i -g truffle
truffle init
Copy the code
Contract deployment
var Adoption = artifacts.require("Adoption"); module.exports = function(deployer) { deployer.deploy(Adoption); }; Configure truffle. Run the truffle migrate commandCopy the code
Contract test cases
Pragma solidity ^ 0.4.17; import 'truffle/Assert.sol'; import 'truffle/DeployedAddresses.sol'; import '.. /contracts/Adoption.sol'; Get the test contract 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."); } / / test adopted address function testGetAdopterAddressByPetid () public {address expected = this; address adopter = adoption.adopters(8); Assert.equal(adopter, expected, "Owner of pet ID 8 should be recorded."); } / / test all the adoption of the 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."); }}Copy the code