Esempio n. 1
0
func initCryptoClients() error {
	crypto.Init()

	// Initialize the clients mapping alice, bob, charlie and dave
	// to identities already defined in 'membersrvc.yaml'

	// Alice as jim
	if err := crypto.RegisterClient("jim", nil, "jim", "6avZQLwcUe9b"); err != nil {
		return err
	}
	var err error
	alice, err = crypto.InitClient("jim", nil)
	if err != nil {
		return err
	}

	// Bob as lukas
	if err := crypto.RegisterClient("lukas", nil, "lukas", "NPKYL39uKbkj"); err != nil {
		return err
	}
	bob, err = crypto.InitClient("lukas", nil)
	if err != nil {
		return err
	}

	bobCert, err = bob.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Bob TCert [%s]", err)
		return err
	}

	return nil
}
func setup() {
	// Conf
	viper.SetConfigName("asset") // name of config file (without extension)
	viper.AddConfigPath(".")     // path to look for the config file in
	err := viper.ReadInConfig()  // Find and read the config file
	if err != nil {              // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s] \n", err))
	}

	// Logging
	var formatter = logging.MustStringFormatter(
		`%{color}[%{module}] %{shortfunc} [%{shortfile}] -> %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)
	logging.SetFormatter(formatter)

	logging.SetLevel(logging.DEBUG, "peer")
	logging.SetLevel(logging.DEBUG, "chaincode")
	logging.SetLevel(logging.DEBUG, "cryptochain")

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	removeFolders()
}
Esempio n. 3
0
func initTCA() (*TCA, error) {
	//init the crypto layer
	if err := crypto.Init(); err != nil {
		return nil, fmt.Errorf("Failed initializing the crypto layer [%v]", err)
	}

	CacheConfiguration() // Cache configuration

	aca := NewACA()
	if aca == nil {
		return nil, fmt.Errorf("Could not create a new ACA")
	}

	eca := NewECA(aca)
	if eca == nil {
		return nil, fmt.Errorf("Could not create a new ECA")
	}

	tca := NewTCA(eca)
	if tca == nil {
		return nil, fmt.Errorf("Could not create a new TCA")
	}

	return tca, nil
}
Esempio n. 4
0
func initCryptoClients() error {
	crypto.Init()

	// Initialize the clients mapping charlie, dave, and edwina
	// to identities already defined in 'membersrvc.yaml'

	// Charlie as diego
	if err := crypto.RegisterClient("diego", nil, "diego", "DRJ23pEQl16a"); err != nil {
		return err
	}
	var err error
	charlie, err = crypto.InitClient("diego", nil)
	if err != nil {
		return err
	}

	// Dave as binhn
	if err := crypto.RegisterClient("binhn", nil, "binhn", "7avZQLwcUe9q"); err != nil {
		return err
	}
	dave, err = crypto.InitClient("binhn", nil)
	if err != nil {
		return err
	}

	// Edwina as test_user0
	if err := crypto.RegisterClient("test_user0", nil, "test_user0", "MS9qrN8hFjlE"); err != nil {
		return err
	}
	edwina, err = crypto.InitClient("test_user0", nil)
	if err != nil {
		return err
	}

	charlieCert, err = charlie.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Charlie ECert [%s]", err)
		return err
	}

	daveCert, err = dave.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Dave ECert [%s]", err)
		return err
	}

	edwinaCert, err = edwina.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Edwina ECert [%s]", err)
		return err
	}

	clients = map[string]crypto.Client{"charlie": charlie, "dave": dave, "edwina": edwina}
	certs = map[string]crypto.CertificateHandler{"charlie": charlieCert, "dave": daveCert, "edwina": edwinaCert}

	myClient = clients[user]
	myCert = certs[user]

	return nil
}
Esempio n. 5
0
func setup() {
	// Conf
	viper.SetConfigName("rbac") // name of config file (without extension)
	viper.AddConfigPath(".")    // path to look for the config file in
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file [%s] \n", err))
	}

	// Logging
	var formatter = logging.MustStringFormatter(
		`%{color}[%{module}] %{shortfunc} [%{shortfile}] -> %{level:.4s} %{id:03x}%{color:reset} %{message}`,
	)
	logging.SetFormatter(formatter)

	logging.SetLevel(logging.DEBUG, "peer")
	logging.SetLevel(logging.DEBUG, "chaincode")
	logging.SetLevel(logging.DEBUG, "cryptoain")

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	hl := filepath.Join(os.TempDir(), "hyperledger")

	viper.Set("peer.fileSystemPath", filepath.Join(hl, "production"))
	viper.Set("server.rootpath", filepath.Join(hl, "ca"))

	removeFolders()
}
Esempio n. 6
0
func TestNewCA(t *testing.T) {

	//init the crypto layer
	if err := crypto.Init(); err != nil {
		t.Errorf("Failed initializing the crypto layer [%s]", err)
	}

	//initialize logging to avoid panics in the current code
	LogInit(os.Stdout, os.Stdout, os.Stdout, os.Stderr, os.Stdout)

	//Create new CA
	ca := NewCA(name)
	if ca == nil {
		t.Error("could not create new CA")
	}

	missing := 0
	//check to see that the expected files were created
	for _, file := range caFiles {
		if _, err := os.Stat(ca.path + "/" + file); err != nil {
			missing++
			t.Logf("failed to find file [%s]", file)
		}
	}

	if missing > 0 {
		t.FailNow()
	}

	//check CA certificate for correct properties
	pem, err := ioutil.ReadFile(ca.path + "/" + name + ".cert")
	if err != nil {
		t.Fatalf("could not read CA X509 certificate [%s]", name+".cert")
	}

	cacert, err := primitives.PEMtoCertificate(pem)
	if err != nil {
		t.Fatalf("could not parse CA X509 certificate [%s]", name+".cert")
	}

	//check that commonname, organization and country match config
	org := GetConfigString("pki.ca.subject.organization")
	if cacert.Subject.Organization[0] != org {
		t.Fatalf("ca cert subject organization [%s] did not match configuration [%s]",
			cacert.Subject.Organization, org)
	}

	country := GetConfigString("pki.ca.subject.country")
	if cacert.Subject.Country[0] != country {
		t.Fatalf("ca cert subject country [%s] did not match configuration [%s]",
			cacert.Subject.Country, country)
	}

	//cleanup
	err = cleanupFiles(ca.path)
	if err != nil {
		t.Logf("Failed removing [%s] [%s]\n", ca.path, err)
	}

}
Esempio n. 7
0
func initTCA() (*TCA, error) {
	//init the crypto layer
	if err := crypto.Init(); err != nil {
		return nil, fmt.Errorf("Failed initializing the crypto layer [%v]", err)
	}

	//initialize logging to avoid panics in the current code
	LogInit(os.Stdout, os.Stdout, os.Stdout, os.Stderr, os.Stdout)
	CacheConfiguration() // Cache configuration
	eca := NewECA()
	if eca == nil {
		return nil, fmt.Errorf("Could not create a new ECA")
	}

	aca := NewACA()
	if aca == nil {
		return nil, fmt.Errorf("Could not create a new ACA")
	}

	tca := NewTCA(eca)
	if tca == nil {
		return nil, fmt.Errorf("Could not create a new TCA")
	}

	return tca, nil
}
Esempio n. 8
0
func main() {
	// For environment variables.
	viper.SetEnvPrefix(cmdRoot)
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	// Define command-line flags that are valid for all peer commands and
	// subcommands.
	mainFlags := mainCmd.PersistentFlags()
	mainFlags.BoolVarP(&versionFlag, "version", "v", false, "Display current version of fabric peer server")

	mainFlags.String("logging-level", "", "Default logging level and overrides, see core.yaml for full syntax")
	viper.BindPFlag("logging_level", mainFlags.Lookup("logging-level"))
	testCoverProfile := ""
	mainFlags.StringVarP(&testCoverProfile, "test.coverprofile", "", "coverage.cov", "Done")

	var alternativeCfgPath = os.Getenv("PEER_CFG_PATH")
	if alternativeCfgPath != "" {
		logger.Infof("User defined config file path: %s", alternativeCfgPath)
		viper.AddConfigPath(alternativeCfgPath) // Path to look for the config file in
	} else {
		viper.AddConfigPath("./") // Path to look for the config file in
		// Path to look for the config file in based on GOPATH
		gopath := os.Getenv("GOPATH")
		for _, p := range filepath.SplitList(gopath) {
			peerpath := filepath.Join(p, "src/github.com/hyperledger/fabric/peer")
			viper.AddConfigPath(peerpath)
		}
	}

	// Now set the configuration file.
	viper.SetConfigName(cmdRoot) // Name of config file (without extension)

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error when reading %s config file: %s\n", cmdRoot, err))
	}

	mainCmd.AddCommand(version.Cmd())
	mainCmd.AddCommand(node.Cmd())
	mainCmd.AddCommand(network.Cmd())
	mainCmd.AddCommand(chaincode.Cmd())

	runtime.GOMAXPROCS(viper.GetInt("peer.gomaxprocs"))

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed to initialize the crypto layer: %s", err))
	}

	// On failure Cobra prints the usage message and error string, so we only
	// need to exit with a non-0 status
	if mainCmd.Execute() != nil {
		os.Exit(1)
	}
	logger.Info("Exiting.....")
}
Esempio n. 9
0
// Init method will be called during deployment
func (t *RBACChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) {

	function, args := stub.GetFunctionAndParameters()
	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	myLogger.Info("Init")
	// if len(args) != 0 {
	// 	return nil, errors.New("Incorrect number of arguments. Expecting 0")
	// }

	myLogger.Debug("Creating RBAC Table...")

	// Create RBAC table
	err := stub.CreateTable("RBAC", []*shim.ColumnDefinition{
		&shim.ColumnDefinition{Name: "ID", Type: shim.ColumnDefinition_BYTES, Key: true},
		&shim.ColumnDefinition{Name: "Roles", Type: shim.ColumnDefinition_STRING, Key: false},
	})
	if err != nil {
		return nil, errors.New("Failed creating RBAC table.")
	}

	myLogger.Debug("Assign 'admin' role...")

	// Give to the deployer the role 'admin'
	deployer, err := stub.GetCallerMetadata()
	if err != nil {
		return nil, errors.New("Failed getting metadata.")
	}
	if len(deployer) == 0 {
		return nil, errors.New("Invalid admin certificate. Empty.")
	}

	myLogger.Debug("Add admin [% x][%s]", deployer, "admin")
	ok, err := stub.InsertRow("RBAC", shim.Row{
		Columns: []*shim.Column{
			&shim.Column{Value: &shim.Column_Bytes{Bytes: deployer}},
			&shim.Column{Value: &shim.Column_String_{String_: "admin"}},
		},
	})
	if !ok && err == nil {
		return nil, fmt.Errorf("Failed initiliazing RBAC entries.")
	}
	if err != nil {
		return nil, fmt.Errorf("Failed initiliazing RBAC entries [%s]", err)
	}

	myLogger.Debug("Done.")

	return nil, nil
}
Esempio n. 10
0
func TestChaincodeInvokeChaincodeWithSec(t *testing.T) {
	testDBWrapper.CleanDB(t)
	viper.Set("security.enabled", "true")

	//Initialize crypto
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	//set paths for memberservice to pick up
	viper.Set("peer.fileSystemPath", filepath.Join(os.TempDir(), "hyperledger", "production"))
	viper.Set("server.rootpath", filepath.Join(os.TempDir(), "ca"))

	var err error
	var memSrvcLis net.Listener
	if memSrvcLis, err = initMemSrvc(); err != nil {
		t.Fail()
		t.Logf("Error registering user  %s", err)
		return
	}

	time.Sleep(2 * time.Second)

	var peerLis net.Listener
	if peerLis, err = initPeer(); err != nil {
		finitMemSrvc(memSrvcLis)
		t.Fail()
		t.Logf("Error registering user  %s", err)
		return
	}

	if err = crypto.RegisterClient("jim", nil, "jim", "6avZQLwcUe9b"); err != nil {
		finitMemSrvc(memSrvcLis)
		finitPeer(peerLis)
		t.Fail()
		t.Logf("Error registering user  %s", err)
		return
	}

	//login as jim and test chaincode-chaincode interaction with security
	if err = chaincodeInvokeChaincode(t, "jim"); err != nil {
		finitMemSrvc(memSrvcLis)
		finitPeer(peerLis)
		t.Fail()
		t.Logf("Error executing test %s", err)
		return
	}

	//cleanup
	finitMemSrvc(memSrvcLis)
	finitPeer(peerLis)

}
Esempio n. 11
0
func initCryptoClients() error {
	crypto.Init()

	// Initialize the clients mapping alice, bob, charlie and dave
	// to identities already defined in 'membersrvc.yaml'

	// Alice as jim
	if err := crypto.RegisterClient("jim", nil, "jim", "6avZQLwcUe9b"); err != nil {
		return err
	}
	var err error
	alice, err = crypto.InitClient("jim", nil)
	if err != nil {
		return err
	}

	// Bob as lukas
	if err := crypto.RegisterClient("lukas", nil, "lukas", "NPKYL39uKbkj"); err != nil {
		return err
	}
	bob, err = crypto.InitClient("lukas", nil)
	if err != nil {
		return err
	}

	// Charlie
	if err := crypto.RegisterClient("diego", nil, "diego", "DRJ23pEQl16a"); err != nil {
		return err
	}
	charlie, err = crypto.InitClient("diego", nil)
	if err != nil {
		return err
	}

	// Dave as binhn
	if err := crypto.RegisterClient("binhn", nil, "binhn", "7avZQLwcUe9q"); err != nil {
		return err
	}
	dave, err = crypto.InitClient("binhn", nil)
	if err != nil {
		return err
	}

	return nil
}
Esempio n. 12
0
func main() {
	viper.SetEnvPrefix(envPrefix)
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)
	viper.SetConfigName("membersrvc")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./")
	// Path to look for the config file based on GOPATH
	gopath := os.Getenv("GOPATH")
	for _, p := range filepath.SplitList(gopath) {
		cfgpath := filepath.Join(p, "src/github.com/hyperledger/fabric/membersrvc")
		viper.AddConfigPath(cfgpath)
	}
	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error when reading %s config file: %s\n", "membersrvc", err))
	}

	var iotrace, ioinfo, iowarning, ioerror, iopanic io.Writer
	if viper.GetInt("logging.trace") == 1 {
		iotrace = os.Stdout
	} else {
		iotrace = ioutil.Discard
	}
	if viper.GetInt("logging.info") == 1 {
		ioinfo = os.Stdout
	} else {
		ioinfo = ioutil.Discard
	}
	if viper.GetInt("logging.warning") == 1 {
		iowarning = os.Stdout
	} else {
		iowarning = ioutil.Discard
	}
	if viper.GetInt("logging.error") == 1 {
		ioerror = os.Stderr
	} else {
		ioerror = ioutil.Discard
	}
	if viper.GetInt("logging.panic") == 1 {
		iopanic = os.Stdout
	} else {
		iopanic = ioutil.Discard
	}

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]", err))
	}

	ca.LogInit(iotrace, ioinfo, iowarning, ioerror, iopanic)
	// cache configure
	ca.CacheConfiguration()

	ca.Info.Println("CA Server (" + viper.GetString("server.version") + ")")

	aca := ca.NewACA()
	defer aca.Stop()

	eca := ca.NewECA()
	defer eca.Stop()

	tca := ca.NewTCA(eca)
	defer tca.Stop()

	tlsca := ca.NewTLSCA(eca)
	defer tlsca.Stop()

	runtime.GOMAXPROCS(viper.GetInt("server.gomaxprocs"))

	var opts []grpc.ServerOption
	if viper.GetString("server.tls.cert.file") != "" {
		creds, err := credentials.NewServerTLSFromFile(viper.GetString("server.tls.cert.file"), viper.GetString("server.tls.key.file"))
		if err != nil {
			panic(err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	srv := grpc.NewServer(opts...)

	aca.Start(srv)
	eca.Start(srv)
	tca.Start(srv)
	tlsca.Start(srv)

	if sock, err := net.Listen("tcp", viper.GetString("server.port")); err != nil {
		ca.Error.Println("Fail to start CA Server: ", err)
		os.Exit(1)
	} else {
		srv.Serve(sock)
		sock.Close()
	}
}
Esempio n. 13
0
func main() {
	// For environment variables.
	viper.SetEnvPrefix(cmdRoot)
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	// Define command-line flags that are valid for all peer commands and
	// subcommands.
	mainFlags := mainCmd.PersistentFlags()
	mainFlags.String("logging-level", "", "Default logging level and overrides, see core.yaml for full syntax")
	viper.BindPFlag("logging_level", mainFlags.Lookup("logging-level"))
	testCoverProfile := ""
	mainFlags.StringVarP(&testCoverProfile, "test.coverprofile", "", "coverage.cov", "Done")

	// Set the flags on the node start command.
	flags := nodeStartCmd.Flags()
	flags.BoolVarP(&chaincodeDevMode, "peer-chaincodedev", "", false, "Whether peer in chaincode development mode")

	// Now set the configuration file.
	viper.SetConfigName(cmdRoot) // Name of config file (without extension)
	viper.AddConfigPath("./")    // Path to look for the config file in
	// Path to look for the config file in based on GOPATH
	gopath := os.Getenv("GOPATH")
	for _, p := range filepath.SplitList(gopath) {
		peerpath := filepath.Join(p, "src/github.com/hyperledger/fabric/peer")
		viper.AddConfigPath(peerpath)
	}

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error when reading %s config file: %s\n", cmdRoot, err))
	}

	nodeCmd.AddCommand(nodeStartCmd)
	nodeCmd.AddCommand(nodeStatusCmd)

	nodeStopCmd.Flags().StringVar(&stopPidFile, "stop-peer-pid-file", viper.GetString("peer.fileSystemPath"), "Location of peer pid local file, for forces kill")
	nodeCmd.AddCommand(nodeStopCmd)

	mainCmd.AddCommand(nodeCmd)

	// Set the flags on the login command.
	networkLoginCmd.PersistentFlags().StringVarP(&loginPW, "password", "p", undefinedParamValue, "The password for user. You will be requested to enter the password if this flag is not specified.")

	networkCmd.AddCommand(networkLoginCmd)

	// vmCmd.AddCommand(vmPrimeCmd)
	// mainCmd.AddCommand(vmCmd)

	networkCmd.AddCommand(networkListCmd)

	mainCmd.AddCommand(networkCmd)

	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeLang, "lang", "l", "golang", fmt.Sprintf("Language the %s is written in", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeCtorJSON, "ctor", "c", "{}", fmt.Sprintf("Constructor message for the %s in JSON format", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeAttributesJSON, "attributes", "a", "[]", fmt.Sprintf("User attributes for the %s in JSON format", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodePath, "path", "p", undefinedParamValue, fmt.Sprintf("Path to %s", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeName, "name", "n", undefinedParamValue, fmt.Sprintf("Name of the chaincode returned by the deploy transaction"))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeUsr, "username", "u", undefinedParamValue, fmt.Sprintf("Username for chaincode operations when security is enabled"))
	chaincodeCmd.PersistentFlags().StringVarP(&customIDGenAlg, "tid", "t", undefinedParamValue, fmt.Sprintf("Name of a custom ID generation algorithm (hashing and decoding) e.g. sha256base64"))

	chaincodeQueryCmd.Flags().BoolVarP(&chaincodeQueryRaw, "raw", "r", false, "If true, output the query value as raw bytes, otherwise format as a printable string")
	chaincodeQueryCmd.Flags().BoolVarP(&chaincodeQueryHex, "hex", "x", false, "If true, output the query value byte array in hexadecimal. Incompatible with --raw")

	chaincodeCmd.AddCommand(chaincodeDeployCmd)
	chaincodeCmd.AddCommand(chaincodeInvokeCmd)
	chaincodeCmd.AddCommand(chaincodeQueryCmd)

	mainCmd.AddCommand(chaincodeCmd)

	runtime.GOMAXPROCS(viper.GetInt("peer.gomaxprocs"))

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed to initialize the crypto layer: %s", err))
	}

	// On failure Cobra prints the usage message and error string, so we only
	// need to exit with a non-0 status
	if mainCmd.Execute() != nil {
		//os.Exit(1)
	}
	logger.Info("Exiting.....")
}
Esempio n. 14
0
func main() {
	viper.AutomaticEnv()
	viper.SetConfigName("membersrvc")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}

	var iotrace, ioinfo, iowarning, ioerror, iopanic io.Writer
	if ca.GetConfigInt("logging.trace") == 1 {
		iotrace = os.Stdout
	} else {
		iotrace = ioutil.Discard
	}
	if ca.GetConfigInt("logging.info") == 1 {
		ioinfo = os.Stdout
	} else {
		ioinfo = ioutil.Discard
	}
	if ca.GetConfigInt("logging.warning") == 1 {
		iowarning = os.Stdout
	} else {
		iowarning = ioutil.Discard
	}
	if ca.GetConfigInt("logging.error") == 1 {
		ioerror = os.Stderr
	} else {
		ioerror = ioutil.Discard
	}
	if ca.GetConfigInt("logging.panic") == 1 {
		iopanic = os.Stdout
	} else {
		iopanic = ioutil.Discard
	}

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]%", err))
	}

	ca.LogInit(iotrace, ioinfo, iowarning, ioerror, iopanic)
	ca.Info.Println("CA Server (" + viper.GetString("server.version") + ")")

	eca := ca.NewECA()
	defer eca.Close()

	tca := ca.NewTCA(eca)
	defer tca.Close()

	tlsca := ca.NewTLSCA(eca)
	defer tlsca.Close()

	runtime.GOMAXPROCS(ca.GetConfigInt("server.gomaxprocs"))

	var opts []grpc.ServerOption
	if viper.GetString("server.tls.certfile") != "" {
		creds, err := credentials.NewServerTLSFromFile(viper.GetString("server.tls.certfile"), viper.GetString("server.tls.keyfile"))
		if err != nil {
			panic(err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	srv := grpc.NewServer(opts...)

	eca.Start(srv)
	tca.Start(srv)
	tlsca.Start(srv)

	if sock, err := net.Listen("tcp", ca.GetConfigString("server.port")); err != nil {
		ca.Error.Println("Fail to start CA Server: ", err)
		os.Exit(1)
	} else {
		srv.Serve(sock)
		sock.Close()
	}
}
Esempio n. 15
0
func main() {

	viper.SetEnvPrefix(envPrefix)
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)
	viper.SetConfigName("membersrvc")
	viper.SetConfigType("yaml")
	viper.AddConfigPath("./")
	// Path to look for the config file based on GOPATH
	gopath := os.Getenv("GOPATH")
	for _, p := range filepath.SplitList(gopath) {
		cfgpath := filepath.Join(p, "src/github.com/hyperledger/fabric/membersrvc")
		viper.AddConfigPath(cfgpath)
	}
	err := viper.ReadInConfig()
	if err != nil {
		logger.Panicf("Fatal error when reading %s config file: %s", "membersrvc", err)
	}

	flogging.LoggingInit("server")

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		logger.Panicf("Failed initializing the crypto layer [%s]", err)
	}

	// cache configure
	ca.CacheConfiguration()

	logger.Infof("CA Server (" + metadata.Version + ")")

	aca := ca.NewACA()
	defer aca.Stop()

	eca := ca.NewECA(aca)
	defer eca.Stop()

	tca := ca.NewTCA(eca)
	defer tca.Stop()

	tlsca := ca.NewTLSCA(eca)
	defer tlsca.Stop()

	runtime.GOMAXPROCS(viper.GetInt("server.gomaxprocs"))

	var opts []grpc.ServerOption
	if viper.GetString("server.tls.cert.file") != "" {
		creds, err := credentials.NewServerTLSFromFile(viper.GetString("server.tls.cert.file"), viper.GetString("server.tls.key.file"))
		if err != nil {
			logger.Panic(err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	srv := grpc.NewServer(opts...)

	if viper.GetBool("aca.enabled") {
		aca.Start(srv)
	}
	eca.Start(srv)
	tca.Start(srv)
	tlsca.Start(srv)

	if sock, err := net.Listen("tcp", viper.GetString("server.port")); err != nil {
		logger.Errorf("Fail to start CA Server: %s", err)
		os.Exit(1)
	} else {
		srv.Serve(sock)
		sock.Close()
	}
}
Esempio n. 16
0
func main() {
	// For environment variables.
	viper.SetEnvPrefix(cmdRoot)
	viper.AutomaticEnv()
	replacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(replacer)

	// Define command-line flags that are valid for all obc-peer commands and
	// subcommands.
	mainFlags := mainCmd.PersistentFlags()
	mainFlags.String("logging-level", "", "Default logging level and overrides, see core.yaml for full syntax")
	viper.BindPFlag("logging_level", mainFlags.Lookup("logging-level"))

	// Set the flags on the peer command.
	flags := peerCmd.Flags()
	flags.Bool("peer-tls-enabled", false, "Connection uses TLS if true, else plain TCP")
	flags.String("peer-tls-cert-file", "testdata/server1.pem", "TLS cert file")
	flags.String("peer-tls-key-file", "testdata/server1.key", "TLS key file")
	flags.Int("peer-port", 30303, "Port this peer listens to for incoming connections")
	flags.Int("peer-gomaxprocs", 2, "The maximum number threads excuting peer code")
	flags.Bool("peer-discovery-enabled", true, "Whether peer discovery is enabled")

	flags.BoolVarP(&chaincodeDevMode, "peer-chaincodedev", "", false, "Whether peer in chaincode development mode")

	viper.BindPFlag("peer_tls_enabled", flags.Lookup("peer-tls-enabled"))
	viper.BindPFlag("peer_tls_cert_file", flags.Lookup("peer-tls-cert-file"))
	viper.BindPFlag("peer_tls_key_file", flags.Lookup("peer-tls-key-file"))
	viper.BindPFlag("peer_port", flags.Lookup("peer-port"))
	viper.BindPFlag("peer_gomaxprocs", flags.Lookup("peer-gomaxprocs"))
	viper.BindPFlag("peer_discovery_enabled", flags.Lookup("peer-discovery-enabled"))

	// Now set the configuration file.
	viper.SetConfigName(cmdRoot) // Name of config file (without extension)
	viper.AddConfigPath("./")    // Path to look for the config file in
	// Path to look for the config file in based on GOPATH
	gopath := os.Getenv("GOPATH")
	for _, p := range filepath.SplitList(gopath) {
		peerpath := filepath.Join(p, "src/github.com/hyperledger/fabric/peer")
		viper.AddConfigPath(peerpath)
	}

	err := viper.ReadInConfig() // Find and read the config file
	if err != nil {             // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error when reading %s config file: %s\n", cmdRoot, err))
	}

	mainCmd.AddCommand(peerCmd)
	mainCmd.AddCommand(statusCmd)

	stopCmd.Flags().StringVarP(&stopPidFile, "stop-peer-pid-file", "", viper.GetString("peer.fileSystemPath"), "Location of peer pid local file, for forces kill")
	mainCmd.AddCommand(stopCmd)

	// Set the flags on the login command.
	loginCmd.PersistentFlags().StringVarP(&loginPW, "password", "p", undefinedParamValue, "The password for user. You will be requested to enter the password if this flag is not specified.")

	mainCmd.AddCommand(loginCmd)

	// vmCmd.AddCommand(vmPrimeCmd)
	// mainCmd.AddCommand(vmCmd)

	mainCmd.AddCommand(networkCmd)

	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeLang, "lang", "l", "golang", fmt.Sprintf("Language the %s is written in", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeCtorJSON, "ctor", "c", "{}", fmt.Sprintf("Constructor message for the %s in JSON format", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodePath, "path", "p", undefinedParamValue, fmt.Sprintf("Path to %s", chainFuncName))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeName, "name", "n", undefinedParamValue, fmt.Sprintf("Name of the chaincode returned by the deploy transaction"))
	chaincodeCmd.PersistentFlags().StringVarP(&chaincodeUsr, "username", "u", undefinedParamValue, fmt.Sprintf("Username for chaincode operations when security is enabled"))

	chaincodeQueryCmd.Flags().BoolVarP(&chaincodeQueryRaw, "raw", "r", false, "If true, output the query value as raw bytes, otherwise format as a printable string")
	chaincodeQueryCmd.Flags().BoolVarP(&chaincodeQueryHex, "hex", "x", false, "If true, output the query value byte array in hexadecimal. Incompatible with --raw")

	chaincodeCmd.AddCommand(chaincodeDeployCmd)
	chaincodeCmd.AddCommand(chaincodeInvokeCmd)
	chaincodeCmd.AddCommand(chaincodeQueryCmd)

	mainCmd.AddCommand(chaincodeCmd)

	runtime.GOMAXPROCS(viper.GetInt("peer.gomaxprocs"))

	// Init the crypto layer
	if err := crypto.Init(); err != nil {
		panic(fmt.Errorf("Failed initializing the crypto layer [%s]%", err))
	}

	// On failure Cobra prints the usage message and error string, so we only
	// need to exit with a non-0 status
	if mainCmd.Execute() != nil {
		os.Exit(1)
	}
}
Esempio n. 17
0
func initCryptoClients() error {
	crypto.Init()

	// Initialize the clients mapping bob, charlie, dave, and edwina
	// to identities already defined in 'membersrvc.yaml'

	// Bob as lukas
	if err := crypto.RegisterClient("lukas", nil, "lukas", "NPKYL39uKbkj"); err != nil {
		return err
	}
	var err error
	bob, err = crypto.InitClient("lukas", nil)
	if err != nil {
		return err
	}

	// Charlie as diego
	if err := crypto.RegisterClient("diego", nil, "diego", "DRJ23pEQl16a"); err != nil {
		return err
	}
	charlie, err = crypto.InitClient("diego", nil)
	if err != nil {
		return err
	}

	// Dave as binhn
	if err := crypto.RegisterClient("binhn", nil, "binhn", "7avZQLwcUe9q"); err != nil {
		return err
	}
	dave, err = crypto.InitClient("binhn", nil)
	if err != nil {
		return err
	}

	// Edwina as test_user0
	if err := crypto.RegisterClient("test_user0", nil, "test_user0", "MS9qrN8hFjlE"); err != nil {
		return err
	}
	edwina, err = crypto.InitClient("test_user0", nil)
	if err != nil {
		return err
	}

	bobCert, err = bob.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Bob ECert [%s]", err)
		return err
	}

	charlieCert, err = charlie.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Charlie ECert [%s]", err)
		return err
	}

	daveCert, err = dave.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Dave ECert [%s]", err)
		return err
	}

	edwinaCert, err = edwina.GetEnrollmentCertificateHandler()
	if err != nil {
		appLogger.Errorf("Failed getting Edwina ECert [%s]", err)
		return err
	}

	return nil
}