Exemplo n.º 1
0
//initialize peer and start up. If security==enabled, login as vp
func initPeer(chainID string) (net.Listener, error) {
	//start clean
	finitPeer(nil)
	var opts []grpc.ServerOption
	if viper.GetBool("peer.tls.enabled") {
		creds, err := credentials.NewServerTLSFromFile(viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file"))
		if err != nil {
			return nil, fmt.Errorf("Failed to generate credentials %v", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)

	viper.Set("peer.fileSystemPath", filepath.Join(os.TempDir(), "hyperledger", "production"))

	peerAddress, err := peer.GetLocalAddress()
	if err != nil {
		return nil, fmt.Errorf("Error obtaining peer address: %s", err)
	}
	lis, err := net.Listen("tcp", peerAddress)
	if err != nil {
		return nil, fmt.Errorf("Error starting peer listener %s", err)
	}

	//initialize ledger
	peer.MockInitialize()

	getPeerEndpoint := func() (*pb.PeerEndpoint, error) {
		return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil
	}

	// Install security object for peer
	if viper.GetBool("security.enabled") {
		//TODO:  integrate new crypto / idp
		securityLevel := viper.GetInt("security.level")
		hashAlgorithm := viper.GetString("security.hashAlgorithm")
		primitives.SetSecurityLevel(hashAlgorithm, securityLevel)
	} else {
		// the primitives need to be instantiated no matter what. Otherwise
		// the escc code won't have a hash algorithm available to hash the proposal
		primitives.SetSecurityLevel("SHA2", 256)
	}

	ccStartupTimeout := time.Duration(30000) * time.Millisecond
	pb.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(getPeerEndpoint, false, ccStartupTimeout))

	chaincode.RegisterSysCCs()

	if err = peer.MockCreateChain(chainID); err != nil {
		closeListenerAndSleep(lis)
		return nil, err
	}

	chaincode.DeploySysCCs(chainID)

	go grpcServer.Serve(lis)

	return lis, nil
}
Exemplo n.º 2
0
func TestGetValue_Clear_NullTCert(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)
	_, err := GetValueFrom("position", nil)
	if err == nil {
		t.Error(err)
	}
}
Exemplo n.º 3
0
func TestGetValue_Clear_InvalidAttribute(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
				metadata := []byte{32, 64}
		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: tcertder, metadata: attributeMetadata}*/
	stub := &chaincodeStubMock{callerCert: tcertder}
	handler, err := NewAttributesHandlerImpl(stub)
	if err != nil {
		t.Error(err)
	}

	value, err := handler.GetValue("age")
	if value != nil || err == nil {
		t.Fatalf("Test should fail [%v] \n", string(value))
	}
}
Exemplo n.º 4
0
func main() {
	primitives.SetSecurityLevel("SHA3", 256)
	err := shim.Start(new(AssetManagementChaincode))
	if err != nil {
		fmt.Printf("Error starting AssetManagementChaincode: %s", err)
	}
}
Exemplo n.º 5
0
func TestSignatureVerifierSHA2_384(t *testing.T) {
	// Create a signature
	primitives.SetSecurityLevel("SHA2", 384)

	cert, key, err := utils.NewSelfSignedCert()
	if err != nil {
		t.Fatal(err)
	}

	message := []byte("Hello World!")
	signature, err := utils.ECDSASign(key, message)
	if err != nil {
		t.Fatal(err)
	}

	// Instantiate a new SignatureVerifier
	sv := NewX509ECDSASignatureVerifier()

	// Verify the signature
	ok, err := sv.Verify(cert, signature, message)
	if err != nil {
		t.Fatal(err)
	}
	if !ok {
		t.Fatal("Signature does not verify")
	}
}
Exemplo n.º 6
0
func TestVerifyAttribute(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
	tcert, prek0, err := loadTCertAndPreK0() */
	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
		metadata := []byte{32, 64}

		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: tcertder, metadata: attributeMetadata}*/
	stub := &chaincodeStubMock{callerCert: tcertder}
	handler, err := NewAttributesHandlerImpl(stub)
	if err != nil {
		t.Error(err)
	}

	isOk, err := handler.VerifyAttribute("position", []byte("Software Engineer"))
	if err != nil {
		t.Error(err)
	}

	if !isOk {
		t.Fatal("Attribute not verified.")
	}
}
Exemplo n.º 7
0
func TestMain(m *testing.M) {
	// setup crypto algorithms
	primitives.SetSecurityLevel("SHA2", 256)
	// setup the MSP manager so that we can sign/verify
	mspMgrConfigDir := "../../msp/sampleconfig/"
	err := mspmgmt.LoadFakeSetupWithLocalMspAndTestChainMsp(mspMgrConfigDir)
	if err != nil {
		fmt.Printf("Could not initialize msp, err %s", err)
		os.Exit(-1)
		return
	}

	signer, err = mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
	if err != nil {
		fmt.Printf("Could not get signer")
		os.Exit(-1)
		return
	}

	signerSerialized, err = signer.Serialize()
	if err != nil {
		fmt.Printf("Could not serialize identity")
		os.Exit(-1)
		return
	}

	os.Exit(m.Run())
}
Exemplo n.º 8
0
func TestGetValue_Clear(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	value, err := GetValueFrom("position", tcertder)
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(value, []byte("Software Engineer")) != 0 {
		t.Fatalf("Value expected was [%v] and result was [%v].", []byte("Software Engineer"), value)
	}

	//Second time read from cache.
	value, err = GetValueFrom("position", tcertder)
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(value, []byte("Software Engineer")) != 0 {
		t.Fatalf("Value expected was [%v] and result was [%v].", []byte("Software Engineer"), value)
	}
}
Exemplo n.º 9
0
func TestVerifyAttributes_InvalidHeader(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
	tcert, prek0, err := loadTCertAndPreK0() */
	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}

	//Change header extensions
	tcert.Raw[583] = tcert.Raw[583] + 124

	tcertder := tcert.Raw
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
		metadata := []byte{32,64}
		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: tcertder, metadata: attributeMetadata}*/
	stub := &chaincodeStubMock{callerCert: tcertder}
	handler, err := NewAttributesHandlerImpl(stub)
	if err != nil {
		t.Error(err)
	}

	_, err = handler.VerifyAttributes(&accesscontrol.Attribute{Name: "position", Value: []byte("Software Engineer")})
	if err == nil {
		t.Fatal("Error can't be nil.")
	}
}
Exemplo n.º 10
0
func setupTestConfig() {
	primitives.SetSecurityLevel("SHA3", 256)
	viper.AutomaticEnv()
	viper.SetConfigName("ca_test") // name of config file (without extension)
	viper.AddConfigPath("./")      // path to look for the config file in
	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))
	}
}
Exemplo n.º 11
0
func TestGetValue_BadHeaderTCert(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	tcert, err := loadTCertFromFile("./test_resources/tcert_bad.dump")
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	_, err = GetValueFrom("position", tcertder)
	if err == nil {
		t.Fatal("Test should be fail due TCert has an invalid header.")
	}
}
Exemplo n.º 12
0
func TestMain(m *testing.M) {
	var err error
	primitives.SetSecurityLevel("SHA2", 256)

	// setup the MSP manager so that we can sign/verify
	mspMgrConfigDir := "../../msp/sampleconfig/"
	mspmgmt.LoadFakeSetupWithLocalMspAndTestChainMsp(mspMgrConfigDir)
	signer, err = mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
	if err != nil {
		os.Exit(-1)
		fmt.Printf("Could not initialize msp/signer")
		return
	}

	SetupTestConfig()
	os.Exit(m.Run())
}
Exemplo n.º 13
0
func TestNewAttributesHandlerImpl_InvalidCertificate(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)
	tcert, _, err := loadTCertAndPreK0()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	if err != nil {
		t.Error(err)
	}
	tcertder[0] = tcertder[0] + 1
	stub := &metadataErrorMock{callerCert: tcertder}
	_, err = NewAttributesHandlerImpl(stub)
	if err == nil {
		t.Fatal("Error shouldn't be nil")
	}
}
Exemplo n.º 14
0
func TestGetValue(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
	tcert, prek0, err := loadTCertAndPreK0() */
	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
			metadata := []byte{32, 64}

		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: tcertder, metadata: attributeMetadata}*/
	stub := &chaincodeStubMock{callerCert: tcertder}
	handler, err := NewAttributesHandlerImpl(stub)
	if err != nil {
		t.Error(err)
	}

	value, err := handler.GetValue("position")
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(value, []byte("Software Engineer")) != 0 {
		t.Fatalf("Value expected was [%v] and result was [%v].", []byte("Software Engineer"), value)
	}

	//Second time read from cache.
	value, err = handler.GetValue("position")
	if err != nil {
		t.Error(err)
	}

	if bytes.Compare(value, []byte("Software Engineer")) != 0 {
		t.Fatalf("Value expected was [%v] and result was [%v].", []byte("Software Engineer"), value)
	}
}
Exemplo n.º 15
0
func TestNewAttributesHandlerImpl_NullCertificate(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	/*
				TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
		tcert, prek0, err := loadTCertAndPreK0()
		tcert, err := loadTCertClear()
		if err != nil {
			t.Error(err)
		}
		metadata := []byte{32, 64}
		tcertder := tcert.Raw
		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: nil, metadata: attributeMetadata}*/
	stub := &chaincodeStubMock{callerCert: nil}
	_, err := NewAttributesHandlerImpl(stub)
	if err == nil {
		t.Fatal("Error can't be nil.")
	}
}
Exemplo n.º 16
0
func init() {
	var err error
	primitives.SetSecurityLevel("SHA2", 256)
	// setup the MSP manager so that we can sign/verify
	mspMgrConfigDir, err := getMSPMgrConfigDir()
	if err != nil {
		fmt.Printf("Could not get location of msp manager config file")
		os.Exit(-1)
		return
	}
	err = mspmgmt.LoadFakeSetupWithLocalMspAndTestChainMsp(mspMgrConfigDir)
	if err != nil {
		fmt.Printf("Could not load msp config, err %s", err)
		os.Exit(-1)
		return
	}
	signer, err = mspmgmt.GetLocalMSP().GetDefaultSigningIdentity()
	if err != nil {
		os.Exit(-1)
		fmt.Printf("Could not initialize msp/signer")
		return
	}
}
Exemplo n.º 17
0
func TestGetValue_InvalidAttribute(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
	tcert, prek0, err := loadTCertAndPreK0() */
	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}
	tcertder := tcert.Raw
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
				metadata := []byte{32, 64}
		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: tcertder, metadata: attributeMetadata}*/
	stub := &chaincodeStubMock{callerCert: tcertder}
	handler, err := NewAttributesHandlerImpl(stub)
	if err != nil {
		t.Error(err)
	}

	_, err = handler.GetValue("age")
	if err == nil {
		t.Error(err)
	}

	//Force invalid key
	handler.keys["position"] = nil
	_, err = handler.GetValue("positions")
	if err == nil {
		t.Error(err)
	}
}
Exemplo n.º 18
0
func TestVerifyAttributes_InvalidAttributeValue(t *testing.T) {
	primitives.SetSecurityLevel("SHA3", 256)

	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
	tcert, prek0, err := loadTCertAndPreK0() */
	tcert, err := loadTCertClear()
	if err != nil {
		t.Error(err)
	}

	//Change header extensions
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field. 337 is the offset in encrypted tcert.
	tcert.Raw[371] = tcert.Raw[371] + 124*/
	tcert.Raw[558] = tcert.Raw[558] + 124

	tcertder := tcert.Raw
	/*
			TODO: ##attributes-keys-pending This code have be redefined to avoid use of metadata field.
		metadata := []byte{32,64}
		attributeMetadata, err := attributes.CreateAttributesMetadata(tcertder, metadata, prek0, attributeNames)
		if err != nil {
			t.Error(err)
		}
		stub := &chaincodeStubMock{callerCert: tcertder, metadata: attributeMetadata} */
	stub := &chaincodeStubMock{callerCert: tcertder}
	handler, err := NewAttributesHandlerImpl(stub)
	if err != nil {
		t.Fatalf("Error creating attribute handlder %v", err)
	}

	v, err := handler.GetValue("position")
	if err == nil {
		t.Fatal("Error can't be nil." + string(v))
	}
}
Exemplo n.º 19
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(chaincode.Cmd(nil))
	mainCmd.AddCommand(clilogging.Cmd())

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

	// Init the crypto layer
	//TODO: integrate new crypto / idp code
	primitives.SetSecurityLevel("SHA2", 256)

	// Init the MSP
	// TODO: determine the location of this config file
	var mspMgrConfigDir string
	if alternativeCfgPath != "" {
		mspMgrConfigDir = alternativeCfgPath + "/msp/sampleconfig/"
	} else if _, err := os.Stat("./msp/sampleconfig/"); err == nil {
		mspMgrConfigDir = "./msp/sampleconfig/"
	} else {
		mspMgrConfigDir = os.Getenv("GOPATH") + "/src/github.com/hyperledger/fabric/msp/sampleconfig/"
	}

	// FIXME: when this peer joins a chain, it should get the
	// config for that chain with the list of MSPs that the
	// chain uses; however this is not yet implemented.
	// Additionally, we might always want to have an MSP for
	// the local test chain so that we can run tests with the
	// peer CLI. This is why we create this fake setup here for now
	err = mspmgmt.LoadFakeSetupWithLocalMspAndTestChainMsp(mspMgrConfigDir)
	if err != nil {
		panic(fmt.Errorf("Fatal error when setting up MSP from directory %s: err %s\n", mspMgrConfigDir, 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.....")
}