// CreateTxtRules create receive rules for this PU based on the update of the policy.
185113
func (p *PUContext) CreateTxtRules(policyRules policy.TagSelectorList) {
	p.txt = p.createRuleDBs(policyRules)
}
115238
func (lc *LightningChannel) createCommitmentTx(c *commitment,
	filteredHTLCView *htlcView, keyRing *CommitmentKeyRing) error {

	ourBalance := c.ourBalance
	theirBalance := c.theirBalance

	numHTLCs := int64(0)
	for _, htlc := range filteredHTLCView.ourUpdates {
		if htlcIsDust(false, c.isOurs, c.feePerKw,
			htlc.Amount.ToSatoshis(), c.dustLimit) {

			continue
		}

		numHTLCs++
	}
	for _, htlc := range filteredHTLCView.theirUpdates {
		if htlcIsDust(true, c.isOurs, c.feePerKw,
			htlc.Amount.ToSatoshis(), c.dustLimit) {

			continue
		}

		numHTLCs++
	}

	// Next, we'll calculate the fee for the commitment transaction based
	// on its total weight. Once we have the total weight, we'll multiply
	// by the current fee-per-kw, then divide by 1000 to get the proper
	// fee.
	totalCommitWeight := input.CommitWeight + (input.HtlcWeight * numHTLCs)

	// With the weight known, we can now calculate the commitment fee,
	// ensuring that we account for any dust outputs trimmed above.
	commitFee := c.feePerKw.FeeForWeight(totalCommitWeight)
	commitFeeMSat := lnwire.NewMSatFromSatoshis(commitFee)

	// Currently, within the protocol, the initiator always pays the fees.
	// So we'll subtract the fee amount from the balance of the current
	// initiator. If the initiator is unable to pay the fee fully, then
	// their entire output is consumed.
	switch {
	case lc.channelState.IsInitiator && commitFee > ourBalance.ToSatoshis():
		ourBalance = 0

	case lc.channelState.IsInitiator:
		ourBalance -= commitFeeMSat

	case !lc.channelState.IsInitiator && commitFee > theirBalance.ToSatoshis():
		theirBalance = 0

	case !lc.channelState.IsInitiator:
		theirBalance -= commitFeeMSat
	}

	var (
		delay                      uint32
		delayBalance, p2wkhBalance btcutil.Amount
	)
	if c.isOurs {
		delay = uint32(lc.localChanCfg.CsvDelay)
		delayBalance = ourBalance.ToSatoshis()
		p2wkhBalance = theirBalance.ToSatoshis()
	} else {
		delay = uint32(lc.remoteChanCfg.CsvDelay)
		delayBalance = theirBalance.ToSatoshis()
		p2wkhBalance = ourBalance.ToSatoshis()
	}

	// Generate a new commitment transaction with all the latest
	// unsettled/un-timed out HTLCs.
	commitTx, err := CreateCommitTx(lc.fundingTxIn(), keyRing, delay,
		delayBalance, p2wkhBalance, c.dustLimit)
	if err != nil {
		return err
	}

	// We'll now add all the HTLC outputs to the commitment transaction.
	// Each output includes an off-chain 2-of-2 covenant clause, so we'll
	// need the objective local/remote keys for this particular commitment
	// as well.
	for _, htlc := range filteredHTLCView.ourUpdates {
		if htlcIsDust(false, c.isOurs, c.feePerKw,
			htlc.Amount.ToSatoshis(), c.dustLimit) {
			continue
		}

		err := lc.addHTLC(commitTx, c.isOurs, false, htlc, keyRing)
		if err != nil {
			return err
		}
	}
	for _, htlc := range filteredHTLCView.theirUpdates {
		if htlcIsDust(true, c.isOurs, c.feePerKw,
			htlc.Amount.ToSatoshis(), c.dustLimit) {
			continue
		}

		err := lc.addHTLC(commitTx, c.isOurs, true, htlc, keyRing)
		if err != nil {
			return err
		}
	}

	// Set the state hint of the commitment transaction to facilitate
	// quickly recovering the necessary penalty state in the case of an
	// uncooperative broadcast.
	err = SetStateNumHint(commitTx, c.height, lc.stateHintObfuscator)
	if err != nil {
		return err
	}

	// Sort the transactions according to the agreed upon canonical
	// ordering. This lets us skip sending the entire transaction over,
	// instead we'll just send signatures.
	txsort.InPlaceSort(commitTx)

	// Next, we'll ensure that we don't accidentally create a commitment
	// transaction which would be invalid by consensus.
	uTx := btcutil.NewTx(commitTx)
	if err := blockchain.CheckTransactionSanity(uTx); err != nil {
		return err
	}

	// Finally, we'll assert that were not attempting to draw more out of
	// the channel that was originally placed within it.
	var totalOut btcutil.Amount
	for _, txOut := range commitTx.TxOut {
		totalOut += btcutil.Amount(txOut.Value)
	}
	if totalOut > lc.channelState.Capacity {
		return fmt.Errorf("height=%v, for ChannelPoint(%v) attempts "+
			"to consume %v while channel capacity is %v",
			c.height, lc.channelState.FundingOutpoint,
			totalOut, lc.channelState.Capacity)
	}

	c.txn = commitTx
	c.fee = commitFee
	c.ourBalance = ourBalance
	c.theirBalance = theirBalance
	return nil
}
1064514
func applyRules(text string, rules []rule) string {
	for _, rule := range rules {
		text = rule.sub(text)
	}
	return text
}
675074
func (s *AutoScalingPolicy) SetRules(v []*ScalingRule) *AutoScalingPolicy {
	s.Rules = v
	return s
}
965624
func (qri *Map) SetRules(ruleSource string, newRules *Rules) error {
	if newRules == nil {
		newRules = New()
	}
	qri.mu.Lock()
	defer qri.mu.Unlock()
	if _, ok := qri.queryRulesMap[ruleSource]; ok {
		qri.queryRulesMap[ruleSource] = newRules.Copy()
		return nil
	}
	return errors.New("Rule source identifier " + ruleSource + " is not valid")
}
1149270
func (c *Client) CreateFirewallRule(p *CreateFirewallRuleParameter) (*FirewallRule, error) {
	obj, err := c.Request("createFirewallRule", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*FirewallRule), err
}
917690
func (p *PUContext) searchRules(
	policies *policies,
	tags *policy.TagStore,
	skipRejectPolicies bool,
) (report *policy.FlowPolicy, packet *policy.FlowPolicy) {

	var reportingAction *policy.FlowPolicy
	var packetAction *policy.FlowPolicy

	if !skipRejectPolicies {
		// Look for rejection rules
		observeIndex, observeAction := policies.observeRejectRules.Search(tags)
		if observeIndex >= 0 {
			reportingAction = observeAction.(*policy.FlowPolicy)
		}

		index, action := policies.rejectRules.Search(tags)
		if index >= 0 {
			packetAction = action.(*policy.FlowPolicy)
			if reportingAction == nil {
				reportingAction = packetAction
			}
			return reportingAction, packetAction
		}
	}

	if reportingAction == nil {
		// Look for allow rules
		observeIndex, observeAction := policies.observeAcceptRules.Search(tags)
		if observeIndex >= 0 {
			reportingAction = observeAction.(*policy.FlowPolicy)
		}
	}

	index, action := policies.acceptRules.Search(tags)
	if index >= 0 {
		packetAction = action.(*policy.FlowPolicy)
		// Look for encrypt rules
		encryptIndex, _ := policies.encryptRules.Search(tags)
		if encryptIndex >= 0 {
			// Do not overwrite the action for accept rules.
			finalAction := action.(*policy.FlowPolicy)
			packetAction = &policy.FlowPolicy{
				Action:    policy.Accept | policy.Encrypt,
				PolicyID:  finalAction.PolicyID,
				ServiceID: finalAction.ServiceID,
			}
		}
		if reportingAction == nil {
			reportingAction = packetAction
		}
		return reportingAction, packetAction
	}

	// Look for observe apply rules
	observeIndex, observeAction := policies.observeApplyRules.Search(tags)
	if observeIndex >= 0 {
		packetAction = observeAction.(*policy.FlowPolicy)
		if reportingAction == nil {
			reportingAction = packetAction
		}
		return reportingAction, packetAction
	}

	// Handle default if nothing provides to drop with no policyID.
	packetAction = &policy.FlowPolicy{
		Action:   policy.Reject,
		PolicyID: "default",
	}

	if reportingAction == nil {
		reportingAction = packetAction
	}

	return reportingAction, packetAction
}
446131
func (p *PoliciesClient) Create(ctx context.Context, policy *primitive.Policy) (*envelope.Policy, error) {

	ID, err := identity.NewMutable(policy)
	if err != nil {
		return nil, err
	}

	env := envelope.Policy{
		ID:      &ID,
		Version: 1,
		Body:    policy,
	}

	res := envelope.Policy{}
	err = p.client.RoundTrip(ctx, "POST", "/policies", nil, env, &res)
	return &res, err
}
216568
func (s *ReplicationConfiguration) SetRules(v []*ReplicationRule) *ReplicationConfiguration {
	s.Rules = v
	return s
}
517667
func (mcs *ConsenterSupport) CreateNextBlock(data []*cb.Envelope) *cb.Block {
	block := cb.NewBlock(0, nil)
	mtxs := make([][]byte, len(data))
	for i := range data {
		mtxs[i] = utils.MarshalOrPanic(data[i])
	}
	block.Data = &cb.BlockData{Data: mtxs}
	mcs.NextBlockVal = block
	return block
}
1306750
func (s *DataRetrievalPolicy) SetRules(v []*DataRetrievalRule) *DataRetrievalPolicy {
	s.Rules = v
	return s
}
703905
func (s *BucketLifecycleConfiguration) SetRules(v []*LifecycleRule) *BucketLifecycleConfiguration {
	s.Rules = v
	return s
}
842100
func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) {
	switch ld.Mode {
	case "block", "challenge", "js_challenge", "whitelist":
		break
	default:
		return nil, errors.New(`the User-Agent Block rule mode must be one of "block", "challenge", "js_challenge", "whitelist"`)
	}

	uri := "/zones/" + zoneID + "/firewall/ua_rules"
	res, err := api.makeRequest("POST", uri, ld)
	if err != nil {
		return nil, errors.Wrap(err, errMakeRequestError)
	}

	response := &UserAgentRuleResponse{}
	err = json.Unmarshal(res, &response)
	if err != nil {
		return nil, errors.Wrap(err, errUnmarshalError)
	}

	return response, nil
}
536723
func newTtlRule(nextAction string, args ...string) (Rule, error) {
	if len(args) < 2 {
		return nil, fmt.Errorf("too few (%d) arguments for a ttl rule", len(args))
	}
	var s string
	if len(args) == 2 {
		s = args[1]
	}
	if len(args) == 3 {
		s = args[2]
	}
	ttl, valid := isValidTtl(s)
	if valid == false {
		return nil, fmt.Errorf("invalid TTL '%s' for a ttl rule", s)
	}
	if len(args) == 3 {
		switch strings.ToLower(args[0]) {
		case ExactMatch:
			return &exactTtlRule{
				nextAction,
				plugin.Name(args[1]).Normalize(),
				ResponseRule{
					Active: true,
					Type:   "ttl",
					Ttl:    ttl,
				},
			}, nil
		case PrefixMatch:
			return &prefixTtlRule{
				nextAction,
				plugin.Name(args[1]).Normalize(),
				ResponseRule{
					Active: true,
					Type:   "ttl",
					Ttl:    ttl,
				},
			}, nil
		case SuffixMatch:
			return &suffixTtlRule{
				nextAction,
				plugin.Name(args[1]).Normalize(),
				ResponseRule{
					Active: true,
					Type:   "ttl",
					Ttl:    ttl,
				},
			}, nil
		case SubstringMatch:
			return &substringTtlRule{
				nextAction,
				plugin.Name(args[1]).Normalize(),
				ResponseRule{
					Active: true,
					Type:   "ttl",
					Ttl:    ttl,
				},
			}, nil
		case RegexMatch:
			regexPattern, err := regexp.Compile(args[1])
			if err != nil {
				return nil, fmt.Errorf("invalid regex pattern in a ttl rule: %s", args[1])
			}
			return &regexTtlRule{
				nextAction,
				regexPattern,
				ResponseRule{
					Active: true,
					Type:   "ttl",
					Ttl:    ttl,
				},
			}, nil
		default:
			return nil, fmt.Errorf("A ttl rule supports only exact, prefix, suffix, substring, and regex name matching")
		}
	}
	if len(args) > 3 {
		return nil, fmt.Errorf("many few arguments for a ttl rule")
	}
	return &exactTtlRule{
		nextAction,
		plugin.Name(args[0]).Normalize(),
		ResponseRule{
			Active: true,
			Type:   "ttl",
			Ttl:    ttl,
		},
	}, nil
}
734186
func (s *ServerSideEncryptionConfiguration) SetRules(v []*ServerSideEncryptionRule) *ServerSideEncryptionConfiguration {
	s.Rules = v
	return s
}
167864
func (g *Cloud) CreateAlphaRegionForwardingRule(rule *computealpha.ForwardingRule, region string) error {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newForwardingRuleMetricContextWithVersion("create", region, computeAlphaVersion)
	return mc.Observe(g.c.AlphaForwardingRules().Insert(ctx, meta.RegionalKey(rule.Name, region), rule))
}
1282082
func CreatePolicyAndToken(t testing.T, state StateStore, index uint64, name, rule string) *structs.ACLToken {
	CreatePolicy(t, state, index, name, rule)
	return CreateToken(t, state, index+1, []string{name})
}