// NewAESGCMBarrier is used to construct a new barrier that uses
// the provided physical backend for storage.
760789
func NewAESGCMBarrier(physical physical.Backend) (*AESGCMBarrier, error) {
	b := &AESGCMBarrier{
		backend:                  physical,
		sealed:                   true,
		cache:                    make(map[uint32]cipher.AEAD),
		currentAESGCMVersionByte: byte(AESGCMVersion2),
	}
	return b, nil
}
336874
func (b *AESGCMBarrier) aeadFromKey(key []byte) (cipher.AEAD, error) {
	// Create the AES cipher
	aesCipher, err := aes.NewCipher(key)
	if err != nil {
		return nil, errwrap.Wrapf("failed to create cipher: {{err}}", err)
	}

	// Create the GCM mode AEAD
	gcm, err := cipher.NewGCM(aesCipher)
	if err != nil {
		return nil, fmt.Errorf("failed to initialize GCM mode")
	}
	return gcm, nil
}
1351560
func NewBackend(c map[string]string, logger log.Logger) (physical.Backend, error) {
	logger.Debug("configuring backend")

	// Database name
	database := os.Getenv(envDatabase)
	if database == "" {
		database = c["database"]
	}
	if database == "" {
		return nil, errors.New("missing database name")
	}

	// Table name
	table := os.Getenv(envTable)
	if table == "" {
		table = c["table"]
	}
	if table == "" {
		table = defaultTable
	}

	// HA table name
	haTable := os.Getenv(envHATable)
	if haTable == "" {
		haTable = c["ha_table"]
	}
	if haTable == "" {
		haTable = table + defaultHASuffix
	}

	// HA configuration
	haEnabled := false
	haEnabledStr := os.Getenv(envHAEnabled)
	if haEnabledStr == "" {
		haEnabledStr = c["ha_enabled"]
	}
	if haEnabledStr != "" {
		var err error
		haEnabled, err = strconv.ParseBool(haEnabledStr)
		if err != nil {
			return nil, errwrap.Wrapf("failed to parse HA enabled: {{err}}", err)
		}
	}

	// Max parallel
	maxParallel, err := extractInt(c["max_parallel"])
	if err != nil {
		return nil, errwrap.Wrapf("failed to parse max_parallel: {{err}}", err)
	}

	logger.Debug("configuration",
		"database", database,
		"table", table,
		"haEnabled", haEnabled,
		"haTable", haTable,
		"maxParallel", maxParallel,
	)
	logger.Debug("creating client")

	ctx := context.Background()
	client, err := spanner.NewClient(ctx, database,
		option.WithUserAgent(useragent.String()),
	)
	if err != nil {
		return nil, errwrap.Wrapf("failed to create spanner client: {{err}}", err)
	}

	return &Backend{
		database:  database,
		table:     table,
		haEnabled: haEnabled,
		haTable:   haTable,

		client:     client,
		permitPool: physical.NewPermitPool(maxParallel),
		logger:     logger,
	}, nil
}
27814
func NewMsgAlert(serializedPayload []byte, signature []byte) *MsgAlert {
	return &MsgAlert{
		SerializedPayload: serializedPayload,
		Signature:         signature,
		Payload:           nil,
	}
}
912725
func NewOAEPParams(hashAlg, mgf, sourceType uint, sourceData []byte) *OAEPParams {
	return &OAEPParams{
		HashAlg:    hashAlg,
		MGF:        mgf,
		SourceType: sourceType,
		SourceData: sourceData,
	}
}
1220161
func newContainerManager(docker builder.ExecBackend) *containerManager {
	return &containerManager{
		backend:       docker,
		tmpContainers: make(map[string]struct{}),
	}
}
739808
func (g *S3) NewGatewayLayer(creds auth.Credentials) (minio.ObjectLayer, error) {
	// creds are ignored here, since S3 gateway implements chaining
	// all credentials.
	clnt, err := newS3(g.host)
	if err != nil {
		return nil, err
	}

	s := s3Objects{
		Client: clnt,
	}
	// Enables single encyption of KMS is configured.
	if minio.GlobalKMS != nil {
		encS := s3EncObjects{s}

		// Start stale enc multipart uploads cleanup routine.
		go encS.cleanupStaleEncMultipartUploads(context.Background(),
			minio.GlobalMultipartCleanupInterval, minio.GlobalMultipartExpiry, minio.GlobalServiceDoneCh)

		return &encS, nil
	}
	return &s, nil
}
1322579
func (b *AESGCMBarrier) encrypt(path string, term uint32, gcm cipher.AEAD, plain []byte) ([]byte, error) {
	// Allocate the output buffer with room for tern, version byte,
	// nonce, GCM tag and the plaintext
	capacity := termSize + 1 + gcm.NonceSize() + gcm.Overhead() + len(plain)
	size := termSize + 1 + gcm.NonceSize()
	out := make([]byte, size, capacity)

	// Set the key term
	binary.BigEndian.PutUint32(out[:4], term)

	// Set the version byte
	out[4] = b.currentAESGCMVersionByte

	// Generate a random nonce
	nonce := out[5 : 5+gcm.NonceSize()]
	n, err := rand.Read(nonce)
	if err != nil {
		return nil, err
	}
	if n != len(nonce) {
		return nil, errors.New("unable to read enough random bytes to fill gcm nonce")
	}

	// Seal the output
	switch b.currentAESGCMVersionByte {
	case AESGCMVersion1:
		out = gcm.Seal(out, nonce, plain, nil)
	case AESGCMVersion2:
		aad := []byte(nil)
		if path != "" {
			aad = []byte(path)
		}
		out = gcm.Seal(out, nonce, plain, aad)
	default:
		panic("Unknown AESGCM version")
	}

	return out, nil
}
55361
func (s *UCSService) NewAddUcsManagerParams(password string, url string, username string, zoneid string) *AddUcsManagerParams {
	p := &AddUcsManagerParams{}
	p.p = make(map[string]interface{})
	p.p["password"] = password
	p.p["url"] = url
	p.p["username"] = username
	p.p["zoneid"] = zoneid
	return p
}
836506
func NewNSGateway() *NSGateway {

	return &NSGateway{
		TCPMSSEnabled:                    false,
		TCPMaximumSegmentSize:            1330,
		ZFBMatchAttribute:                "NONE",
		TPMStatus:                        "UNKNOWN",
		SSHService:                       "INHERITED",
		LastConfigurationReloadTimestamp: -1,
		GatewayConnected:                 false,
		NetworkAcceleration:              "NONE",
		InheritedSSHServiceState:         "ENABLED",
		ConfigurationReloadState:         "UNKNOWN",
		ConfigurationStatus:              "UNKNOWN",
		ControlTrafficCOSValue:           7,
		ControlTrafficDSCPValue:          56,
	}
}
516409
func NewValidationBarrier(numActiveReqs int,
	quitChan chan struct{}) *ValidationBarrier {

	v := &ValidationBarrier{
		chanAnnFinSignal:     make(map[lnwire.ShortChannelID]chan struct{}),
		chanEdgeDependencies: make(map[lnwire.ShortChannelID]chan struct{}),
		nodeAnnDependencies:  make(map[route.Vertex]chan struct{}),
		quit:                 quitChan,
	}

	// We'll first initialize a set of sempahores to limit our concurrency
	// when validating incoming requests in parallel.
	v.validationSemaphore = make(chan struct{}, numActiveReqs)
	for i := 0; i < numActiveReqs; i++ {
		v.validationSemaphore <- struct{}{}
	}

	return v
}
823093
func newGateway() *gateway {
	return &gateway{
		tk:     timekeeper.RealTime{},
		logger: log.DefaultLogger.CreateChild(),
		stdout: os.Stdout,
		debugContext: web.HeaderCtxFlag{
			HeaderName: "X-Debug-Id",
		},
		debugSink: dpsink.ItemFlagger{
			EventMetaName:       "dbg_events",
			MetricDimensionName: "sf_metric",
		},
		setupDoneSignal: make(chan struct{}),
		signalChan:      make(chan os.Signal, 1),
	}
}
941268
func NewRouteAppenderAggregator(ctx context.Context, chainBuilder chainBuilder, conf static.Configuration, entryPointName string, currentConfiguration *safe.Safe) *RouteAppenderAggregator {
	aggregator := &RouteAppenderAggregator{}

	if conf.Providers != nil && conf.Providers.Rest != nil {
		aggregator.AddAppender(conf.Providers.Rest)
	}

	if conf.API != nil && conf.API.EntryPoint == entryPointName {
		chain := chainBuilder.BuildChain(ctx, conf.API.Middlewares)
		aggregator.AddAppender(&WithMiddleware{
			appender: api.Handler{
				EntryPoint:            conf.API.EntryPoint,
				Dashboard:             conf.API.Dashboard,
				Statistics:            conf.API.Statistics,
				DashboardAssets:       conf.API.DashboardAssets,
				CurrentConfigurations: currentConfiguration,
				Debug:                 conf.Global.Debug,
			},
			routerMiddlewares: chain,
		})

	}

	if conf.Ping != nil && conf.Ping.EntryPoint == entryPointName {
		chain := chainBuilder.BuildChain(ctx, conf.Ping.Middlewares)
		aggregator.AddAppender(&WithMiddleware{
			appender:          conf.Ping,
			routerMiddlewares: chain,
		})
	}

	if conf.Metrics != nil && conf.Metrics.Prometheus != nil && conf.Metrics.Prometheus.EntryPoint == entryPointName {
		chain := chainBuilder.BuildChain(ctx, conf.Metrics.Prometheus.Middlewares)
		aggregator.AddAppender(&WithMiddleware{
			appender:          metrics.PrometheusHandler{},
			routerMiddlewares: chain,
		})
	}

	return aggregator
}
1317719
func newRekeyAEAD(key []byte) (*rekeyAEAD, error) {
	k := len(key)
	if k != kdfKeyLen+nonceLen {
		return nil, KeySizeError(k)
	}
	return &rekeyAEAD{
		kdfKey:     key[:kdfKeyLen],
		kdfCounter: make([]byte, kdfCounterLen),
		nonceMask:  key[kdfKeyLen:],
		nonceBuf:   make([]byte, nonceLen),
		gcmAEAD:    nil,
	}, nil
}
1138034
func NewConfigMapPayload(cm *apiv1.ConfigMap) (Payload, error) {
	if cm == nil {
		return nil, fmt.Errorf("ConfigMap must be non-nil")
	} else if cm.ObjectMeta.UID == "" {
		return nil, fmt.Errorf("ConfigMap must have a non-empty UID")
	} else if cm.ObjectMeta.ResourceVersion == "" {
		return nil, fmt.Errorf("ConfigMap must have a non-empty ResourceVersion")
	}

	return &configMapPayload{cm}, nil
}
189983
func NewPINGRESPFromBytes(fixedHeader FixedHeader, remaining []byte) (Packet, error) {
	// Validate the byte data.
	if err := validatePINGRESPBytes(fixedHeader, remaining); err != nil {
		return nil, err
	}

	// Create a PINGRESP Packet.
	p := &PINGRESP{}

	// Set the fixed header to the Packet.
	p.fixedHeader = fixedHeader

	// Return the Packet.
	return p, nil
}
855497
func NewModelManagerBackend(m *state.Model, pool *state.StatePool) ModelManagerBackend {
	return modelManagerStateShim{m.State(), m, pool}
}