...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego
Showing posts with label Tips & Tricks. Show all posts
Showing posts with label Tips & Tricks. Show all posts

Friday, May 21, 2021

Intermediate CA with Explorer or Gatweway on Hyperlegder Fabric

 


If you use Hyperledger Fabric with hieararchical CA-s and want to use Hyperledger Explorer or gateway, you might as well face with the situation that the tlsCACerts property for the TLS communication must be configured. The thing is that neither intermediate TLS certs or root TLS certs will work here you should create a file that contains the whole certificate chain (just copy in one file first the root cert then the direct intermediate cert, then the next intermediate cert and son on). 

Saturday, June 6, 2020

Ethereum parity node and monitoring



If you run a parity node one of the most important is to check if your sync is running or if it is stopped for some reason. Making sure that the json-rpc is enabled, you can use two checks:

1. Check if the sync is fully synced. 

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

if you get a false for the above command, it is fully synced. Otherwise you get the actual block number where the sync stays.

2.  Even if it is fully synced, the ancient block sync might be running, so the following command has to show that the blockGap is null:

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

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, 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);

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.  

Sunday, December 30, 2018

Solidity Tips and Tricks - struct at local function hack


Solidity has a lot of surprising and actually shitty characteristics. On thing is that a struct can be defined both in memory and in storage as well similarly to arrays. The problem is however that if you define your struct in a local function body, it overwrites the storage variables of the contract itself. On top unfortunately, if you create a struct in a function body without explicitly marking if it is a storage or a memory one, it is created automatically as a storage. So the following example:

contract StructHack {
    uint public myNum = 0;
    
    struct TestStruct {
        uint structNum;
    }
    
    function hackStruct() {
        TestStruct test;
        test.structNum = 22;
    }
}

Surprisingly, if you deploy the contract and call the function hackStruct, the myNum value will be initialized to 22.  

Wednesday, December 26, 2018

Solidity Tips and Tricks - transferring ether at fallback logic


There are basically three ways of sending ether from a solidity contract:

- contractAddress.call.value("sent_value")() is the less secure version of all of the possibilities. It opens the door for reentrancy and other attacks. It is usually not proposed to use this contract due to security reasons. However, if you transfer ether for a contract that has a complicated fallback functionality, actually this is the only possibility. If you want to fine-tune the gas price of the executed target logic, it is again the only possibility. 

- contractAddress.send("value") sends the value to the address in a way that only 23000 gas is allocated to a possible fallback logic. The call gives back a true or false value depending result of the logic. So it can not really be used at complicated fallback logic. 

- contractAddress.transfer("value") sends the value to the address in a way that only 23000 gas is allocated to a possible fallback logic. The call throws an exception if something goes wrong, so it is regarded as a more secure way of transferring values. It can not be used at complicated fallback logic either. 

Sunday, November 25, 2018

How to trigger Ethereum smart contract if Solidity event occurs


Well you cannot react to an event in a solidity smart contract, there is no command at all in EVM that checks the event log. Besides, there is no way of starting a smart contract automatically. However, you can use a semi-trusted setup with Oraclize, where similarly to my previous blog, you can periodically check if an event has occurred.

Firstly, you can use an Ethereum explorer API to get information of an event of a contract with the following http get request.

https://api-ropsten.etherscan.io/api?module=logs&action=getLogs
   &fromBlock=<from>
   &toBlock=latest
   &address=<contract address>
   &topic0=<event id>&
   apikey=<YourApiKeyToken>

So, what you have to do is to query this log periodically with Oraclize and check if the necessary information is present.

  // schedule update schedules the next call
 function scheduleUpdate() payable {
   if (oraclize_getPrice("URL") > this.balance) {
       LogNewOraclizeQuery("Not enough fund");
   } else {
       // NEXT UPDATE IS SCHEDULED IN 60 MIN
      oraclize_query(60, "URL", " url explorer API for the event ");
   }
 }

 function __callback(bytes32 myid, string result) {
    // SECURITY CHECK
    if (msg.sender != oraclize_cbAddress()) revert();
        
    // PROCESS INFORMATION
    if (information_not_present){
    // SCHEDULE NEXT UPDATE
       scheduleUpdate();
    }
 }

Certainly this is not the cheapest and most efficient way of triggering a smart contract for an event, but it might work on a small scale. Experimental implementation can be found under EventTriggeredEthereumContract in the following GitHub repo

Saturday, November 24, 2018

Truffle and solidity tips and tricks - test events in unit tests


If you use truffle and want to test solidity with javascript unit test, you might want to test the raised events as well. As result gives back the whole transaction including the event log, the easiest way to get the event is to get them directly from the event log:

   return ContractInstance.functionCall({from: accounts[0]});       
   }).then(function(result) {

- result contains the whole transactions
result.logs contains the whole log
- result.logs[0].event contains the first event

So, an assert that checks if an event was raised might simply look like:

assert.equal(result.logs[0].event, "EventName", "Event raised");



Friday, November 23, 2018

Truffle and solidity tips and tricks - error at contract deployment gas amount


If you deploy a contract with the help of truffle possibly on a development environment and you get the following error message: 

"Error encountered, bailing. Network state unknown. Review successful transactions manually 
Error: The contract code couldn't be stored, please check your gas amount."

Well, there might be the problem of the real gas amount at the deployment, but most typically you want to deploy a contract that has an abstract method, or it inherits coincidentally and abstract method that is not implemented. 

Tuesday, November 20, 2018

Truffle and solidity tips and tricks - nonce error with Metamask


If you use truffle development environment with Metamask as well you can often get the following error message: "the tx doesn't have the correct nonce". The problem is that you probably use the same accounts both from truffle development console and from the Metamask UI. Unfortunately, Metamask does not automatically update/refresh the nonce if the transaction was executed by the truffle development console. So what you have to do is to reset the Metamask account: Settings - Reset Account. 

Thursday, November 15, 2018

Solidity and Truffle Tips and Tricks - converting string to byte32


If you want to convert strings in solidity to byte32 and you get different kind of error messages at  explicit or implicit converting or at changing between memory and storage variables, you can use the following function:


function stringToBytes32(string memory source) 
                                        returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
        return 0x0;
    }

    assembly {
        result := mload(add(source, 32))
    }
}

Monday, November 12, 2018

Fabric composer tips and tricks - Cyclic ACL Rule detected, rule condition is invoking the same rule


If one of your asset or participant is not updated and you get the following error message like in the javascript console if you the use fabric composer online playground:"Fabric composer tips and tricks - Cyclic ACL Rule detected, rule condition is invoking the same rule" . The problem can be that you do not use the statement await before an update and two updates might happen parallel.  

Fabric composer tips and tricks - deleting asset from array


If you want to delete an element from an asset or participant that as a reference array to another asset or participant, the process is pretty similar to deleting an element from a javascript array:

1. Getting a registry for the asset or participant
const assetReg = await getAssetRegistry(namespace + '.Asset'); 

2. Getting an index of the asset or participant to be deleted
var index = asset.arrayOfReferences.indexOf(assetToBeDeleted);

3. Delete the index in a javascript style
  if (index > -1) {
     asset.arrayOfReferences.splice(index, 1);
  }

4. Update the asset
assetReg.update(asset);

Fabric composer tips and tricks - not updating without error message



Working with fabric composer, you can sometimes get the phenomena that some item is not being updated, however there is no error message or anything, the transaction is executed without any problems, only something is not updated. This can be caused by exchanging the getAssetRegistry with the getParticipantRegistry statement. If you experience such a phenomena, check if you try to update assets with the getAssetRegistry and update participants with the getParticipantRegistry statements.   

Wednesday, October 24, 2018

Fabric composer tips and tricks - importing external javascript library


In Hyperledger Fabric Composer at smart contact development importing external javascript libraries are not really supported at the moment. What you can basically do:

1. use the extra functionality on the client and server side and not directly in the smart contract. Pay attention that the smart contract is executed and evaluated on each endorsement peers of the Hyperledger Fabric architecture. This security guarantee is not always possible for most of the logic. Sometimes you can reconstruct your business logic in a way that the functionality provided by the external javascript library is executed on the client side and only the result is presented on the smart-contract side. 

2. if the code of the external javascript functionality is not huge, you can try to integrate the javascript files as extra files in your business network archive file. The framework references automatically the added javascript files. Certainly, you added files can not have external references. 

Thursday, October 18, 2018

Fabric composer tips and tricks - return value of a transaction


Unfortunately there isn't possible to return value from a transaction in Hyperledger Fabric Composer. What you can do however:

- Emitting an event, like

  let retValEvent = getFactory().newEvent(namespace, 'RetValEvent');
  retValEvent.RetValue = "value";
    emit(retValEvent);

- writing the return value into the variables of an asset or participants. For fine-tuning the access rules, it might be possible to define a separate asset containing only the return values of the different transactions:

  asset ReturnValueAsser identified by retId {
    o String retId
    o String retValTransaction1
    o String retValTransaction2
    --> RelatedAsset relatedAsset
 }



Sunday, October 14, 2018

Fabric composer tips and tricks - item with ID already exist but not visible


Sometimes if you work with the Fabric Composer online playground and you create an item from a transaction you get the error message that the given id already exist even if it is not directly visible in the asset list. This is actually a "feature" of the online playground, it happens if the old item with the old id already existed but it was deleted. For some reasons it is sometimes cached somewhere that can not be explicitly deleted. What you can do in such situations that you redeploy the business network archive file:
- Make sure that the latest version of the .bna (business network archive) is downloaded.
- Delete the existing business network in the online playground.
- Rdeploy the business network from the downloaded .bna file.