Cryptokitties Source Analysis: Cat's correct posture!

Source: Internet
Author: User
Tags modifier modifiers

Today I would like to introduce a "block chain" application cryptokitties that has recently been compared with fire, this application essentially realizes the function is the electronic cat breeding and trading two functions, although the function is relatively simple, but plus block chain this powerful bottom technology as a support, let it in the whole industry set off a wave of upsurge, It has even led to the blockage of the Ethernet main network, allowing the number of unacknowledged transactions in the ether to rise from the usual 2.5k to 15k, and other transactions in the network have also been greatly affected. The entire project has a total of 2000 lines of code, which also contains detailed comments so that even students who have not learned solidity programming (for example, me) can easily read the code through the Ethernet square browser (https://etherscan.io/address/ 0x06012c8cf97bead5deae237070f9587f8e7a266d#code) to view directly, or to view another online version (Https://ethfiddle.com/09YbyJRfiI), The latter one supports online compilation and debugging. High Level Overview

As a senior (pseudo) Cat later patients, first of all want to introduce this project, so that many late night cat addiction attack Night sleep patients find the harbor of the soul. Project official website: https://www.cryptokitties.co/, the operation is actually relatively simple, first you have to have the Ethernet currency, and then install a chrome plug-in, that is, a ETH lightweight wallet, then you can enter the marketplace choose the right little cute, As a deal failed several times to recommend that you buy 8-page after the meow, because the previous pages have been basically bought away, but the transaction is still waiting for confirmation, the site updates some delay, this time if you buy it is likely to waste gas (transaction costs). Each meow is determined by a 256-digit integer DNA, no sex, and any two of them that have no direct kinship are breeding offspring, and parents and siblings cannot reproduce. All of the meow can be linked to the auction market to sell, breeding is to pay fees, other types of transactions only need to pay gas (transaction costs) on the line, but now the network congestion, a large number of unconfirmed transactions still exist, so gas recommended set to 50-60.

In accordance with the contract succession in the project, there are a total of the following contracts:

Contract Kittyaccesscontrol
contract kittybase is kittyaccesscontrol contract kittyownership
are kittybase ERC721
contract kittybreeding is kittyownership
contract kittyauction is kittybreeding
contract Kittyminting is kittyauction
contract Kittycore is kittyminting

So Kittycore is the final application of the contract address, it inherits all the data and methods of the previous contract, let's take a look at the specific implementation of each contract. 1 Kittyaccesscontrol: Access control

The main purpose of this contract is to set up three addresses: Ceo/cfo/coo, and define some function modifiers (http://solidity.readthedocs.io/en/develop/ Contracts.html#function-modifiers) such as Onlyceo/onlycfo/onlyclevel, and so on, then define some functions and add a function The modifier identity allows these functions to be invoked only by a specific role, such as freezing and releasing the entire contract.

Modifier Onlyclevel () {
    require (
        msg.sender = = Cooaddress | |
        Msg.sender = = Ceoaddress | |
        Msg.sender = = Cfoaddress
    );
    _;
}

///...

@dev called by any "c-level" role to pause the contract. Used only when
///  a bug or exploit are detected and we need to limit damage.
function pause () external onlyclevel whennotpaused {
    paused = true;
}

According to the explanation in the code, the original design of this pause () function is designed to reduce the loss of a vulnerability by suspending the contract when the program is compromised, which means that the Clevel member has the absolute right to control the operation of the project. Instead of having to go through the miners ' voting fork for all the decisions in the general block chain, many of the dapp we call are essentially not as decentralized as we think. 2 kittybase: storage structure

This contract defines the basic attributes that each meow contains, the data stored variables during the operation of the contract (each meow owner, hang up the auction house meow, wait for mating meow, etc.) and some basic operating functions (such as Meow's right to transfer, Mew's birth).

First defines the basic properties of meow,

struct Kitty {
    uint256 genes;//Gene
    UInt64 birthtime;//Birth block timestamp
    UInt64 cooldownendblock;//reproduction of the block number
    UI Nt32 Matronid; Mother's ID
    uint32 Sireid//father's ID
    uint32 siringwithid;//If the breeding period is the ID of the current mating object, or 0
    uint16 cooldownindex; Reproductive cooling time
    uint16 generation;//Generation
}

Meow is no sex, the attribute of parents is to see who gave birth to the new meow. All the meow is through the genes to determine the appearance, and this genes is created by a non-open source library, to avoid the parents ' genes to directly infer the new meow gene, thereby reducing the proportion of fancy cat. It's also worth noting that all the meow appearances are resolved by the front-end Web server, which means developers can define which meow is fancy cat, and once the Web server crashes then all the meow except the Cooldownindex will make no difference. This also reflects a defect in the block chain application--it is not possible to store all the application data on the block chain, because the cost of storing data on the chain is too high, it is a question to consider how to center the storage of the data in the future if you want to develop a real, fully-centralized application.

/*** STORAGE ***/

    ///Save all Meow IDs
    kitty[] kitties;

    All Meow IDs to owner's address Map
    mapping (uint256 => addresses) public kittyindextoowner;

    The Mapping
    mapping (address => uint256) of the number of token to owner is ownershiptokencount;

    The Meow ID to be sold to the owner address mapping
    mapping (uint256 => addresses) public kittyindextoapproved;

    The Meow ID to be mated to the address of owner is mapped
    mapping (uint256 => addresses) public sireallowedtoaddress;

    The address of the auction contract, the handling of transactions between users and the system-generated gen0 saleclockauction public saleauction every 15 minutes
    ;

    The contract address of the mating is different from the auction above because the two methods are handled differently
    siringclockauction public siringauction;

This defines all the storage data structures in the contract operation, and it can be seen that there are not many variables stored in total. We then define two functions _transfer () and _createkitty () to transfer the Meow's ownership and create a new meow, both of which can only be invoked from within,

    An internal function is used to create a new meow and then save it, assuming that all the input data is valid, the///function will eventually trigger a brith and transfer event. function _createkitty (uint256 _matronid,//Mother's ID, does not exist is 0 uint256 _sireid,//Father's ID, does not exist is 0 Uint25
        6 _generation,//Current first generation, calculated by caller uint256 _genes,//Gene address _owner//owner) Internal
        Returns (UINT) {//guarantee that the data is within the normal range require (_matronid = = uint256 (UInt32 (_matronid)));
        require (_sireid = = uint256 (UInt32 (_sireid)));

        require (_generation = = uint256 (uint16 (_generation))); The new meow cooldown is decided by GENERATION/2//generation = MAX (mothergeneration, fathergeneration) +1 uint16 cooldowni
        Ndex = UInt16 (_GENERATION/2);
        if (Cooldownindex >) {cooldownindex = 13;
            }//Create new meow kitty memory _kitty = Kitty ({genes: _genes, Birthtime:uint64 (now), cooldownendblock:0, Matronid:uint32 (_matronid), SireiD:uint32 (_sireid), siringwithid:0, Cooldownindex:cooldownindex, Generation:uint16 (
        _generation)}); uint256 Newkittenid = Kitties.push (_kitty)-1;

        Save the new Meow ID//Ensure that the total number of meow is less than 2^32 require (Newkittenid = = uint256 (UInt32 (Newkittenid)));
            Triggers the birth event birth (_owner, Newkittenid, uint256 (_kitty.matronid),

        uint256 (_kitty.sireid), _kitty.genes);

        Allocation of new Meow _transfer (0, _owner, Newkittenid);
    return Newkittenid; }

The above function shows the detailed process of creating a new meow, mainly calculating the new Meow generation, and then allocating the corresponding attributes according to generation. 3 kittyownership: Right of ownership

This part of the main implementation of the Meow ID and the actual Ethernet address to correspond, the implementation of functions, including _owns () and transfer (), etc. involving the ownership of the acquisition or conversion operations, the implementation of relatively simple. 4 kittybreeding: Breeding

The contract contains two of the necessary steps to breed the next-generation meow, breeding relies on an external genetic combination contract (genescience), but the contract is not open source, and the address of the contract is set by the CEO by calling Setgenescienceaddress , that is, the CEO can change the method of gene combination at will.

    function setgenescienceaddress (address _address) external Onlyceo {
        Genescienceinterface candidatecontract = Genescienceinterface (_address);
        Require (Candidatecontract.isgenescience ());
        Genescience = candidatecontract;
    }

Two meow breeding needs to invoke Breedwithauto (), first will check a series of conditions, such as whether the reproduction cost is sufficient, both sides are allowed, whether there is no direct relationship between the two sides, and so on, these conditions are satisfied to call the internal function _breedwith () to reproduce, At the same time, change the reproductive state of both sides and trigger _triggercooldown () to change the next reproductive cooling time, the _breedwith () function finally triggers the pregnant () event, and the Web front-end breeding interface is through the monitoring pregnant () Event to be modified, and call Givebirth () at the time of arrival to produce a new meow.

function Givebirth (uint256 _matronid) external whennotpaused Returns (UINT256) {//through mother

        Pro ID Get Object Kitty storage matron = Kitties[_matronid];

        Verify by Birthtime Whether it is legal to meow require (matron.birthtime!= 0);

        Check whether the mother should give birth to require (_isreadytogivebirth (matron));
        Get the object of the father uint256 Sireid = Matron.siringwithid;

        Kitty Storage sire = Kitties[sireid];
        A uint16 Parentgen = Matron.generation that calculates the generation of a parent;
        if (Sire.generation > matron.generation) {parentgen = sire.generation; //afferent parent gene, call external gene combination function, get new meow gene uint256 Childgenes = Genescience.mixgenes (Matron.genes, Sire.genes, matron

        . cooldownEndBlock-1);
        The new meow owner is set to the mother's owner address owner = Kittyindextoowner[_matronid];

        uint256 Kittenid = _createkitty (_matronid, Matron.siringwithid, Parentgen + 1, childgenes, owner); Clears the mother's mating object, making it possible to reproduce the delete again Matron.siringwithid;

        The number of the pregnant meow minus one pregnantkitties--;

        Send the fee to Father Msg.sender.send (Autobirthfee);
    Returns the new Meow ID return kittenid; }
5 kittyauction: Auction

The auction contract includes buying, selling and breeding, which refers to the provision of a party as a father, to take the reproduction costs and the mother side to obtain the breeding of new meow. According to the developer, they divided the auction contract into several sub contracts, because "the logic is more complex, there is always the risk of bugs, each process into a separate contract, we can not change the main contract to upgrade the child contract." "So this contract provides two functions setsaleauctionaddress () and setsiringauctionaddress to set up the sub contract address to facilitate the upgrade of the child contract. This is really good for the code to fix and upgrade from a security point of view, but on the other hand, the CEO of the contract has the right to arbitrarily change the auction rules. 6 kittyminting: The first generation meow

This part of the contract provides for the number of first-generation meow with a contract, written in a hard-coded form,

Limits the number of cats the contract owner can ever create.
    uint256 Public constant promo_creation_limit = 5000;
    uint256 Public constant gen0_creation_limit = 45000;

5000 refers to the number of meow used to promote, 45000 refers to the contract to produce a first-generation meow limit, the process is produced by calling Createpromokitty () and Creategen0auction (), through Creategen0auction () The resulting meow is directly linked to the auction house, and the price is 1.5来 as the initial price through the average price of the last 5 first-generation meow. Both functions can only be invoked by COO, and creation is a direct pass to the gene, which means that COO can replicate any number of copies up to 5,000, so you think a unique meow may not be as unique as you might think. 7 Kittycore: main contract

The role of the main contract is to control the operation and update of the contract, it inherits all the above contracts, so also includes all the above storage structure and functions. The contract is controlled by the variable paused to stop and run, the setnewaddress () function is used to set the address of the contract update, and the unpaused () function is used to start the contract. Also included are two external call functions Getkitty () and Withdrawbalance (), where Getkitty () is used to read all the properties of each meow, should be used in the background of the Web server, and Withdrawbalance () is used to extract all the balances in the contract, but to retain the cost of pregnant kitties reproduction, as this requires calling the Givebirth () function from the outside. Summary

If you look at the actual operating effect, have to say that this project is very successful, at least so far also occupy a large number of network transactions, as a block chain application, it is also really able to grasp the trend of the times, but from the above code to see there are several problems: all the meow is essentially just a 256-bit integer, The right to interpret is vested in the front end; The CEO has the absolute right to control the application operation, can suspend the contract unconditionally or update the sub contract, but the open source contract has called the non-open source contract (gene Science).

The last one may not be called a problem, but from my point of view open source should be all open source, if the gene science this part of the replacement of the open source of the random gene combination may be better, at least not let others feel that there is anything fishy. But the first two questions are really there, so technically it's not exactly a block-chain application, but it's a good and successful attempt. Reference https://medium.com/loom-network/ Your-crypto-kitty-isnt-forever-why-dapps-aren-t-as-decentralized-as-you-think-871d6acfea https://medium.com/ Loom-network/how-to-code-your-own-cryptokitties-style-game-on-ethereum-7c8ac86a4eb3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.