From 95d39673ea5b5131aed3074e65f1c8c692c3c44a Mon Sep 17 00:00:00 2001 From: "S m, Aruna" Date: Sun, 18 Apr 2021 04:38:11 +0530 Subject: [PATCH] Enable TLS on asset-transfer-basic external chaincode 1. Introduce environment variables to enable or disable TLS at runtime. Also, introduce environment variables which carries the server key, cert and the client machine's root CA cert information. 2. Read the environment variables to decide with appropriate assumptions on default values to work as is today. Signed-off-by: S m, Aruna --- .../chaincode-external/assetTransfer.go | 54 +++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/asset-transfer-basic/chaincode-external/assetTransfer.go b/asset-transfer-basic/chaincode-external/assetTransfer.go index d66e0735..d9d75179 100644 --- a/asset-transfer-basic/chaincode-external/assetTransfer.go +++ b/asset-transfer-basic/chaincode-external/assetTransfer.go @@ -7,8 +7,10 @@ package main import ( "encoding/json" "fmt" + "io/ioutil" "log" "os" + "strconv" "github.com/hyperledger/fabric-chaincode-go/shim" "github.com/hyperledger/fabric-contract-api-go/contractapi" @@ -224,12 +226,58 @@ func main() { CCID: config.CCID, Address: config.Address, CC: chaincode, - TLSProps: shim.TLSProperties{ - Disabled: true, - }, + TLSProps: getTLSProperties(), } if err := server.Start(); err != nil { log.Panicf("error starting asset-transfer-basic chaincode: %s", err) } } + +func getTLSProperties() shim.TLSProperties { + // Check if chaincode is TLS enabled + tlsDisabledStr := getEnvOrDefault("CHAINCODE_TLS_DISABLED", "true") + key := getEnvOrDefault("CHAINCODE_TLS_KEY", "") + cert := getEnvOrDefault("CHAINCODE_TLS_CERT", "") + clientCACert := getEnvOrDefault("CHAINCODE_CLIENT_CA_CERT", "") + + // convert tlsDisabledStr to boolean + tlsDisabled := getBoolOrDefault(tlsDisabledStr, false) + + keyBytes, err := ioutil.ReadFile(key) + if err != nil { + log.Panicf("error while reading the crypto file: %s", err) + } + certBytes, err := ioutil.ReadFile(cert) + if err != nil { + log.Panicf("error while reading the crypto file: %s", err) + } + clientCACertBytes, err := ioutil.ReadFile(clientCACert) + if err != nil { + log.Panicf("error while reading the crypto file: %s", err) + } + return shim.TLSProperties{ + Disabled: tlsDisabled, + Key: keyBytes, + Cert: certBytes, + ClientCACerts: clientCACertBytes, + } +} + +func getEnvOrDefault(env, defaultVal string) string { + value, ok := os.LookupEnv(env) + if !ok { + value = defaultVal + } + return value +} + +// Note that the method returns default value if the string +// cannot be parsed! +func getBoolOrDefault(value string, defaultVal bool) bool { + parsed, err := strconv.ParseBool(value) + if err!= nil { + return defaultVal + } + return parsed +}