func startTLSCA(t *testing.T) { CacheConfiguration() // Cache configuration ecaS = NewECA(nil) tlscaS = NewTLSCA(ecaS) var opts []grpc.ServerOption creds, err := credentials.NewServerTLSFromFile(viper.GetString("server.tls.cert.file"), viper.GetString("server.tls.key.file")) if err != nil { t.Logf("Failed creating credentials for TLS-CA service: %s", err) t.Fail() } opts = []grpc.ServerOption{grpc.Creds(creds)} srv = grpc.NewServer(opts...) ecaS.Start(srv) tlscaS.Start(srv) sock, err := net.Listen("tcp", viper.GetString("server.port")) if err != nil { t.Logf("Failed to start TLS-CA service: %s", err) t.Fail() } srv.Serve(sock) }
func startPKI() { var opts []grpc.ServerOption if viper.GetBool("peer.pki.tls.enabled") { // TLS configuration creds, err := credentials.NewServerTLSFromFile( filepath.Join(viper.GetString("server.rootpath"), "tlsca.cert"), filepath.Join(viper.GetString("server.rootpath"), "tlsca.priv"), ) if err != nil { panic("Failed creating credentials for OBC-CA: " + err.Error()) } opts = []grpc.ServerOption{grpc.Creds(creds)} } fmt.Printf("open socket...\n") sockp, err := net.Listen("tcp", viper.GetString("server.port")) if err != nil { panic("Cannot open port: " + err.Error()) } fmt.Printf("open socket...done\n") server = grpc.NewServer(opts...) eca.Start(server) tca.Start(server) tlsca.Start(server) fmt.Printf("start serving...\n") server.Serve(sockp) }
//Start Start func Start(port int, tls bool, certFile, keyFile string, ch chan string) { log.Println("demo start") sid = utils.Randstr20() s := new(grpcService) lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { grpclog.Fatalf("failed to listen: %v", err) } var opts []grpc.ServerOption if tls { creds, err := credentials.NewServerTLSFromFile(certFile, keyFile) if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) demo.RegisterRPCServer(grpcServer, s) go func() { <-ch grpcServer.Stop() }() grpcServer.Serve(lis) log.Println("demo end") }
func startTLSCA(t *testing.T) { LogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, os.Stdout) eca_s = NewECA() tlsca_s = NewTLSCA(eca_s) var opts []grpc.ServerOption creds, err := credentials.NewServerTLSFromFile(viper.GetString("server.tls.certfile"), viper.GetString("server.tls.keyfile")) if err != nil { t.Logf("Failed creating credentials for TLS-CA service: %s", err) t.Fail() } opts = []grpc.ServerOption{grpc.Creds(creds)} srv = grpc.NewServer(opts...) eca_s.Start(srv) tlsca_s.Start(srv) sock, err := net.Listen("tcp", viper.GetString("server.port")) if err != nil { t.Logf("Failed to start TLS-CA service: %s", err) t.Fail() } srv.Serve(sock) }
func main() { flag.Parse() lis, err := net.Listen("tcp", *serverAddr) if err != nil { grpclog.Fatalf("failed to listen: %v", err) } var opts []grpc.ServerOption if *tls { creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = append(opts, grpc.Creds(creds)) } grpcServer := grpc.NewServer(opts...) oidcClient, err := util.GetOIDCClient(*clientID, *clientSecret, *discovery, *redirectURL) if err != nil { grpclog.Fatalf("unable to get oidc client: %s", err) } s, err := server.NewRoloServer(oidcClient, *policyFile) if err != nil { grpclog.Fatalln("unable to create ca from parent:", err) } pb.RegisterRoloServer(grpcServer, s) grpclog.Println("serving at", *serverAddr) grpcServer.Serve(lis) }
func (s *Server) ListenGRPC() error { grpcPort := s.Config.GetGrpcPortString() //Listen lis, err := net.Listen("tcp", grpcPort) if err != nil { return fmt.Errorf("server.go: failed to listen, %v", err) } var opts []grpc.ServerOption if s.Config.TlsCertFile != "" && s.Config.TlsKeyFile != "" { creds, err := credentials.NewServerTLSFromFile(s.Config.TlsCertFile, s.Config.TlsKeyFile) if err != nil { return fmt.Errorf("server.go: Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } s.checker = health.New(s, s.DB) grpcServer := grpc.NewServer(opts...) man := newABManager(s) s.ab = man ab := &abTestServer{m: man, s: s} registryGrpc := &RegistryServer{server: s} otsimopb.RegisterRegistryServiceServer(grpcServer, registryGrpc) otsimopb.RegisterABTestServer(grpcServer, ab) grpc_health_v1.RegisterHealthServer(grpcServer, s.checker) log.Infof("server.go: Binding %s for grpc", grpcPort) return grpcServer.Serve(lis) }
func (s *Server) ListenGRPC() error { grpcPort := s.Config.GetGrpcPortString() //Listen lis, err := net.Listen("tcp", grpcPort) if err != nil { return fmt.Errorf("server.go: failed to listen: %v", err) } var opts []grpc.ServerOption if s.Config.TlsCertFile != "" && s.Config.TlsKeyFile != "" { creds, err := credentials.NewServerTLSFromFile(s.Config.TlsCertFile, s.Config.TlsKeyFile) if err != nil { log.Fatalf("server.go: Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} s.tlsCheck = tlscheck.New(s.Config.TlsCertFile, s.Config.TlsKeyFile, time.Hour*24*16) } h := health.New(s, s.Storage) grpcServer := grpc.NewServer(opts...) catalogGrpc := &catalogGrpcServer{ server: s, } pb.RegisterCatalogServiceServer(grpcServer, catalogGrpc) grpc_health_v1.RegisterHealthServer(grpcServer, h) go http.ListenAndServe(s.Config.GetHealthPortString(), h) log.Infof("server.go: Binding %s for grpc", grpcPort) //Serve return grpcServer.Serve(lis) }
func main() { // 2. 解析flags flag.Parse() // 3. 监听端口 lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)) if err != nil { grpclog.Fatalf("failed to listen: %v", err) } // 4. 指定TLS var opts []grpc.ServerOption if *tls { creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } // 关联Server和Handler grpcServer := grpc.NewServer(opts...) pb.RegisterRouteGuideServer(grpcServer, newServer()) grpcServer.Serve(lis) }
func (cc *CCServer) Serve() error { l, err := net.Listen("tcp", cc.cfg.ListenAddress) if err != nil { return err } var opts []grpc.ServerOption if cc.cfg.UseTLS { if cc.cfg.MutualTLS { mtc, err := mutualTLS(*cc.cfg) if err != nil { return err } creds := credentials.NewTLS(mtc) opts = []grpc.ServerOption{grpc.Creds(creds)} } else { creds, err := credentials.NewServerTLSFromFile(cc.cfg.CertFile, cc.cfg.KeyFile) if err != nil { return err } opts = []grpc.ServerOption{grpc.Creds(creds)} } } s := grpc.NewServer(opts...) pb.RegisterCmdCtrlServer(s, cc) return s.Serve(l) }
func (rs *RingSyndicates) launchSyndicates(k int) { rs.Syndics[k].Lock() defer rs.waitGroup.Done() rs.waitGroup.Add(1) l, err := net.Listen("tcp", fmt.Sprintf(":%d", rs.Syndics[k].config.Port)) if err != nil { log.Fatalln(err) return } var opts []grpc.ServerOption creds, err := credentials.NewServerTLSFromFile(rs.Syndics[k].config.CertFile, rs.Syndics[k].config.KeyFile) if err != nil { log.Fatalln("Error load cert or key:", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} rs.Syndics[k].gs = grpc.NewServer(opts...) if rs.Syndics[k].config.Master { pb.RegisterSyndicateServer(rs.Syndics[k].gs, rs.Syndics[k].server) log.Println("Master starting up on", rs.Syndics[k].config.Port) rs.Syndics[k].gs.Serve(l) } else { //pb.RegisterRingDistServer(s, newRingDistServer()) //log.Printf("Starting ring slave up on %d...\n", cfg.Port) //s.Serve(l) log.Fatalln("Syndicate slaves not implemented yet") } rs.Syndics[k].Unlock() }
func createEventHubServer() (net.Listener, *grpc.Server, error) { var lis net.Listener var grpcServer *grpc.Server var err error if viper.GetBool("peer.validator.enabled") { lis, err = net.Listen("tcp", viper.GetString("peer.validator.events.address")) if err != nil { return nil, nil, fmt.Errorf("failed to listen: %v", err) } //TODO - do we need different SSL material for events ? 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, nil, fmt.Errorf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer = grpc.NewServer(opts...) ehServer := producer.NewOpenchainEventsServer(uint(viper.GetInt("peer.validator.events.buffersize")), viper.GetInt("peer.validator.events.timeout")) pb.RegisterOpenchainEventsServer(grpcServer, ehServer) } return lis, grpcServer, err }
// Test the execution of an invalid transaction. func TestExecuteInvokeInvalidTransaction(t *testing.T) { testDBWrapper.CleanDB(t) 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 { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) viper.Set("peer.fileSystemPath", "/var/hyperledger/test/tmpdb") //use a different address than what we usually use for "peer" //we override the peerAddress set in chaincode_support.go peerAddress := "0.0.0.0:21212" lis, err := net.Listen("tcp", peerAddress) if err != nil { t.Fail() t.Logf("Error starting peer listener %s", err) return } getPeerEndpoint := func() (*pb.PeerEndpoint, error) { return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil)) go grpcServer.Serve(lis) var ctxt = context.Background() url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02" chaincodeID := &pb.ChaincodeID{Path: url} //FAIL, FAIL! args := []string{"x", "-1"} err = invokeExample02Transaction(ctxt, chaincodeID, args, false) //this HAS to fail with expectedDeltaStringPrefix if err != nil { errStr := err.Error() t.Logf("Got error %s\n", errStr) t.Logf("InvalidInvoke test passed") GetChain(DefaultChain).Stop(ctxt, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeID: chaincodeID}}) closeListenerAndSleep(lis) return } t.Fail() t.Logf("Error invoking transaction %s", err) GetChain(DefaultChain).Stop(ctxt, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeID: chaincodeID}}) closeListenerAndSleep(lis) }
func main() { f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("error opening file: %v", err) } log.SetOutput(io.MultiWriter(f, os.Stdout)) http.HandleFunc("/", fronthandler) http.HandleFunc("/_ah/health", healthhandler) go http.ListenAndServe(httpport, nil) ce, err := credentials.NewServerTLSFromFile("server_crt.pem", "server_key.pem") if err != nil { log.Fatalf("Failed to generate credentials %v", err) } lis, err := net.Listen("tcp", grpcport) if err != nil { log.Fatalf("failed to listen: %v", err) } sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(10)} sopts = append(sopts, grpc.Creds(ce)) s := grpc.NewServer(sopts...) echo.RegisterEchoServerServer(s, &server{}) log.Printf("Starting gRPC server on port %v", grpcport) s.Serve(lis) }
func createGRPCLayer(port int) (*grpc.Server, net.Listener, grpc.DialOption) { var s *grpc.Server var ll net.Listener var err error var serverOpts []grpc.ServerOption var dialOpts grpc.DialOption keyFileName := fmt.Sprintf("key.%d.pem", time.Now().UnixNano()) certFileName := fmt.Sprintf("cert.%d.pem", time.Now().UnixNano()) defer os.Remove(keyFileName) defer os.Remove(certFileName) err = generateCertificates(keyFileName, certFileName) if err == nil { var creds credentials.TransportCredentials creds, err = credentials.NewServerTLSFromFile(certFileName, keyFileName) serverOpts = append(serverOpts, grpc.Creds(creds)) ta := credentials.NewTLS(&tls.Config{ InsecureSkipVerify: true, }) dialOpts = grpc.WithTransportCredentials(&authCreds{tlsCreds: ta}) } else { dialOpts = grpc.WithInsecure() } listenAddress := fmt.Sprintf("%s:%d", "", port) ll, err = net.Listen("tcp", listenAddress) if err != nil { panic(err) } s = grpc.NewServer(serverOpts...) return s, ll, dialOpts }
// NewGrpcServer - func NewGrpcServer(serv services.Servicer, opts options.Options, logger *logging.Entry) (Serverer, error) { addr, addrOk := opts.Get("grpc-addr") if !addrOk { return nil, errors.New("You must provide `grpc-addr` in order to create gRPC server...") } listener, err := net.Listen("tcp", addr.String()) if err != nil { return nil, fmt.Errorf("Failed to listen: %v", err) } var grpcOpts []grpc.ServerOption if useGrpc, ok := opts.Get("grpc-tls"); ok && useGrpc.Bool() { certFile, certOk := opts.Get("grpc-tls-cert") certKey, keyOk := opts.Get("grpc-tls-key") if !certOk { return nil, errors.New("You must provide `grpc-tls-cert` in order to create gRPC server...") } if !keyOk { return nil, errors.New("You must provide `grpc-tls-key` in order to create gRPC server...") } creds, err := credentials.NewServerTLSFromFile(certFile.String(), certKey.String()) if err != nil { return nil, fmt.Errorf("Failed to generate gRPC credentials: %v", err) } grpcOpts = []grpc.ServerOption{grpc.Creds(creds)} } if maxStreams, msOk := opts.Get("grpc-max-concurrent-streams"); msOk { grpcOpts = []grpc.ServerOption{grpc.MaxConcurrentStreams(maxStreams.UInt32())} } grpcServer := grpc.NewServer(grpcOpts...) s := &Grpc{ Options: opts, Server: grpcServer, Listener: listener, Entry: logger, Servicer: serv, ConnectivityState: &ConnectivityState{}, Interrupt: serv.GetInterruptChan(), } if listenForever, lfOk := opts.Get("grpc-listen-forever"); lfOk { s.ListenForever = listenForever.Bool() } return Serverer(s), nil }
func TestExecuteInvokeTransaction(t *testing.T) { testDBWrapper.CleanDB(t) var opts []grpc.ServerOption //TLS is on by default. This is the ONLY test that does NOT use TLS viper.Set("peer.tls.enabled", false) //turn OFF keepalive. All other tests use keepalive viper.Set("peer.chaincode.keepalive", "0") 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 { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) viper.Set("peer.fileSystemPath", "/var/hyperledger/test/tmpdb") //use a different address than what we usually use for "peer" //we override the peerAddress set in chaincode_support.go peerAddress := "0.0.0.0:21212" lis, err := net.Listen("tcp", peerAddress) if err != nil { t.Fail() t.Logf("Error starting peer listener %s", err) return } getPeerEndpoint := func() (*pb.PeerEndpoint, error) { return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil)) go grpcServer.Serve(lis) var ctxt = context.Background() url := "github.com/hyperledger/fabric/examples/chaincode/go/chaincode_example02" chaincodeID := &pb.ChaincodeID{Path: url} args := []string{"a", "b", "10"} err = invokeExample02Transaction(ctxt, chaincodeID, args, true) if err != nil { t.Fail() t.Logf("Error invoking transaction: %s", err) } else { fmt.Printf("Invoke test passed\n") t.Logf("Invoke test passed") } GetChain(DefaultChain).Stop(ctxt, &pb.ChaincodeDeploymentSpec{ChaincodeSpec: &pb.ChaincodeSpec{ChaincodeID: chaincodeID}}) closeListenerAndSleep(lis) }
//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 }
func main() { flag.Parse() creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile) if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } opts := []grpc.ServerOption{grpc.Creds(creds)} fmt.Printf("grpc on port: %d\n", *port) serve(opts) }
// main the control function func main() { cfg := resolveConfig(nil) var opts []grpc.ServerOption creds, err := credentials.NewServerTLSFromFile(path.Join(cfg.path, "server.crt"), path.Join(cfg.path, "server.key")) FatalIf(err, "Couldn't load cert from file") opts = []grpc.ServerOption{grpc.Creds(creds)} s := grpc.NewServer(opts...) var cOpts []grpc.DialOption tlsConfig := &ftls.Config{ MutualTLS: !cfg.skipMutualTLS, InsecureSkipVerify: cfg.insecureSkipVerify, CertFile: path.Join(cfg.path, "client.crt"), KeyFile: path.Join(cfg.path, "client.key"), CAFile: path.Join(cfg.path, "ca.pem"), } rOpts, err := ftls.NewGRPCClientDialOpt(&ftls.Config{ MutualTLS: false, InsecureSkipVerify: cfg.insecureSkipVerify, CAFile: path.Join(cfg.path, "ca.pem"), }) if err != nil { grpclog.Fatalln("Cannot setup tls config for synd client:", err) } clientID, _ := os.Hostname() if clientID != "" { clientID += "/oohhc-filesysd" } gstore := api.NewReplGroupStore(&api.ReplGroupStoreConfig{ AddressIndex: 2, StoreFTLSConfig: tlsConfig, GRPCOpts: cOpts, RingServer: cfg.oortGroupSyndicate, RingCachePath: path.Join(cfg.path, "ring/groupstore.ring"), RingServerGRPCOpts: []grpc.DialOption{rOpts}, RingClientID: clientID, }) if gerr := gstore.Startup(context.Background()); gerr != nil { grpclog.Fatalln("Cannot start valuestore connector:", gerr) } fs, err := NewFileSystemWS(gstore) if err != nil { grpclog.Fatalln(err) } l, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.port)) FatalIf(err, "Failed to bind to port") fb.RegisterFileSystemAPIServer(s, NewFileSystemAPIServer(fs)) grpclog.Printf("Starting up on %d...\n", cfg.port) s.Serve(l) }
// Test deploy of a transaction. func TestExecuteDeploySysChaincode(t *testing.T) { 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 { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) viper.Set("peer.fileSystemPath", "/var/hyperledger/test/tmpdb") //lis, err := net.Listen("tcp", viper.GetString("peer.address")) //use a different address than what we usually use for "peer" //we override the peerAddress set in chaincode_support.go peerAddress := "0.0.0.0:40303" lis, err := net.Listen("tcp", peerAddress) if err != nil { t.Fail() t.Logf("Error starting peer listener %s", err) return } getPeerEndpoint := func() (*pb.PeerEndpoint, error) { return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil)) go grpcServer.Serve(lis) var ctxt = context.Background() system_chaincode.RegisterSysCCs() url := "github.com/hyperledger/fabric/core/system_chaincode/sample_syscc" args := []string{"greeting", "hello world"} cds := &pb.ChaincodeDeploymentSpec{ExecEnv: 1, ChaincodeSpec: &pb.ChaincodeSpec{Type: 1, ChaincodeID: &pb.ChaincodeID{Name: "sample_syscc", Path: url}, CtorMsg: &pb.ChaincodeInput{Args: args}}} _, err = deploy2(ctxt, cds) chaincodeID := cds.ChaincodeSpec.ChaincodeID.Name if err != nil { GetChain(DefaultChain).Stop(ctxt, cds) closeListenerAndSleep(lis) t.Fail() t.Logf("Error deploying <%s>: %s", chaincodeID, err) return } GetChain(DefaultChain).Stop(ctxt, cds) closeListenerAndSleep(lis) }
// start starts server. Other goroutines should block on s.readyChan for futher operations. func (s *server) start(useTLS bool, port int, maxStreams uint32, ht hType) { var err error if port == 0 { s.lis, err = net.Listen("tcp", ":0") } else { s.lis, err = net.Listen("tcp", ":"+strconv.Itoa(port)) } if err != nil { log.Fatalf("failed to listen: %v", err) } if useTLS { creds, err := credentials.NewServerTLSFromFile(tlsDir+"server1.pem", tlsDir+"server1.key") if err != nil { log.Fatalf("Failed to generate credentials %v", err) } s.lis = creds.NewListener(s.lis) } _, p, err := net.SplitHostPort(s.lis.Addr().String()) if err != nil { log.Fatalf("failed to parse listener address: %v", err) } s.port = p s.conns = make(map[ServerTransport]bool) if s.readyChan != nil { close(s.readyChan) } for { conn, err := s.lis.Accept() if err != nil { return } t, err := NewServerTransport("http2", conn, maxStreams) if err != nil { return } s.mu.Lock() if s.conns == nil { s.mu.Unlock() t.Close() return } s.conns[t] = true s.mu.Unlock() h := &testStreamHandler{t} switch ht { case suspended: go t.HandleStreams(h.handleStreamSuspension) case misbehaved: go t.HandleStreams(h.handleStreamMisbehave) default: go t.HandleStreams(h.handleStream) } } }
func main() { var ( debugListenAddr = flag.String("debug-listen-addr", "127.0.0.1:7801", "HTTP listen address.") listenAddr = flag.String("listen-addr", "127.0.0.1:7800", "HTTP listen address.") tlsCert = flag.String("tls-cert", withConfigDir("cert.pem"), "TLS server certificate.") tlsKey = flag.String("tls-key", withConfigDir("key.pem"), "TLS server key.") jwtPrivateKey = flag.String("jwt-private-key", withConfigDir("jwt-key.pem"), "The RSA private key to use for signing JWTs") ) flag.Parse() var err error log.Println("Auth service starting...") for { _, err := os.Open("/var/lib/auth.db") if !os.IsNotExist(err) { break } log.Println("missing auth database, retrying in 5 secs.") time.Sleep(5 * time.Second) } boltdb, err = bolt.Open("/var/lib/auth.db", 0600, nil) if err != nil { log.Fatal(err) } ta, err := credentials.NewServerTLSFromFile(*tlsCert, *tlsKey) if err != nil { log.Fatal(err) } gs := grpc.NewServer(grpc.Creds(ta)) as, err := NewAuthServer(*jwtPrivateKey) if err != nil { log.Fatal(err) } pb.RegisterAuthServer(gs, as) hs := health.NewHealthServer() hs.SetServingStatus("grpc.health.v1.authservice", 1) healthpb.RegisterHealthServer(gs, hs) ln, err := net.Listen("tcp", *listenAddr) if err != nil { log.Fatal(err) } go gs.Serve(ln) trace.AuthRequest = func(req *http.Request) (any, sensitive bool) { return true, true } log.Println("Auth service started successfully.") log.Fatal(http.ListenAndServe(*debugListenAddr, nil)) }
// Test the invocation of a transaction. func TestExecuteInvokeTransaction(t *testing.T) { 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 { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) viper.Set("peer.fileSystemPath", "/var/openchain/test/tmpdb") //use a different address than what we usually use for "peer" //we override the peerAddress set in chaincode_support.go peerAddress := "0.0.0.0:40303" lis, err := net.Listen("tcp", peerAddress) if err != nil { t.Fail() t.Logf("Error starting peer listener %s", err) return } getPeerEndpoint := func() (*pb.PeerEndpoint, error) { return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil)) go grpcServer.Serve(lis) var ctxt = context.Background() url := "github.com/openblockchain/obc-peer/openchain/example/chaincode/chaincode_example02" //url := "https://github.com/prjayach/chaincode_examples/chaincode_example02" chaincodeID := &pb.ChaincodeID{Path: url} args := []string{"a", "b", "10"} err = invokeExample02Transaction(ctxt, chaincodeID, args) if err != nil { t.Fail() t.Logf("Error invoking transaction: %s", err) } else { fmt.Printf("Invoke test passed\n") t.Logf("Invoke test passed") } GetChain(DefaultChain).stopChaincode(ctxt, chaincodeID) closeListenerAndSleep(lis) }
// Test deploy of a transaction. func TestExecuteDeployTransaction(t *testing.T) { 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 { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) viper.Set("peer.fileSystemPath", "/var/openchain/test/tmpdb") //lis, err := net.Listen("tcp", viper.GetString("peer.address")) //use a different address than what we usually use for "peer" //we override the peerAddress set in chaincode_support.go peerAddress := "0.0.0.0:40303" lis, err := net.Listen("tcp", peerAddress) if err != nil { t.Fail() t.Logf("Error starting peer listener %s", err) return } getPeerEndpoint := func() (*pb.PeerEndpoint, error) { return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil)) go grpcServer.Serve(lis) var ctxt = context.Background() url := "github.com/openblockchain/obc-peer/openchain/example/chaincode/chaincode_example01" f := "init" args := []string{"a", "100", "b", "200"} spec := &pb.ChaincodeSpec{Type: 1, ChaincodeID: &pb.ChaincodeID{Path: url}, CtorMsg: &pb.ChaincodeInput{Function: f, Args: args}} _, err = deploy(ctxt, spec) chaincodeID := spec.ChaincodeID.Name if err != nil { GetChain(DefaultChain).stopChaincode(ctxt, spec.ChaincodeID) closeListenerAndSleep(lis) t.Fail() t.Logf("Error deploying <%s>: %s", chaincodeID, err) return } GetChain(DefaultChain).stopChaincode(ctxt, spec.ChaincodeID) closeListenerAndSleep(lis) }
func setUp(hs *health.HealthServer, maxStream uint32, ua string, e env) (s *grpc.Server, cc *grpc.ClientConn) { sopts := []grpc.ServerOption{grpc.MaxConcurrentStreams(maxStream)} la := ":0" switch e.network { case "unix": la = "/tmp/testsock" + fmt.Sprintf("%d", time.Now()) syscall.Unlink(la) } lis, err := net.Listen(e.network, la) if err != nil { grpclog.Fatalf("Failed to listen: %v", err) } if e.security == "tls" { creds, err := credentials.NewServerTLSFromFile(tlsDir+"server1.pem", tlsDir+"server1.key") if err != nil { grpclog.Fatalf("Failed to generate credentials %v", err) } sopts = append(sopts, grpc.Creds(creds)) } s = grpc.NewServer(sopts...) if hs != nil { healthpb.RegisterHealthCheckServer(s, hs) } testpb.RegisterTestServiceServer(s, &testServer{}) go s.Serve(lis) addr := la switch e.network { case "unix": default: _, port, err := net.SplitHostPort(lis.Addr().String()) if err != nil { grpclog.Fatalf("Failed to parse listener address: %v", err) } addr = "localhost:" + port } if e.security == "tls" { creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { grpclog.Fatalf("Failed to create credentials %v", err) } cc, err = grpc.Dial(addr, grpc.WithTransportCredentials(creds), grpc.WithDialer(e.dialer), grpc.WithUserAgent(ua)) } else { cc, err = grpc.Dial(addr, grpc.WithDialer(e.dialer), grpc.WithUserAgent(ua)) } if err != nil { grpclog.Fatalf("Dial(%q) = %v", addr, err) } return }
// Start starts the ECA. // func (eca *ECA) Start(wg *sync.WaitGroup) { var opts []grpc.ServerOption if viper.GetString("eca.tls.certfile") != "" { creds, err := credentials.NewServerTLSFromFile(viper.GetString("eca.tls.certfile"), viper.GetString("eca.tls.keyfile")) if err != nil { Panic.Panicln(err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } wg.Add(2) go eca.startECAP(wg, opts) go eca.startECAA(wg, opts) Info.Println("ECA started.") }
func TestGenesis(t *testing.T) { //use a different address than what we usually use for "peer" //we override the peerAddress set in chaincode_support.go peerAddress := "0.0.0.0:50303" lis, err := net.Listen("tcp", peerAddress) if err != nil { t.Fail() t.Logf("Error starting peer listener %s", err) return } 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 { grpclog.Fatalf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer := grpc.NewServer(opts...) getPeerEndpoint := func() (*protos.PeerEndpoint, error) { return &protos.PeerEndpoint{ID: &protos.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(30000) * time.Millisecond protos.RegisterChaincodeSupportServer(grpcServer, chaincode.NewChaincodeSupport(chaincode.DefaultChain, getPeerEndpoint, false, ccStartupTimeout, nil)) go grpcServer.Serve(lis) ledger := ledger.InitTestLedger(t) if ledger.GetBlockchainSize() != 0 { t.Fatalf("Expected blockchain size of 0, but got %d", ledger.GetBlockchainSize()) } makeGenesisErr := MakeGenesis() if makeGenesisErr != nil { t.Fatalf("Error creating genesis block, %s", makeGenesisErr) } if ledger.GetBlockchainSize() != 1 { t.Fatalf("Expected blockchain size of 1, but got %d", ledger.GetBlockchainSize()) } }
func main() { viper.AutomaticEnv() viper.SetConfigName("obcca") viper.SetConfigType("yaml") viper.AddConfigPath("./") err := viper.ReadInConfig() if err != nil { panic(err) } obcca.LogInit(ioutil.Discard, os.Stdout, os.Stdout, os.Stderr, os.Stdout) obcca.Info.Println("CA Server (" + viper.GetString("server.version") + ")") eca := obcca.NewECA() defer eca.Close() tca := obcca.NewTCA(eca) defer tca.Close() tlsca := obcca.NewTLSCA(eca) defer tlsca.Close() var opts []grpc.ServerOption if viper.GetString("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) sock, err := net.Listen("tcp", viper.GetString("server.port")) if err != nil { panic(err) } srv.Serve(sock) sock.Close() }
func setUp(maxStream uint32, e env) (s *grpc.Server, cc *grpc.ClientConn) { s = grpc.NewServer(grpc.MaxConcurrentStreams(maxStream)) la := ":0" switch e.network { case "unix": la = "/tmp/testsock" + fmt.Sprintf("%p", s) syscall.Unlink(la) } lis, err := net.Listen(e.network, la) if err != nil { log.Fatalf("Failed to listen: %v", err) } testpb.RegisterTestServiceServer(s, &testServer{}) if e.security == "tls" { creds, err := credentials.NewServerTLSFromFile(tlsDir+"server1.pem", tlsDir+"server1.key") if err != nil { log.Fatalf("Failed to generate credentials %v", err) } go s.Serve(creds.NewListener(lis)) } else { go s.Serve(lis) } addr := la switch e.network { case "unix": default: _, port, err := net.SplitHostPort(lis.Addr().String()) if err != nil { log.Fatalf("Failed to parse listener address: %v", err) } addr = "localhost:" + port } if e.security == "tls" { creds, err := credentials.NewClientTLSFromFile(tlsDir+"ca.pem", "x.test.youtube.com") if err != nil { log.Fatalf("Failed to create credentials %v", err) } cc, err = grpc.Dial(addr, grpc.WithTransportCredentials(creds), grpc.WithDialer(e.dialer)) } else { cc, err = grpc.Dial(addr, grpc.WithDialer(e.dialer)) } if err != nil { log.Fatalf("Dial(%q) = %v", addr, err) } return }
//initialize peer and start up. If security==enabled, login as vp func initPeer(chainIDs ...string) (net.Listener, error) { //start clean finitPeer(nil, chainIDs...) peer.MockInitialize() 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...) 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) } getPeerEndpoint := func() (*pb.PeerEndpoint, error) { return &pb.PeerEndpoint{ID: &pb.PeerID{Name: "testpeer"}, Address: peerAddress}, nil } ccStartupTimeout := time.Duration(chaincodeStartupTimeoutDefault) * time.Millisecond pb.RegisterChaincodeSupportServer(grpcServer, NewChaincodeSupport(getPeerEndpoint, false, ccStartupTimeout)) RegisterSysCCs() for _, id := range chainIDs { if err = peer.MockCreateChain(id); err != nil { closeListenerAndSleep(lis) return nil, err } DeploySysCCs(id) } go grpcServer.Serve(lis) return lis, nil }