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

Thursday, August 1, 2019

Hyperledger Fabric tips and tricks - using time or date in chaincode


If you want to use in your chaincode the exact time or date, it is not a straigtforward thing, because, the different endorsement peers might have different time set and if your commitment information is not the same in all of your commitment peers, the transaction will not be accepted as a valid one. What you can use, is the timestamp of the transaction itself, like with the help of a chaincodeStub.getTxTimestamp() call.

Hyperledger Fabric tips and tricks - chaincode log ID


If you log your chaincode activity, like with the help of a standard logger, it is always a good idea to know for which call was your log message generated. You can use the  getTxId() function call to log the transaction ID for you message. 

Hyperledger Fabric tips and tricks - static variables in chaincode


Do not use static variables in your chaincode in Hyperedger Fabric to store general settings, beacuse if the docker containers are restarted, your setting can be lost. Store instead everything in the ledger, or optionally in the private store. 

Sunday, May 12, 2019

Timing attacks against naive atomic swaps


Naive atomic swaps are asymmetrical games. In a standard atomic swap two HTLC-s are created with the h secret and T time lock and the idea is that either each party reveals the h secret or the timeout expires and all transactions are reverted. However the game is a little bit asymmetric, because one party, let we call it Alice creates and knows the h secret value so she can choose the exact time when she reveals this secret. If she chooses to activate that h secret right before the expiry of the T timelock, she has the chance that her counterparty, let we call Bob misses the time windows, so Alice gets the money from both blockchain. She might as well influence the chance of Bob to miss the time window with trying to force the counterparty blockchain, or with bribing some of the miners in the counterparty blockchain to delay the transaction.     

It is an open question, if modified swaps with HTLC contracts can be defined in a way that they reflect the assymetric behaviour of information sharing. 


Monday, March 18, 2019

parity tips and tricks - parity docker and persistent storage


If you use parity above 2.3.5 and you want to run with docker in a way that your chain is synced on a persistent storage, like under /srv/parity on an ubuntu machine, you can use something similar to the  following script:

sudo docker run -ti -d --name parity --network=host --user=root --restart=unless-stopped  -v /srv/parity:/home/parity/.local/share/io.parity.ethereum  parity/parity:v2.3.5 --chain=ropsten --geth --jsonrpc-apis "web3,eth,net,parity,parity_accounts,traces,rpc,parity_set,personal" --base-path /home/parity/.local/share/io.parity.ethereum

parity tips and tricks - ancient block sync error



If you use parity 2.3.5 syncing your blockchain and you open a geth console with the synchronization as well, your geth console might show that everything is synced but you can and error with ancient block syncing.

Like the following error: "Block information is incomplete while ancient block sync is still in progress, before it's finished we cant`t determine the existence of item"
In this case check the following :

 curl --data '{"method":"parity_chainStatus","params":[],"id":401697,"jsonrpc":"2.0"}' -H "Content-Type: application/json" -X POST localhost:8545

if it shows that there is still and existing blockgap it means that an ancient block syncing is still in progress, so wait until it finishes. If the sync does not improve check if you did not coicidently start parity with the --no-ancient option.  

Saturday, March 16, 2019

Phases of learning solidity programming

Month 1: Yes, I can program in Solidity ! This is an easy language, similar to Javascript, with some types.

Month 2: Wait, Underflow / overflow ? I thought they can not cause problems.

Month 3: But, I should upgrade my contract ? Because it contains already ether and I forgot to implement an etherTransfer function ?

Month 4: Cool, I have some upgrade patterns, but they cost too much ether.

Month 5: Ooh, msg.sender, tr.origin, contract in the middle attacks ?

Month 6: Or, Fallback function ? Reentrancy ?

Month 7: Hmm, A transaction is always atomic, right ? So what is with address.transfer or address.call.value ?

Month 8: And, Libraries, Delegate calls ?

Month 9: Hence,  Stack, call stack attacks and front running?

Month 10: So, How about just reusing some ready libraries ? Like OpenZeppelin ?

Month 11: Or, Formal verification, bug-bounty, military programming ?

Month 12: No, I can not program in Solidity !

Sunday, February 10, 2019

Fabric composer tips and tricks - working with current identity


If you work with Fabric Composer, the ACL (Access Control List) language is meant to handle access rules in the system. However there might be the case that you need to define access rules directly in the smart contract code in a hard coded way. If that is the case, you can ask the current identity with the getCurrentIdentity() API call and implement the corresponding access logic based on the identity information:

 var identity = getCurrentIdentity();    

 console.log(identity);

 console.log("identity namespace : " + identity);

 console.log("identity certificate : " + identity.certificate);

 console.log("identity identityId : " + identity.identityId);

 console.log("identity name : " + identity.name);

 console.log("identity participant identifier : " + identity.participant.$identifier);

 console.log("identity participant namespace : " + identity.participant.$namespace);

 console.log("identity participant type : " + identity.participant.$type);

Saturday, February 9, 2019

Blockchain and sustainability

Blockchain and sustainability
In terms of blockchain algorithms and platforms, sustainability can be interpreted in many ways. On the one hand, anyone who has ever heard about the energy demand of the Bitcoin network can rightly think that the system is pretty far from being considered as sustainable or environmentally friendly. This extreme energy requirement is not necessarily similar however with other blockchain platforms. On the other hand, a number of initiatives have been taken over the past few years to address sustainability or environmental issues with decentralized applications. In this article, we analyze the topic of blockchain and sustainability from these two relatively different point of views.

Consensus and energy consumption

One of the most important components of decentralized platforms is the consensus mechanism. The consensus mechanism is responsible for ensuring that the system is always in a consistent state, meaning that all nodes contain the same information. With other words when someone creates a new transaction, the consensus mechanism ensures that the entire system reaches a single state: either each node finds the transaction valid, or each node finds it invalid.


In public blockchain algorithms, the implementation of the consensus algorithm may be particularly difficult. With such systems, there is always the possibility of a so-called sybil attack, where an external attacker creates a large number of hacked nodes and tries to influence the consensus of the system. Therefore, in such systems, the consensus algorithm is not based on the number of nodes, instead on some other economically scarce or expensive resource. Early day consensus algorithms implemented this resource with computational power (Proof of Work). As a participant in such a consensus compete with each other on a market basis, the total computing power can grow to an extremely large extent to maintain the system and the consensus.



Figure 1, the computational capacity needed to maintain the Bitcoin consensus
(source: https://www.blockchain.com/de/charts/hash-rate?timespan=all)


Of course, the computational capacity that might be extremely high in some places has significant energy consumption, which does not affect the sustainability or the environment positively. It is difficult to explicitly measure this energy consumption, but it can be estimated in  two ways. The so-called bottom-up estimation calculates the energy consumption, cooling, and production energy requirements of computing hardware in detail. The other, so called top down approach, takes into account that the participants in the consensus receive profit or reward for their activity. Given that there are many players on the market and that market is pretty competitive, participants can only realize an estimated normal profit and the rest of the revenue can be considered as direct or indirect energy cost. In both cases however, the total amount of  estimated energy is significant.


Figure 2. Energy consumption of the Bitcoin network compared to countries.(source: https://bitcoinist.com/huge-wind-farm-to-power-bitcoin-mining-will-be-built-in-north-africa/)


Fortunately, the Bitcoin consensus mechanism was merely the first working mechanism and it is almost certainly not the last. Many research and development focuses on developing faster and more efficient consensus mechanisms that require less energy. In one solution, the critical resource involved in the consensus is not the computational capacity but directly the cryptographic currency. In such so-called proof of stake systems, nodes intercept a certain amount of cryptocurrencies, which is lost if it turns out that they tried to hack the system. Other approaches, called layer 2 scaling solutions, execute most of the transactions not directly on the blockchain but on a separate off-chain transaction channel. Considering that usually every hundreds transaction is executed or synchronized with a blockchain, the overall efficiency is enormously increased.


The area of ​​consensus mechanisms is very actively researched area. Even if the currently most widespread solution are energy demanding, this will most likely not a problem for future blockchain platforms and consensus mechanisms.

Sustainability applications on the blockchain

There are on the other hand a lot of applications and initiatives that try to support or solve  sustainability and environmental issues with the help of a blockchain. Of course, many of these initiatives are still in the early stage, so it is too early to evaluate which of them is will be real killer sustainability application. Most of these initiatives can be summarized by the following categories:


“Green” energy distribution: One of the applications sustainability and blockchain focues on the  efficient distribution of locally produced “green” energy. Suppose that some residents in a local community install solar cells, and in the case of overproduction of energy they share the extra energy with their neighbors. The blockchain can be used here to accurately and automatically accounting the distributed energy. From a technical point of view, early implementations use Ethereum integrated with local energy IoT devices, creating a so-called smart meter.


Figure 3, “green” energy distribution in a local market


Supply chain trancparency: The next major area of ​​sustainability applications is to improve the transparency of supply chains and value chains. The first applications come from the area of ​​food production and food distribution, where it is particularly important to keep track of the exact lifespan and raw materials of a food product. For example, if it is found that an agricultural area has been sprayed with harmful substances, all the products directly or indirectly affected should be withdrawn. The technology also provides the opportunity to aggregate certain properties in the supply chain and display them on end products. For example, it is possible to say about a food product that it is made from vegetable ingredients or does not contain gluten, considering the entire production chain. In addition to properties directly related to food, other sustainability parameters can be also measured and aggregated along the supply chain, such as greenhouse gas emission or the proportion of recycled materials used.


Incentivies: Blockchain-based incentive systems generally reward some kind of environmentally conscious activity. A classic example is getting a token reward for collecting and recovering recyclable materials. The environmentally conscious activity can be glass recycling, plastic garbage collection or the purchasing services that have an positive overall environmental impact. The motivational token can also be implemented in different ways. It can function as a collectible token, it can work as a local currency to buy different special products, or it can also be a full scale cryptocurrency.

There are a number of other examples and initiatives how blockchain can be used in sustainability or environment protection. Examples include a transparent "green" point system for companies, or a transparent block chain accounting system that tracks charity cash flows. Of course, it is not yet possible to see which application will be a real “killer app” in the area. However, there is a strong chance that many sustainability issues canl be better solved with transparent global blockchain systems and decentralized automated organizations than in the current system, which is usually dominated by short-term financial decisions and other local political interests.

Saturday, January 5, 2019

Using blockchain platforms in sustainability


There can be many ways of using blockchain in sustainability, including public and consortium blockchain platforms. Examples might be:

1. using consortium blockchains for supply chain modelling to aggregate environmental properties of different products, like greenhause gas emission parameters. 

2. using public tokens and public chains to encourage the P2P usage of environment friendly technologies, like green energy. 

3. Gamification badges and collectable tokens: customers could gain different kinds of a non-tradable tokens as badges for consuming and buying environment friendly resources. It is similar to standard gamification 

4. Locally tradable tokens: The gained tokens could be tradable but only in a local environment. As an example, tokens gained for consuming local “green” environmental goods could be used for purchasing other similar goods of local companies.  

5. Full scale “green” cryptocurrency: The gained motivation or gamification token could work as a cryptocurrency having the possibility to be traded against other crypto or standard currencies. 

6. “Green” markets: there could be tokens that represent directly some kind of a direct environment improvement. Examples might range from planting a tree or explicitly reducing the CO2 emission of an area in terms of a negative carbon credit. These tokens could be tradable on an open decentralized market, perhaps with standard cryptocurrencies. 

7. “Green” transaction fee: The previously mentioned possibilities could be combined with the help of a special transaction fee on either standard payment transactions or cryptocurrencies. This “green” transaction fee can be automatically and transparently redirected to activities supporting sustainability. 
  

Notes on atomic and cross-chain swaps


Atomic swaps realize cooperation between several two blockchains in the sense that a transaction on one chain can be executed if and only if another transaction is executed on another chain. 
The simplest working mechanism of such an atomic swap is the following: 

1. Let we imagine that a we want to make an integration between a P public and C consortium network in a way that a Tc transaction is executed on the C consortium network if and only if a Tp public transaction is executed on the public network. 

2. We create a random x secret value and a H(x) cryptographic hash of the random number. 

3. We create a timed hash contract or transaction in a way that the transaction is on the blockchain but it will be executed if and only if x is openly presented on the chain, usually with the help of a transaction. If the x value is not presented in a certain time period, the transaction is automatically reverted. In case of Bitcoin for instance this revert means that the cryptocurrency is efficiently transferred back from the multisig wallet to the sender. However this is not necessarily the only possible use-case. Any logic with a transaction execution and revert can be used. 

4. If x secret is presented on one system, the transaction will be executed. As in this case x secret is public, it can be used to execute to other transaction as well on the other system. 

Certainly the system might have some disadvantages that can be fine-tuned: like in non smart contract based systems, the double spending should be avoided by the algorithm and the participants should be effectively online during the swap. On top, privacy might be an issue as well. 


Wednesday, January 2, 2019

Solidity Tips and Tricks - security of the view modifier of a function


Solidity view function modifier means that the function do not modify the storage of the contract, due to the fact that it costs no gas to call this function. However, one might as well assume this feature as a security guarantee, meaning that the function can not modify the storage.  It is important to note however that in the 4. compiler versions there is actually no guarantee for that, the compiler gives a warning, but despite it compiles and deploys the contract without error. As an example, considering the following contracts:

pragma solidity ^0.4.24;

contract ViewImplementation {    
 uint public storageVariable = 0;
    
 function viewFunction() view external returns (uint) {
   storageVariable = 2;
   return 1;
 }
}

contract TestViewImplementation {
    
  address contractAddress =
           0xbbf289d846208c16edc8474705c748aff07732db;
    
 function testView() public {
   ViewImplementation imp =  ViewImplementation(contractAddress);
   imp.viewFunction();
 }  
}

Calling the viewFunction externally implied zero gas consumption and the storageVariable will not be modified. However, calling the function from another contractlike from testView will modifiy the storageVariable to 2.

The situation is fortunately better in the 5+ solidity versions, as there is not only warning but a compiler error as well in such a situations.  

Designing a generalized Cryptokiities style game framework on the blockchain


Cryptokitties is a genial blockchain game, however it should be extended into a more generalized framework. The collectible crypto animals should have dynamic properties as well, like they should be able to learn things and behave somehow in a more dynamic environment. Such a game might lool like as the followings:
- Users could have contactable cryptoanimals.  
- These cryptoanimals could be mutated or evolved.
- The cryptoaimals could be explicitly trained as well. 
- There could be different kinds of a matches or competitions between the cryptoanimals, like: 
   - who can navigate through on a labyrinth faster.
   - who can capture a flag on a field faster. 
   - who can  perform better in a sense on a simulated field. 
   - perhaps battles or team sports, like a version of football could also be played.
- Based on the match result, there could be some resources won that can be used for like making new mutations or training cycle for the cryptoanimal.  

Tuesday, January 1, 2019

Notes on the future of token standards



Next generation of token standards will define cross-chain tokens, distributing efficiently the functionality between several blockchains or perhaps having even off-chain functionality. This will extend tokenomics and token based business models in the direction of multiply blockchains, or even blockchain and off-chain solutions. From a technological point of view, there is already several initiatives for realizing such a services, like Plazma, Loom network, Polkadot or Cosmos.