...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego

Monday, April 30, 2018

Notes on cross-company business processes


Modelling business processes intern in a company might be totally different as speaking about processes between different companies. The reason for that that companies are built up based on different departments and the major challenge of a corporate business process is to describe the information flow of the department. If we speak about cross company processes however they have a little bit different characteristics. Companies working with each other mostly based on markets, either based on general free markets or some kind of a limited market. Another important difference is that information can not free flow freely, it has very strict private characteristics. As a result, if we want to define cross-company business processes we should much more concentrate and model the markets that are connecting the different enterprises. 

Sunday, April 29, 2018

Generating Solidity from Hyperledger Fabric Composer: asset inheritance


Inheritance can be translated from Hyperledger Composer to Solidity almost one to one. Both frameworks define inheritance among assets or smart contracts and there is the possibility to create abstract assets or smart contracts. The only difference is that Solidity supports multiply inheritance but Fabric Composer not really. 

Creating a blockchain integrated database


Integrating blockchain seems to be pretty straightforward for the first run. We can take an exisiting blockchain solution and validate all of the CRUD operations with the help of the blockchain. As in the following example implemented with Solidity, we can be sure that as soon as the blockchain raises our event, the given operation has been already validated by Ehereum. 

contract DB {

event CRUDOperationEvent (string operation);

    function CRUDOperation (string _operation) {
        CRUDOperationEvent(_operation);
    }
}

Certainly, it is questionable if such an integration makes sense at all, because the performance of the system will be surely dependent on the consensus algorithm itself, meaning that one has to wait for the operation around 15 second. Another issue might be the fact that the database is actually an external element from blockchain, so it is questionable how a real trusted integration can be realized. 

Generating Solidity from Hyperledger Fabric Composer: related assets

One of the idea of Hyperledger Fabric Composer is to have a domain specific language to model complex assets. Besides properties of an asset, connections or relations between assets can be defined as well. Like considering the following example:

asset TestAsset identified by primaryKey{
  o String primaryKey
  o String property1
  o String property2
  --> RelatedAsset relatedAsset
}

asset RelatedAsset{
}

The structure can be translated into several smart-contracts that reference to each other like in the following example:

contract RelatedAsset{
}

contract  TestAsset{
  string primaryKey;
  string property1;
  string property2;
  RelatedAsset public relatedAsset;
  
  function setRelatedAsset(RelatedAsset _relatedAsset) {
      relatedAsset = _relatedAsset;
  }
}

Certainly it is an open question how these contracts are created. On way is that there is an external factory contract that creates and administrates such a creation and calls only the setRelatedAsset function. Another way might be that the contracts realize the CRUD (Create Read Update Delete) operations on their own. 

A totally different way might be to use structs instead of contracts which makes things certainly much cheaper from a gas consumption perspective, however all CRUD operations must be handled externally.

contract Factory{

    struct RelatedAsset{
    }

    struct  TestAsset{
        string primaryKey;
        string property1;
        string property2;
        RelatedAsset  relatedAsset;
    }
}
 



Generating Solidity from Hyperledger Fabric Composer: enums

Translating enums from Hyperledger Fabric Composer to Solidity is pretty straightforward for the first run. You can one to one associate a Fabric Composer enum to a Solidity enum:

Hyperledger Fabric Composer:

enum TestEnum {
  o one
  o two
  o three
}

Solidity:

enum TestEnum {
   one,
   two,   
   three 
}
   
However the exact functioning might be a little bit different from time to time. As an example, in Fabric Composer enums are defined on the global level and handled generally, however in solidity enums are defined on a smart contract level, meaning that if you want to use the same enum  in more variables in several contracts you should define in each of the contracts or put it into an ancestor class and precisely define smart contract inheritance.

Generating Solidity from Hyperledger Fabric Composer: simple assets

Often it is a requirement to model and implement a requirements in different smart contract systems. For such a requirements it is important to know the differences between the different languages and abstraction possibilities. In our serial, we try to investigate the possibilities how Hyperledger Fabric Composer language elements can be translated into Solidity Ethereum.

A simple asset in Hyperledger Fabric Composer has some properties and some kind of a primary key:

asset TestAsset identified by primaryKey{
  o String primaryKey
  o String property1
  o String property2
}

one way to associate it with Solidity is to implement a Solidity smart contract for that, like:

contract TestAsset {
    string primaryKey;
    string property1;
    string property2;
}

However assets are not really handled as individual contracts but rather as a set of crypto-assets that are identified by the primaryKey. As a consequence such contracts should be embedded into a factory contract that creates and administrates the assets. One example might be:

contract TestAssetFactory {
    mapping (string => TestAsset) testAssets;

    function createTestAsset(string _primaryKey) {
       testAssets[_primaryKey] = new TestAsset();  
}}

Another option can be however that instead of contracts we use rather structs and the factory token creates a new struct instead of a new smart contract. From a point of view of gas consumption the second solutions will surely be cheaper. 


Consortium blockchains and business processes


Business processes describing consortium blockchain solutions should be fundamentally different than processes describing the operation of individual companies. The reason for that is that is that companies do not really communicate with  each other in an absolutely free manner. They regard company secrets as a very strong fundamental basis and they cooperate with each other only on a special interfaces. As interface I do not necessarily mean just a technical interface, the cooperation of the two companies usually mean that one provides a service, or sell goods that the other one can buy. So the major cooperation is actually the exchanging of goods and services and not some kind of another information sharing. This implies that best consortium blockchain processes must be able to describe different kind of crypto-assets, the relation, exchange, visibility and access rights of these crypto-assets as a primary goal. They must provide the way of putting most of this logic into the blockhain itself realizing with for example smart contracts and they should provide a way to create and configure things with the help of graphical user interfaces. In this sense Hyperledger Fabric has a good direction, even if they can not provide graphical user interface at the moment.  

Combining conveyor belt with artificial intelligence



Combining a conveyor belt with artificial intelligence is a dream that sounds for the first run pretty much as science fiction. However there a realistic chance of realizing such an algorithms. Let we imagine a configuration space with CU = {cu1,cu2,cu3 ... cuN} different configuration units where each cui configuration unit has a cui = {c1,c2 ... cki} set of different configuration possibilities. General software architectures can be regarded for instance to such systems, they provide many functionalities and which can be configured and put together in many different ways. In this example, we consider the configuration space as independent elements, however in general case they might be dependent from each other. 

A configurable conveyor belt is a subset of subsets of the whole configuration space CB =  {cb1,cb2,cb3 ... cuK}, where each cbi is a subset of a given cui. The cbi elements can be regarded as different steps of the conveyor belt and the elements in each cbi contains the different choices for each step. We can say that the conveyor belt is not configurable if each cbi step contains only one choice. We can say that the conveyor belt is human configurable if it contains 7 plus minus 2 steps and each step contain 7 plus minus 2  configuration choice. A conveyor belt might be hierarchical if each cbi configuration step can be regarded as a whole configuration space with configuration steps and sub-choices.

The major task of a conveyor belt learning algorithm is to analyse different choices of the configuration space and create or estimate a human configurable conveyor belt automatically with the help of statistical analysis or machine learning in order to capture the choice pattern that can be used in most of the situations.  

Domain specific languages can be also regarded in a way as special conveyor belts that are capable of realizing only parts of a theoretical configuration space. Unfortunately there is know known method to integrate with the artificial intelligence or machine learning. Perhaps such a theory could provide the basis for the integration. 

Another open question if conveyor belts can be built up a modular or even modular and hierarchical fashion and if they can be supported by efficient machine learning algorithms. 




Wednesday, April 25, 2018

Blockchain as a decentralized communication channel



From a practical perspective blockchain can be regarded as a decentralized highly available and reliable communication channel between different actors. It is served at the moment rather to transfer value between the different actors without the primary goal to transfer information, however applications could also be imagined where instead besides of value rather information is exchanged. In this sense applications that should be based on a global decentralized event bus can be also imagined based on blockchain. 

Certainly, performance is still an issue, with the current speed of bitcoin or ethereum such an event bus can not be considered to be too performant. However with technologies as Hashgraph such an applications might be easily imagined. With that the question is which use-cases could be considered to be implemented on a distributed ledger technology that focus not only on value exchange, but somehow on information and value exchange ? 

Thursday, April 19, 2018

Blockchain: the new trust layer of the internet

Cryptocurrencies and blockchain technologies are among the best hyped technologies all around the world. Although the technology first appeared in 2009 first as an initiative of a mysterious person called Satoshi Nakamoto the real strengths of the technology hasn't been recognized for a while. The major reason for the recent hype is that the world is getting aware of the technology and trying to understand which use-cases can be efficiently covered by blockchain apart from cryptocurrencies and Bitcoin.  

To understand the real potential of blockhain, the best was is to compare with an old classical protocol internet protocol, like TCP / IP.. Although it sounds technical pretty technical, the TCP / IP protocol is nothing more than a technical cooperation way between different computers for reliable  data transfer. The protocol appeared around fifty years ago, got a little bit more widespread thirty years ago. At first sight it seemed to be a pure technical game for scientific people or tech geeks to exchange information. However nowadays we can already conclude that the TCP/IP protocol has basically changed the world. It is the basic backbone of the internet itself, practically everything that is regard currently as internet or web is based on this technology. It is important to note from a business or marketing perspective that there are many applications of the technology wasn't foreseen thirty years ago. Examples are Facebook or Twitter that are based on this protocol but no-one could predict previously that the become million dollar industries.

From a practical point of view blockchain or distributed ledger technologies are similar to the TCP/IP. They are simply IT, collaboration protocols but instead of reliable data transfer, they realize a trust protocol between different actors. Let we just imagine the situation that there are several actors throughout the world who want to collaborate with each others and exchange value. As an examples, they want to exchange or transfer a currency. These actors are geographically decentralized, they do not know each other, they do not trust each other and actually they do not want to trust each other. Hence they are not necessarily humans, but for examples different IoT devices communication and transferring value with each other. blockchain protocols simply guarantee from an algorithmic level that these actors can exchange value with each other even with such a circumstances.

Traditionally, trust based services were provided by centralized institutes like banks or insurance companies. They provided a working model for many years, however they suffered from many problems, like inefficiency, slowness or sometimes from censorship. Blockchain technology simply disrupts this institutional business model and provides a much faster, cheaper and fairer way for exchanging value or to realize trust based services on the internet.  

There are two major, a little bit controversy applications of blockchain nowadays: cryptocurrencies and token based platform funding (called ICO at the moment) that are disrupting traditional money transfer and corporate funding. It is important to note however, that they are just applications on the protocol. One of the major reason of the Hype that the world is experimenting currently which other classical trust based services can be realized in a more efficient way with the technology.

Certainly, we are pretty much at the dawn of distributed ledger technologies: there are still many technological drawbacks, due to the lack of regulation many scams, and of course classical institutional trust based industries managing billions of dollars won't adapt so easily. Which fields and use-cases will reach the real mainstream adaptation is something that we will probably see in ten-twenty years.




Sunday, April 15, 2018

Notes on decentralized artificial intelligence

Current trends in artificial intelligence, like Singularity.Net, Neureal or Pandora having a little bit the wrong direction. Overall is the idea, that different artificial intelligence components can be somehow marketed and sold with the help of a marketplace which is realized with the help of a blockchain solution and some tokens. However this idea is not really optimal. Distributed ledger should actively help the integration of the different artificial intelligence component, effectively realizing a hierarchical pattern recognition structure. Tokens should not only represent an economic incentive but they should actively carry information among the different pattern recognition components to effectively function as a data bus of the architecture. Certainly classical architectures like blockchain can not really scalled up to carry such a huge amount of information, however with technologies like Hashgraph functioning solution might be carried out.

Certainly, it is a major question if distributed ledger technology is really required, or possibly there is the chance to put everything to a centralized data bus. 

Consortium blockchains and market positioning


Consortium blockchains are pretty hard to sell, because of the fact that they need basically the coordination of several consortium members including negotiating and renegotiating the cooperation among all of the consortium members. To sell such a solution, you do not only sell a product to one enterprise, but possibly to several enterprises, this can be pretty tough. There are however natural business consortiums, sometimes foundations throughout the world which have the basic activity to integrate several exiting companies and to negotiate or re-negotiate different things or to focus on legal process of the different consortium members. Such a natural consortiums can be ideal starting points to position consortium blockchain solutions. 

Friday, April 13, 2018

Notes on designing a cryptoeconomical protocol


Designing a cryptoeconomical protocol is almost as difficult as designing a cryptography protocol even if we consider only the economical part of the system. The economical part should be designed as much on the engineering principles as possible, including at least the following considerations:
- clear strategy what should be incetivized and what should be discouraged. 
- consideration of some economical attacks, like byzantian attack, bribing attacks, collaboration of attackers...
- economic simulations and assessments what should happen in different normal and extreme situations.
- considerations for scaling the network.

Network effect and blockchain forks


Decentralized applications based on the blockchain are heavily dependent on the network effects. The value of each platform will be strongly depend on how many actors use the network. In this sense, public networks have much more chance to reach mainstream adaptation than the consortium ones. It is actually an interesting question which of the consortium blockhain solutions have the chance to reach mainstream adaptation: probably the ones that have public solutions as well. One thing that is however dangerous for public blockchains is the forking. Forking practically splits the community into two competing parts. However because of the network effect, such a split will not half the value of the individual networks but quarters them, with other words halfing the value of the whole network. 

Barriers of consortium blockchain adaptation


The biggest barrier and drawback of the consortium blockchain solutions should not be looked in the technology itself. Consortium blockchain solutions best suited in industry fields with many different actors and companies. Delivering a solutions to such an industrial field require the an efficient coordination between many different companies probably located in many different countries. Such a coordination require very skilled business analyst people and negotiators before the technology roll-out could be even started.  

ICO-s, market liberalization and marketing



From an economical perspective token sales and ICO-s are liberating the funding and venture capital market and big steps for economical and financial equality in the world.

- Demand: You have 10 euros that you want to invest into a start up business, with the classical funding possibilities you did not have the chance.

- Supply: If you want to launch a new business and you need funding, previously you needed banks and business angels, actually very small amount of people in the world really have the possibility to get funding for a new business.

So, practically everybody who wants to ban token sales like Facebook , Google or regulation saying indirectly for a couple of billion people the following message:

You guys born in poor region ? You do not have access for an efficient financial infrastructure to get funding or to invest? That is your fault, you deserve it, we like it that way. Even if there would be an efficient funding infrastructure that you could use, we ban that.


Honestly, I am not an idealist, world works sometimes this way, we have historical examples for that.

However, after saying indirectly fuck off for a couple of billion people it is pretty difficult to make for any of these parties such a marketing that they are the good guys.

Thursday, April 12, 2018

On fairness of transaction ordering in blockchains


Proof of work and mining systems are actually pretty far from being fair regarding transaction ordering. On the one hand the miners in validators in a Proof of Stake system work as local dictators on the set of transactions, meaning that they can select which transactions are put into the next block. This gives on the one hand the possibility to censor or delay certain transactions. How big this delay might be depends on the competition and collaboration of the miners and validators. On the other hand, as the transactions are usually processed based on transaction fees and miners certainly priories the transactions with the higher transaction fee. This gives the possibility for an average user to game the system, in the sense that it can be sure that a higher fee transaction will be surely prioritized over a lower transaction fee, giving for instance the possibility for a successful double spending attack. 

It is an open question if a blockchain protocol can designed in a fair ordering way. Other distributed ledger technologies like Hashgraph has the fair ordering property.  

Directed decentralized evolution


Decentralized systems supported by, like blockchain or distributed ledger provide the way of creating systems in a self improved way controlled by some kind of a directed evolutionary algorithm. If we consider bitcoin and the mining evolution, the bitcoin protocol directly makes incentives for a directed decentralized evolution resulting the appearance of the more and more efficient and advanced mining devices. Another interesting example might be the cryptokitties application, in which the appearance of the different digital lifeforms are controlled by a market mechanisms. 

On public blockchains and open innovation


There are several business model in the blockchain space at the moment, like public blockchains that are pretty much controversially at the moment like from Ethereum and of course the Hyperledger that is carried out in a classical business way installing nodes at different consortium members and doing project management in a classical way. The major advantage is however for a public blockchain solution that it maximally supports open innovation. If you are a developer or a couple of developers, you can easily deploy your smart contracts or DApp to the open blockchain and realize revenue on that. Classical consortium blockchains are playground of the big companies, having classical sales channels, requirement engineering, project management and organisational structures. Such a construct usually kills every kind of a innovation.

If project Hyperledger or Microsoft Azure Blockchain wants to keep up with the exponential changing blockchain world they need to create at least semi public blockchains with internal tokenomics, at which even if the nodes are hosted by different consortium members, every developer has the potential to create and host his own DApp solution and has the potential to earn money with that. 

Hackatons do not support open innovation.
The possibility of creating DApp-s by developers and realizing cash-flow on that without worrying on infrastructure or any big enterprise structure does support open innovation.   

public - semi public and consortium blockchain platforms


In usual blockchain frameworks there are two major ways of defining the general visibility:
- public blockchain: the nodes can be run by anybody, even by hackers. The transactions are visible to everybody as well and practically the whole world can participate. 
- consortium blockchain: the nodes are operated by certain consortium members, and these members have access to the transactions and the whole blockchain content as well. 

There might be a third solution between public and consortium scenarios, let we call it a semi public blockchain. In this version the peers are operated by a consortium with known members, but the network itself fully public meaning that everybody can participate on the transaction side and everybody can deploy and operate smart contracts or decentralized applications on top of the network without requiring a permission from the consortium of the infrastructure side. Such scenario is proposed for example by the Hedera Hashgraph. 

Wednesday, April 11, 2018

Notes on stable cryptocurrency


Designing a stable cryptocurrency is a pretty difficult thing, even if it is possible at all. One thing that might work if the cryptocurrency is "backed" by a digital asset for that we can estimate both the supply and the demand side. Such a digital asset might be for example storage or computation. Both for storage and for computation we can estimate the supply side, which is like the Moore's rule and probably we can estimate the demand as well based on industry trends or historical data. The only thing that we have to do is to design a cryptocurrecny with a certain monetary policy in a way that the monetary policy mimics somehow the price of the backed asset. Certainly, there might be a possibility for unexpected changes in supply or demand, like for instance the appearance of a brand new technology, so the possibility should be given for manually monetary policy adjusting.   

Saturday, April 7, 2018

Permissioned versus public or private transaction in blockchains

It is important to note that if we regard transaction privacy of a blockchain system, there might be two different categories to consider:
transaction privacy: if a transaction visibility is public or private
- transaction permission: here we usually consider something on a higher abstraction level than simple transaction. As an example, something as cryptoasset. In this sense it makes sense to imagine systems where different transactions can be associated with different permissions. 

Certainly, there is an additional dimension that can be considered: it is the publicity of the P2P nodes of the system. 

The different combinations are shown on the following diagram:


1. Systems like Bitcoin or Ethereum are public and non-permissioned. Certainly, there is always a minimum default permission even at non-permissioned systems: only the owner of the private key can spend or transfer the asset.
2. We would expect from a voting system that is private and non-permissioned, meaning that everyone can participate but the voting itself is not visible directly on the blockchain. Cryptocurrencies like Dash or ZCash are developed in the similar direction as well. 
3. A Land title system would have the properties of being permissioned and public.   
4. Last but not least a typical banking application would have both the characteristics of being permissioned and private. Blockchain frameworks as Hyperledger Fabric are able to realize such an applications. 

Wednesday, April 4, 2018

Comparing Ethereum with Hashgraph

Based on the framework of the previous blog and dimensions, we can compare Ethereum with the new emerging technology called Hashgraph. The characteristics of Ethereum can be seen on the following picture:


And similarly the characteristics of Hashgraph can be seen on the following picture:



Comparing the two frameworks, we can see that there are differences in two areas. First of all Hashgraph is at the moment rather an extended consensus mechanism and not a full scale distributed ledger technology. That means that some elements are simply not defined exactly by the framework and are pretty much open for further implementation. Such things are related to the exact transaction realization.The computational part of the consensus can be pretty easily extended in java, however how exactly transactions are implemented is a point that provides the possibility to several implementations. In this sense properties like crypto-economics transaction semantics or transaction privacy are parameters that provide several possibilities in the future. The sure thing is that contrary to Ethereum Hashgraph best fit in consortium scenarios, the structure of the transaction storage is a non-blockchain one and both performance and fault tolerance are more than excellent.

Certainly, this article covers the original concept of Hashgraph produced by Swirlds, in the public version of the technology produced by the Hedera consortium it is planned to have more structure and services regarding on transaction, cryptocurrecnies and storage.

Solidity Tips and Tricks - difference between .call.value(), .send() and .transfer()


It is important to understand the difference of semantics and security implications of the different ways of sending ether to a contract:
- .call.value(ether) - sends ether to a contract by giving all the possible gas for the execution having a strong risk for reentrancy attacks. If it is succeeded true is returned if not false. 
- .send(ether) - sends ether to a contract by giving only 2300 gas for the execution making possible to do only logging and event and preventing reentrancy attacks. Similarly to the previous case if the call succeed it returns true, otherwise it returns false. 
- .transfer(ether) is tecnically the same as require(send(ether)), so if the ether sending not succeeding and error will be thrown and the transaction is reverted.  


Solidity security patterns - reentrancy


Reentrancy can happen if a smart contract calls a second one in a direct way or indirectly by transferring it ether. Typically at the code execution before the given statement terminates it called once again by another contract. Consider the following code fragments:

contract ReentrancyError {
  ...
  function withdraw(uint _amount) public{
    if(balances[msg.sender] >= _amount) {
      if(msg.sender.call.value(_amount)()) {
        balances[msg.sender] -= _amount;
      }
    }
  }
}

contract Attacker {

  function attack() public {
      target.withdraw(donated);
  }
  
  function() public payable{
      if (counter < 10) {
        counter++;
        target.withdraw(donated);
      }
  }
}

The withdraw function of the ReentrancyError contract is meant to be called by externally owned accounts, however a tricky hacker might force to call the function from a hacked contract. If so by calling the withdraw function at the msg.sender.call.value(_amount) by transferring ether to the Attacker contract the fallback function will be called, that calls the withdraw function back again. As balance of the sender is still not modified at this stage, the attacker will succeed to transfer the amount of ether once again starting a new cycle (up to 10).

Possible solutions in this example are:
- reducing the balance before the ether transfer
- using mutex
- using require statement instead of if

Solidity security patterns - difference between call delegate call and library call


It might be a little bit tricky to distinguish between the different kind of calls in solidity. Basically library call is realized on a low-level by delegate call and it is different from a standard call. In a standard call the context of the called contract is considered as active. In a library or delegate call the calling context, meaning variables, storage, visibility remain active. In other words in a library call only the function code of the called contract will be loaded, every other parameter remain the same. The situation can be best seen by the following contract examples: 

contract CalledContract {
    event showAddressEvent(address _from);
    function test() payable public {
        showAddressEvent(this);
    }
}

contract CallingContract {
    function callDifferentContracts(address _contractAddress) public {
        require(_contractAddress.call(bytes4(keccak256("test()"))));
        require(_contractAddress.delegatecall(bytes4(keccak256("test()"))));
        testLib.calledSomeLibFun();
    }
}

library testLib {
    event showAddressEvent(address _from);
    function calledSomeLibFun() public {
        showAddressEvent(this);
    }

By calling the callDifferentContracts function with the address of the CalledContract, the code first reveals the address of CalledContract as it is expected by a standard call. After that it shows the address of the CallingContract both at the delegatecall and at the library call examples. 

Solidity security patterns - delegatecall and callcode


The problem is both with delegatecall and callcode that they dynamically load the code of a smart contract and call its function. Hence they do this loading in a way that the context (storage, memory etc) of the calling contract is preserved. It means that from the called contract any kind of variables (even privates !) of the calling contract can be changed. So it must be particularly paid attention that only one specific smart contract and only one specific function is to be called by callcode or delegatecall.

contract TestCallCode {

  function callDelegateFunction(address _a, string _functionName)  {
        _a.delegatecall(bytes4(keccak256(_functionName)));
 }
}

In the previous example if an attacker can call the callDelegateFunction and influence the address, he can redirect the call to any smart contract of a choice and with the functionName any function can be called. Even if there is no direct match between the _a address and _functionName the system can be sometimes tricked like with implementing malicious code into the fallback function. 

Solidity Tips and Tricks - triggering timed event


In solidity or in Ethereum, you can't trigger an event internally from the environment. What you can do is to have an external trusted source that triggers for you something with the help of an explicit transaction. This raises however the problem of centralization and trust, although there is the possibility to structure decentralized oracle network for similar problems, they still remain pretty much centralized. 

Sometimes however the requirement is more simple, one should not really trigger actively an event explicitly, it has only to be made sure that a given functionality works differently before and after a given point of time. In such cases the block number or the block timestamp can be used. The following situation shows an example pattern for that:

contract TestDebugMode 
{
 uint public eventBlockNumber = 1111111111; 
 uint public eventTimestamp = 1111111111;

  function timeBasedLogic()  
    {
     if (eventBlockNumber > block.number) {
           // do logic  
     }
     if (eventTimestamp > block.timestamp) {     
          // do logic 
     }    
 }
}


It is usually proposed to use the block number because in certain situations block timestamp can be gamed by the miners.  

Solidity Tips and Tricks - debug mode with blocknumber


As we have seen in our previous blog, designing smart contract structure with debug features might be a pretty good idea. One possibility is to realize it with an explicit switch that can be manually switched on or off, however it might happen automatically as well, like based on the actual blocknumber. The following code demonstrates the idea: 

contract TestDebugMode2 
 {    
   uint public targetDebugNumber = 1111111111; 
   
   modifier isInDebug() {       
       require(block.number < targetDebugNumber);
        _;
  }

  function onlyInDebug() isInDebug {

  }

Solidity Tips and Tricks - debug mode with simple switch


Well, designing a smart contract is pretty tricky, basically the contract is immutable so basically it is not upgradable, even if you use some direct patterns for update. So what you can basically do is to build in some debug functionalities, like getting extra debug information or updating parts of the system in a debug mode... The most simple way how you can control such a debug mode is to have a bool switch called debugMode that can be set true only once at the go live causing that the debug functionalities will not be accessible anymore. An example can be seen on the following code:

contract TestDebugMode {
    
 bool public debugMode = true ; 
    
   function goLive(){
      debugMode = false;
   }

   modifier isInDebug(){
      require(debugMode == true);        
      _;
   }

   function onlyInDebug() isInDebug {

   }
}

Certainly, a real smart code might be somewhat more difficult, as it has to be guaranteed that only an owner or an administrator can deactivate the debug mode by going live. 

Consortium blockchain solutions and ICO-s

There seem to be nowadays a couple a blockchain solutions that target consortium or private business blockchain solutions and despite planning or doing an ICO or other form of token sales. One of the best such example is Ripple, which offers bank to bank financial services despite that a lot of its XRP tokens can be freely traded in the major exchanges. 

Such a constellation seems to be a little bit paradox for the first sight. The problem is that institutional investors still do not really buy tokens, instead most of the tokens are sold for everyday people or to bitcoin whales. Considering a B2C decentralized service this can provide a functioning solution, as most of the tokens are probably bought by people who are actually willing to use the service as well as soon it will be ready. This makes the business adaptation faster and accelerates the network effect as well. However with a B2B service it is very difficult to design a usage token in a way that it can be bought by average people as investment but the system will be working in a consortium scenario possibly between enterprises. Certainly it would be an exception if the token could represent a pure investment possibility, however it would require a huge regulation overhead.  

Tuesday, April 3, 2018

blockchain governance and the two levels of smart contract


Blockchain governance is a complicated topic, especially if we consider not only the consortium but the public solutions as well. Mismanaged governance can cause forking and other undesired effects. It would be a great idea if governance activities of a blockchain could be actually supported by smart contracts, implying two categories of smart contracts in the system: 

1. system smart contracts, realizing basic functionalities and services related either to maintain the consensus and the system or providing general services to other smart contracts. 
2. user based or custom smart contracts, providing general user defined functionalities using both the consensus algorithms of the blockchain and the functionalities of the system smart contracts. 

The key concept of such a system smart contract layer is to provide a further integration link between the infrastructure nodes, the services of such a nodes and the system smart contracts, or putting elements of the genesis file into the smart contract. 

On the problems and possible improvements of solidity



The biggest problem of solidity is its inconsistent semantics and unexpected side effects of certain operations.

Examples are type conversion, arithmetic operators, fallback function, different ways of calling other contracts or libraries, variable visibility and access ...

And of course a key point is to understand what it means that your code will be executed on the blockchain.

In this sense, the solution won't be to have a non-Turing complete limited language. The solution will be to have a very strict and logical language in which all side effects are easily foreseen and the language semantics makes more sense in a distributed ledger context. 

Solidity Tips and Tricks - type aliases


There are a couple of aliases or similar types in solidity that you should be paid attention.

- uint is alias to uint256.

- byte is alias to bytes1.

- sha3 is alias to keccak256.

- now is alias to block.timestamp.

- bytes is the same byte[] but packed tightly.

- string is almost the same as bytes but doesn't allow length or index access.

- address is equivalent to uint160

Solidity Tips and Tricks - var as type declaration


Although there is a possibility to use var at a variable declaration, meaning that the variable is initialized by the first declaration automatically, you should have extreme caution using this pattern. As an example, using for instance var i = 0; initializes the variable automatically as uint8 implying that the following loop is an infinite one causing an out of gas exception in solidity.  

contract TestContract {
  function infiniteLoop() {
    for (var i = 0; i < 1000; i++) {
    ...
    }
  }
}

Solidity Tips and Tricks - converting types


In solidity converting between types is not always very straightforward, as an example there is no typecast from address to string, there is no typecast bytes to string, and from bytes to address. If you need such a conversion, you have to implement it. The following example shows a possible implementation for such a conversions:

contract TypeCasting {
    
  function toString(address addr) returns (string) {
    bytes memory b = new bytes(20);
    for (uint i = 0; i < 20; i++) {
      b[i] = byte(uint8(uint(addr) / (2**(8*(19 - i)))));
    }
    return string(b);
  }
  
  function bytes32ToString(bytes32 x) constant returns (string) {
    bytes memory bytesString = new bytes(32);
    uint charCount = 0;
    for (uint j = 0; j < 32; j++) {
      byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
      if (char != 0) {
        bytesString[charCount] = char;
        charCount++;
      }
    }
    bytes memory bytesStringTrimmed = new bytes(charCount);
    for (j = 0; j < charCount; j++) {
      bytesStringTrimmed[j] = bytesString[j];
    }
    return string(bytesStringTrimmed);
  }
  
  function bytesToAddress(bytes _address) public returns (address) {
  uint160 m = 0;
  uint160 b = 0;

  for (uint8 i = 0; i < 20; i++) {
    m *= 256;
    b = uint160(_address[i]);
    m += (b);
  }
 }
}