Install chaincode programmatically¶
To install chaincode inside our application, we need to reach out to system chaincode called _lifecycle.
Following piece of code can be taken as a reference:
1func InstallChaincode(network *client.Network, arguments *lifecycle.InstallChaincodeArgs) (*lifecycle.InstallChaincodeResult, error) {
2 lifecycleChaincode := network.GetContract("_lifecycle")
3
4 argumentsBytes, err := proto.Marshal(arguments)
5 if err != nil {
6 return nil, err
7 }
8
9 chaincodesBytes, err := lifecycleChaincode.EvaluateTransaction("InstallChaincode", string(argumentsBytes))
10 if err != nil {
11 return nil, err
12 }
13
14 installedChaincode := new(lifecycle.InstallChaincodeResult)
15 err = proto.Unmarshal(chaincodesBytes, installedChaincode)
16 if err != nil {
17 return nil, err
18 }
19
20 return installedChaincode, nil
21}
- Where:
lifecycle.InstallChaincodeArgs- protobuf struct that theInstallChaincodechaincode function expects while installing the chaincode (lifecyclepackage is imported from"github.com/hyperledger/fabric-protos-go-apiv2/peer/lifecycle")lifecycle.InstallChaincodeResult- the return type ofInstallChaincodechaincode function
lifecycle.InstallChaincodeArgs has ChaincodeInstallPackage field that we fill with the target chaincode. Take a look at this function usage:
1// ...
2
3arguments := lifecycle.InstallChaincodeArgs{ChaincodeInstallPackage: myChaincodeBytes}
4result, err := InstallChaincode(network, &arguments)
5
6fmt.Printf("Label: %v, Package id: %v", result.Label, result.PackageId)