Invoke Chaincode - hyperledger-fabric

I am reading about chaincode in hyperledger fabric for my project. I have a doubt on
How to invoke chaincode automatically based on events like time. If so, are any working examples available.
Thank you in advance.

You cannot invoke transactions automatically without a client. If you look at the transaction flow of Hyperledger Fabric, the client has a lot of responsibilities signing the transactions, like collecting the endorsement, optionally filtering out the proposal responses (bad ones) and sending it for ordering. So, you cannot replace all this logic in the chaincode layer which is essentially responsible for endorsement.
You have to do this invocation based on events like time with the help of the client whose rules you are supposed to define.
So, best way would be put some sort of authorization logic on the chaincode function you want to invoke at regular intervals of time and use a client and a user's certificate to call the functions on the chaincode using some cron mechanism.
Reference to Authorization in Chaincode:
Summary Video: https://www.youtube.com/watch?v=WTW9QVO28l0
Chaincode Reference: https://github.com/hyperledger/fabric-samples/tree/release-1.2/chaincode/abac/go
Documentation: https://docs.google.com/document/d/1GP5tcN0oK9Zewed9h5pLiM2BowWPhtgFUGXEDKjeGGo/edit

Related

I would like to know if you can import files into Hyperldeger Fabric

I am new in this field and therefore I am still doing studies and researches, I would like to know if JSON files can be imported in Hyperldeger Fabric--if it is better Hyperledeger Fabric or Fabric Composer. more precisely I would like to understand if there is a way to populate the DLT of Hyperledger Fabric automatically.
for now, I have only tried Hyperledger Composer online playground
Fabric don't have any feature to automatically populate the ledger.
You have to develop a solution in order to upoload each Json file and put that on the ledger state.
Any type of data can be inserted on the ledged because it stores byte arrays so its up to you how to serialize.
in case you're asking to making your chaincode or smart contract like talking to the file system and read file or even call some API to collect JSON files,
it could be done but this will break your transaction flow specially during the endorsement process due to during the endorsement process it's expected from each peer to return the same value after executing the transaction against the chaincode to consider the transaction is a valid transaction,
so in case one of the endorsers failed to call the API or failed to read file from file system the transaction will considered to be invalid.
so it's not recommended to do any third party activity in your chaincode or smart contract even if it's possible to do so.
about populating the ledger it can be done it's eventually a database so you can dump it's data, However, if you're trying to backup to recover the ledger in case the whole network down it's impossible due to when you'll reinstall the network the whole config and certificates which were bounded to the transaction will be changed so it has no sense to do it.

How does transaction rollback work in Hyperledger Fabric?

I'm looking for a transaction rollback. This is necessary if a chaincode transaction modifies the state, but then fails with an error before it is able to return.
I saw this is done for a pull request but I can not understand how does it works
Added support for rolling back a tx if chaincode execution fails
Someone can give me an example how does it works?
EDIT
What I'm looking for is the concept of Transaction in database(unit of work) but in Hyperledger Fabric
Let's suppose that we are going to register a product for a list of clients, if there is a problem with the registration of the product in some customer then the operation is eliminated and the registration is not made to any client
The commit you linked is no longer relevant to current Hyperledger Fabric versions. This functionality was added before v1.0, which restructured the entire framework architecture.
As of v1.0+, transactions are first simulated by endorsers, which create a signed set of state changes resulting from the chaincode. If enough endorsers sign a transaction (according to an endorsement policy), the client can then send the transaction to the ordering service for inclusion in the ledger. A transaction that results in an error in the chaincode would never get to this point, because it would fail to gather the necessary endorsements due to the error. The client must modify the transaction or request a modification of the chaincode for it to work.
Check out the Hyperledger Fabric architecture paper for a more detailed explanation, including a sequence diagram.

Transaction hash generation in Hyperledger Composer

When a call is made from Hyperledger Composer to Fabric runtime, is the transaction hash generated only after the commit in the entire network. If thats the case, should we wait synchronously and track the data from traditional system. Like in ethereum cant we get a transaction hash immediately and track the commit status later.What is the best way of handling this in Hyperledger Fabric.
Yes, just like in ethereum we can get transaction hash inside the smart-contract/chaincode in HL fabric too, it doesn't matter if later transaction is committed or not.
For every invocation request, a transaction ID is generated, it can be accessed by a method
getTxId()
(in java chaincode, similarly can be found in go/node cc) which returns a String transaction id for that request.
refer Java chaincode getTxId

Best Practices to follow while writing Hyperledger Fabric Chaincode

What should be some of the best practices to follow to avoid bugs and write efficient Hyperledger Fabric Chaincode?
General Guidelines for writing Hyperledger Fabric Chaincodes.
Refer to the below link for a detailed description on the same:
https://gist.github.com/arnabkaycee/d4c10a7f5c01f349632b42b67cee46db
Some steps are concisely mentioned below:
Use Chaincode DevMode
Use Chaincode Logging
Using logging is simple and easy. Use Fabric's inbuilt logger. Fabric provides logging mechanism as follows:
For Golang: https://godoc.org/github.com/hyperledger/fabric/core/chaincode/shim#ChaincodeLogger
For NodeJS: https://fabric-shim.github.io/Shim.html#.newLogger__anchor
For Java: You can use any standard logging framework like Log4J
Avoid using Global Keys - Hyperledger Fabric uses an Optimistic Locking Model while committing transactions. In the two-stage process of endorsement & committment, if some versions of the keys that you had read in the Endorsement has changed till your transactions reach the committing stage, you get an MVCC_READ_CONFLICT error. This often is a probability when one or more concurrent transactions are updating the same key.
Use Couch DB Queries wisely
Couch DB Queries DO NOT alter the READ SET of a transaction -
Mongo Queries are for querying the Key Value store aka StateDB only. It does not alter the read set of a transaction. This might lead to phantom reads in the transaction.
Only the DATA that you have stored in the couchDB is searchable - Do not be tempted to search for a key by its name using the MangoQuery. Although you can access the Fauxton console of the CouchDB, you cannot access a key by querying a key by which it is stored in the database. Example : Querying by channelName\0000KeyName is not allowed. It is better to store your key as a property in your data itself.
Write Deterministic Chaincode - Never write chaincode that is not deterministic. It means that if I execute the chaincode in 2 or more different environments at different times, result should always be the same, like setting the value as the current time or setting a random number. For example: Avoid statements like calling rand.New(...) , t := time.Now() or even relying on a global variable (check ) that is not persisted to the ledger.
This is because, that if the read write sets generated are not the same, the Validation System chaincode might reject it and throw an ENDORSEMENT_POLICY_FAILURE.
Be cautions when calling Other Chaincodes from your chaincode. - Invoking a chaincode from another is okay when both chaincodes are on the same channel. But be aware that if it is on the other channel then you get only what the chaincode function returns (only if the current invoker has rights to access data on that channel). NO data will be committed in the other channel, even if it attempts to write some. Currently, cross channel chaincode chaincode invocation does not alter data (change writesets) on the other channel. So, it is only possible to write to one channel at a time per transaction.
Remember to Set Chaincode Execution Timeout - Often it might so happen that during high load your chaincode might not complete its execution under 30s. It is a good practice to custom set your timeout as per your needs. This is goverened by the parameter in the core.yaml of the peer. You can override it by setting the environment variable in your docker compose file :
Example: CORE_CHAINCODE_EXECUTETIMEOUT=60s
Refrain from Accessing External Resources - Accessing external resources (http) might expose vulnerability and security threats to your chaincode. You do not want malicous code from external sources to influence your chaincode logic in any way. So keep away from external calls as much as possible.

Using endorsements in Hyperledger Fabric to design a process

I would really like to understand how endorsments work in Hyperledger Fabric in order to help me in designing a solution to a problem.
let's assume I am an endorser and a transaction proposal has just arrived. I would randomly select a participant within my organization, use its identity to perform the validations, checking for replay attacks etc then sign an endorsement with that participant's private key. Assuming I used an admin's credentials, the admin(person) may not be aware that I used its identities to validate and endorse a transaction proposal. Is this example correct?
Initial discussions here makes me feel like the more I look into it, the more confused I become. Could anyone help?
Just to start with, the endorser is the peer that capable to handle incoming invocation, maintain and run the chaincode. The flow works as following, support you have a client (C) and the endorsing peer (P), which runs a chaincode (CC).
Client forms transaction proposal request which includes parameters for chaincode invocation.
In order to get an endorsement for this proposal he sends it the endorsing peer.
Endorsing peer opens a transaction proposal and forwards requests to the required chaincode along the way it passes all parameters.
Chaincode get invoked which produces a RWset (set of keys and values read of changed during the invocation)
Peer collects RWset and forms proposal response and signs it
Client gets the proposal response, signs it as well and send it to the ordering service
Ordering service collects proposal responses and cuts the block which got distributed to the peers in the network.
Upon arrival peers opens a block and validates all transactions, one of the validation is to check whenever transaction conforms the endorsement policy, where basically it checks whenever transaction has enough signatures which satisfies the policy.
Back to your question, please note that at each step everyone uses its own key and certificate to sign, no one randomly selects participants to use they identities for signatures or whatever else.
PS. Note that process above a bit simplified and lack a lot of technical details.
PPS. There is a new course on Coursera which covers pretty well many technical aspects of Hyperledger Fabric architecture and the interaction between different components, I would urge you to consider taking this course.

Resources