def enableTls(context, tlsEnabled): if not hasattr(context, "composition"): context.composition = Composition(context, startContainers=False) context.composition.environ[ "ORDERER_GENERAL_TLS_ENABLED"] = convertBoolean(tlsEnabled) context.composition.environ["CORE_PEER_TLS_ENABLED"] = convertBoolean( tlsEnabled)
def enableTls(context, tlsEnabled, projectName=None): if not hasattr(context, "composition"): context.composition = Composition(context, projectName=projectName, startContainers=False) context.composition.environ[ "ORDERER_GENERAL_TLS_ENABLED"] = convertBoolean(tlsEnabled) context.composition.environ["CORE_PEER_TLS_ENABLED"] = convertBoolean( tlsEnabled) context.composition.environ[ "FABRIC_CA_SERVER_TLS_ENABLED"] = convertBoolean(tlsEnabled)
def create_channel(self, context, orderer, channelId=TEST_CHANNEL_ID): configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) setup = self.get_env_vars(context, "peer0.org1.example.com") timeout = str(120 + common_util.convertToSeconds(context.composition.environ.get('CONFIGTX_ORDERER_BATCHTIMEOUT', '0s'))) command = ["peer", "channel", "create", "--file", "/var/hyperledger/configs/{0}/{1}.tx".format(context.composition.projectName, channelId), "--channelID", channelId, "--timeout", timeout, "--orderer", '{0}:7050'.format(orderer)] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/{1}/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir, orderer)] command.append('"') output = context.composition.docker_exec(setup+command, ['cli']) print("[{0}]: {1}".format(" ".join(setup+command), output)) if "SERVICE_UNAVAILABLE" in output['cli']: time.sleep(5) print("Received: {0}, Trying again...".format(output['cli'])) output = context.composition.docker_exec(setup+command, ['cli']) assert "Error:" not in output, "Unable to successfully create channel {}".format(channelId) return output
def instantiate_chaincode(self, context, chaincode, peers): configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) args = chaincode.get('args', '[]').replace('"', r'\"') output = {} for peer in peers: peerParts = peer.split('.') org = '.'.join(peerParts[1:]) setup = self.get_env_vars(context, peer) command = ["peer", "chaincode", "instantiate", "--name", chaincode['name'], "--version", str(chaincode.get('version', 0)), "--lang", chaincode['language'], "--channelID", str(chaincode.get('channelID', TEST_CHANNEL_ID)), "--ctor", r"""'{\"Args\": %s}'""" % (args)] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/orderer0.example.com/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir)] if "orderers" in chaincode: command = command + ["--orderer", '{0}:7050'.format(chaincode["orderers"][0])] if "user" in chaincode: command = command + ["--username", chaincode["user"]] if "policy" in chaincode: command = command + ["--policy", chaincode["policy"]] command.append('"') output[peer] = context.composition.docker_exec(setup + command, [peer]) print("[{0}]: {1}".format(" ".join(setup + command), output)) return output
def create_channel(self, context, orderers, channelId=TEST_CHANNEL_ID): configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) setup = self.get_env_vars(context, "peer0.org1.example.com") timeout = str(120 + common_util.convertToSeconds(context.composition.environ.get('CONFIGTX_ORDERER_BATCHTIMEOUT', '0s'))) command = ["peer", "channel", "create", "--file", "/var/hyperledger/configs/{0}/{1}.tx".format(context.composition.projectName, channelId), "--channelID", channelId, "--timeout", timeout, "--orderer", '{0}:7050'.format(orderers[0])] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/orderer0.example.com/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir)] command.append('"') output = context.composition.docker_exec(setup+command, ['cli']) print("[{0}]: {1}".format(" ".join(setup+command), output)) assert "Error:" not in output, "Unable to successfully create channel {}".format(channelId) # # For now, copy the channel block to the config directory # output = context.composition.docker_exec(["cp", # "{0}.block".format(channelId), # configDir], # ['cli']) # print("[{0}]: {1}".format(" ".join(command), output)) return output
def invoke_chaincode(self, context, chaincode, orderer, peer, channelId=TEST_CHANNEL_ID, targs="", user="******"): # channelId, targs and user are optional parameters with defaults set if they are not included configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) args = chaincode.get('args', '[]').replace('"', r'\"') peerParts = peer.split('.') org = '.'.join(peerParts[1:]) setup = self.get_env_vars(context, peer, user=user) command = ["peer", "chaincode", "invoke", "--name", chaincode['name'], "--ctor", r"""'{\"Args\": %s}'""" % (args), "--channelID", channelId] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/orderer0.example.com/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir)] if targs: #to escape " so that targs are compatible with cli command targs = targs.replace('"', r'\"') command = command + ["--transient", targs] command = command + ["--orderer", '{0}:7050'.format(orderer)] command.append('"') output = context.composition.docker_exec(setup+command, [peer]) print("Invoke[{0}]: {1}".format(" ".join(setup+command), str(output))) output = self.retry(context, output, peer, setup, command) return output
def upgrade_chaincode(self, context, orderer, peer, channelId=TEST_CHANNEL_ID, user="******"): configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) setup = self.get_env_vars(context, peer, user=user) command = ["peer", "chaincode", "upgrade", "--name", context.chaincode['name'], "--version", str(context.chaincode.get('version', 1)), "--channelID", str(context.chaincode.get('channelID', channelId))] if context.chaincode["args"]: command = command + ["--ctor", r"""'{\"Args\": %s}'""" % (str(context.chaincode["args"].replace('"', r'\"')))] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/orderer0.example.com/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir)] if "orderers" in context.chaincode: command = command + ["--orderer", '{}:7050'.format(orderer)] if "user" in context.chaincode: command = command + ["--username", context.chaincode["user"]] if context.chaincode.get("policy", None) is not None: command = command + ["--policy", context.chaincode["policy"].replace('"', r'\"')] command.append('"') output = context.composition.docker_exec(setup+command, ['peer0.org1.example.com']) print("[{0}]: {1}".format(" ".join(setup + command), output)) return output
def create_channel(self, context, orderer, channelId=TEST_CHANNEL_ID, user="******"): configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) setup = self.get_env_vars(context, "peer0.org1.example.com", user=user) # Ideally this would NOT be a 5 minute timeout, but more like a 2 minute timeout. timeout = 300 + common_util.convertToSeconds(context.composition.environ.get('CONFIGTX_ORDERER_BATCHTIMEOUT', '0s')) command = ["peer", "channel", "create", "--file", "/var/hyperledger/configs/{0}/{1}.tx".format(context.composition.projectName, channelId), "--channelID", channelId, "--timeout", "{}s".format(timeout), "--orderer", '{0}:7050'.format(orderer)] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/{1}/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir, orderer)] if hasattr(context, "mutual_tls") and context.mutual_tls: org = "org1.example.com" command = command + ["--clientauth", "--certfile", '{0}/peerOrganizations/{1}/users/{2}@{1}/tls/client.crt'.format(configDir, org, user), "--keyfile", '{0}/peerOrganizations/{1}/users/{2}@{1}/tls/client.key'.format(configDir, org, user)] command.append('"') output = context.composition.docker_exec(setup+command, ['cli']) print("[{0}]: {1}".format(" ".join(setup+command), output)) if "SERVICE_UNAVAILABLE" in output['cli']: time.sleep(5) print("Received: {0}, Trying again...".format(output['cli'])) output = context.composition.docker_exec(setup+command, ['cli']) assert "Error:" not in output, "Unable to successfully create channel {}".format(channelId) return output
def generateNetworkConfig(self, context): with open("./configs/network-config.json", "r") as fd: networkConfig = fd.read() grpcType = "grpc" proto = "http" if context.tls: grpcType = "grpcs" proto = "https" networkConfigFile = "{0}/configs/{1}/network-config.json".format(os.path.abspath('.'), context.projectName) with open("{1}/configs/{0}/ordererOrganizations/example.com/ca/ca.example.com-cert.pem".format(context.projectName, os.path.abspath('.')), "r") as fd: certs = fd.read().replace("\n", "\\r\\n") for org in ["org1.example.com", "org2.example.com"]: with open("{2}/configs/{0}/peerOrganizations/{1}/ca/ca.{1}-cert.pem".format(context.projectName, org, os.path.abspath('.')), "r") as fd: certs += fd.read().replace("\n", "\\r\\n") with open(networkConfigFile, "w+") as fd: structure = {"config": "{0}/configs/{1}".format(os.path.abspath('.'), context.projectName), "tls": common_util.convertBoolean(context.tls), "grpcType": grpcType, "proto": proto, "cacerts": certs, "networkId": context.projectName} updated = json.loads(networkConfig % (structure)) fd.write(json.dumps(updated, indent=2)) return networkConfigFile
def bootstrapped_impl(context, ordererType, database, tlsEnabled=False, timeout=300, ouEnabled=False): assert ordererType in config_util.ORDERER_TYPES, "Unknown network type '%s'" % ordererType curpath = os.path.realpath('.') # Get the correct composition file context.composeFile = getCompositionFiles(context, curpath, ordererType, database) # Should TLS be enabled context.tls = tlsEnabled compose_util.enableTls(context, tlsEnabled) # Perform bootstrap process context.ordererProfile = config_util.PROFILE_TYPES.get( ordererType, "SampleInsecureSolo") channelID = context.interface.SYS_CHANNEL_ID if hasattr(context, "composition"): context.projectName = context.composition.projectName elif not hasattr(context, "projectName"): context.projectName = str(uuid.uuid1()).replace('-', '') # Determine number of orderers numOrderers = 1 if ordererType == 'kafka': numOrderers = 3 # Get Configs setup if ouEnabled: config_util.buildCryptoFile( context, 2, 2, numOrderers, 2, ouEnable=common_util.convertBoolean(ouEnabled)) config_util.generateCrypto( context, "./configs/{0}/crypto.yaml".format(context.projectName)) else: config_util.generateCrypto(context) config_util.generateConfig(context, channelID, config_util.CHANNEL_PROFILE, context.ordererProfile) compose_impl(context, context.composeFile, projectName=context.projectName) wait_for_bootstrap_completion(context, timeout)
def instantiate_chaincode(self, context, peer="peer0.org1.example.com", user="******"): configDir = "/var/hyperledger/configs/{0}".format( context.composition.projectName) args = context.chaincode.get('args', '[]').replace('"', r'\"') output = {} peerParts = peer.split('.') org = '.'.join(peerParts[1:]) setup = self.get_env_vars(context, peer, user=user) command = [ "peer", "chaincode", "instantiate", "--name", context.chaincode['name'], "--version", str(context.chaincode.get('version', 0)), "--lang", context.chaincode['language'], "--channelID", str(context.chaincode.get('channelID', self.TEST_CHANNEL_ID)), "--ctor", r"""'{\"Args\": %s}'""" % (args) ] if context.tls: command = command + [ "--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/orderer0.example.com/msp/tlscacerts/tlsca.example.com-cert.pem' .format(configDir) ] if hasattr(context, "mutual_tls") and context.mutual_tls: command = command + [ "--clientauth", "--certfile", '{0}/peerOrganizations/{1}/users/{2}@{1}/tls/client.crt'. format(configDir, org, user), "--keyfile", '{0}/peerOrganizations/{1}/users/{2}@{1}/tls/client.key'. format(configDir, org, user) ] if "orderers" in context.chaincode: command = command + ["--orderer", 'orderer0.example.com:7050'] if "user" in context.chaincode: command = command + ["--username", context.chaincode["user"]] if context.chaincode.get("policy", None) is not None: command = command + [ "--policy", context.chaincode["policy"].replace('"', r'\"') ] command.append('"') output[peer] = context.composition.docker_exec(setup + command, [peer]) print("[{0}]: {1}".format(" ".join(setup + command), output)) return output
def generateNetworkConfig(self, context): with open("./configs/network-config.json", "r") as fd: networkConfig = fd.read() grpcType = "grpc" if context.tls: grpcType = "grpcs" networkConfigFile = "{0}/configs/{1}/network-config.json".format(os.path.abspath('.'), context.projectName) with open(networkConfigFile, "w+") as fd: structure = {"config": "{0}/configs/{1}".format(os.path.abspath('.'), context.projectName), "tls": common_util.convertBoolean(context.tls), "grpcType": grpcType, "networkId": context.projectName} updated = networkConfig % (structure) fd.write(updated) return networkConfigFile
def invoke_chaincode(self, context, chaincode, orderers, peer, channelId=TEST_CHANNEL_ID): configDir = "/var/hyperledger/configs/{0}".format(context.composition.projectName) args = chaincode.get('args', '[]').replace('"', r'\"') peerParts = peer.split('.') org = '.'.join(peerParts[1:]) setup = self.get_env_vars(context, peer) command = ["peer", "chaincode", "invoke", "--name", chaincode['name'], "--ctor", r"""'{\"Args\": %s}'""" % (args), "--channelID", channelId] if context.tls: command = command + ["--tls", common_util.convertBoolean(context.tls), "--cafile", '{0}/ordererOrganizations/example.com/orderers/orderer0.example.com/msp/tlscacerts/tlsca.example.com-cert.pem'.format(configDir)] command = command + ["--orderer", '{0}:7050'.format(orderers[0])] command.append('"') output = context.composition.docker_exec(setup+command, [peer]) print("Invoke[{0}]: {1}".format(" ".join(setup+command), str(output))) return output
def buildCryptoFile(context, numOrgs, numPeers, numOrderers, numUsers, orgName=None, ouEnable=False): testConfigs = makeProjectConfigDir(context) # Orderer Stanza ordererHostStr = "" for count in range(int(numOrderers)): ordererHostStr += ORDERER_HOST.format(count=count) ordererStr = ORDERER_STR + ordererHostStr # Peer Stanza peerStanzas = "" for count in range(int(numOrgs)): name = "Org{0}ExampleCom".format(count + 1) domain = "org{0}.example.com".format(count + 1) if orgName is not None: name = orgName.title().replace('.', '') domain = orgName if type(ouEnable) == bool: ouEnableStr = common_util.convertBoolean(ouEnable) elif ouEnable == name: ouEnableStr = "true" else: ouEnableStr = "false" peerStanzas += PEER_ORG_STR.format(name=name, domain=domain, numPeers=numPeers, numUsers=numUsers, ouEnable=ouEnableStr) peerStr = "PeerOrgs:" + peerStanzas cryptoStr = ordererStr + "\n\n" + peerStr with open("{0}/crypto.yaml".format(testConfigs), "w") as fd: fd.write(cryptoStr)