// startOfValidatedChainForLeaf returns the earliest revision in the
// chain leading up to `leafRev` that's been validated so far.  If no
// validations have occurred yet, it returns `leafRev`.
176592
func (md *MDOpsStandard) startOfValidatedChainForLeaf(
	tlfID tlf.ID, leafRev kbfsmd.Revision) kbfsmd.Revision {
	md.lock.Lock()
	defer md.lock.Unlock()
	revs, ok := md.leafChainsValidated[tlfID]
	if !ok {
		return leafRev
	}
	min, ok := revs[leafRev]
	if !ok {
		return leafRev
	}
	return min
}
1139637
func (f *lightFetcher) lastTrustedTreeNode(p *peer) (*types.Header, []common.Hash) {
	unapprovedHashes := make([]common.Hash, 0)
	current := f.chain.CurrentHeader()

	if f.lastTrustedHeader == nil {
		return current, unapprovedHashes
	}

	canonical := f.chain.CurrentHeader()
	if canonical.Number.Uint64() > f.lastTrustedHeader.Number.Uint64() {
		canonical = f.chain.GetHeaderByNumber(f.lastTrustedHeader.Number.Uint64())
	}
	commonAncestor := rawdb.FindCommonAncestor(f.pm.chainDb, canonical, f.lastTrustedHeader)
	if commonAncestor == nil {
		log.Error("Common ancestor of last trusted header and canonical header is nil", "canonical hash", canonical.Hash(), "trusted hash", f.lastTrustedHeader.Hash())
		return current, unapprovedHashes
	}

	for current.Hash() == commonAncestor.Hash() {
		if f.isTrustedHash(current.Hash()) {
			break
		}
		unapprovedHashes = append(unapprovedHashes, current.Hash())
		current = f.chain.GetHeader(current.ParentHash, current.Number.Uint64()-1)
	}
	return current, unapprovedHashes
}
129730
func (lscc *LifeCycleSysCC) isValidChaincodeName(chaincodeName string) error {
	if chaincodeName == "" {
		return EmptyChaincodeNameErr("")
	}

	if !isValidCCNameOrVersion(chaincodeName, allowedChaincodeName) {
		return InvalidChaincodeNameErr(chaincodeName)
	}

	return nil
}
72382
func (a *Account) MaxTotalLeafNodesReached() bool {
	a.mu.RLock()
	mtc := a.maxTotalLeafNodesReached()
	a.mu.RUnlock()
	return mtc
}
797926
func verifyChain(tlsCfg *tls.Config, rawCerts [][]byte, client bool) (*x509.Certificate, error) {

	// Fetch leaf and intermediates. This is based on code form tls handshake.
	if len(rawCerts) < 1 {
		return nil, errors.New("tls: no certificates from peer")
	}
	certs := make([]*x509.Certificate, len(rawCerts))
	for i, asn1Data := range rawCerts {
		cert, err := x509.ParseCertificate(asn1Data)
		if err != nil {
			return nil, errors.New("tls: failed to parse certificate from peer: " + err.Error())
		}
		certs[i] = cert
	}

	cas := tlsCfg.RootCAs
	if client {
		cas = tlsCfg.ClientCAs
	}

	opts := x509.VerifyOptions{
		Roots:         cas,
		Intermediates: x509.NewCertPool(),
	}
	if !client {
		// Server side only sets KeyUsages in tls. This defaults to ServerAuth in
		// x509 lib. See
		// https://github.com/golang/go/blob/ee7dd810f9ca4e63ecfc1d3044869591783b8b74/src/crypto/x509/verify.go#L866-L868
		opts.KeyUsages = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
	}

	// All but the first cert are intermediates
	for _, cert := range certs[1:] {
		opts.Intermediates.AddCert(cert)
	}
	_, err := certs[0].Verify(opts)
	return certs[0], err
}
704879
func isValidRootStructure(r Root) error {
	expectedType := TUFTypes[CanonicalRootRole]
	if r.Type != expectedType {
		return ErrInvalidMetadata{
			role: CanonicalRootRole, msg: fmt.Sprintf("expected type %s, not %s", expectedType, r.Type)}
	}

	if r.Version < 1 {
		return ErrInvalidMetadata{
			role: CanonicalRootRole, msg: "version cannot be less than 1"}
	}

	// all the base roles MUST appear in the root.json - other roles are allowed,
	// but other than the mirror role (not currently supported) are out of spec
	for _, roleName := range BaseRoles {
		roleObj, ok := r.Roles[roleName]
		if !ok || roleObj == nil {
			return ErrInvalidMetadata{
				role: CanonicalRootRole, msg: fmt.Sprintf("missing %s role specification", roleName)}
		}
		if err := isValidRootRoleStructure(CanonicalRootRole, roleName, *roleObj, r.Keys); err != nil {
			return err
		}
	}
	return nil
}
765422
func validRootIntCerts(allIntCerts map[string][]*x509.Certificate) map[string][]*x509.Certificate {
	validIntCerts := make(map[string][]*x509.Certificate)

	// Go through every leaf cert ID, and build its valid intermediate certificate list
	for leafID, intCertList := range allIntCerts {
		for _, intCert := range intCertList {
			if err := utils.ValidateCertificate(intCert, true); err != nil {
				continue
			}
			validIntCerts[leafID] = append(validIntCerts[leafID], intCert)
		}

	}
	return validIntCerts
}
49428
func (c *CfFilteredChainView) Start() error {
	// Already started?
	if atomic.AddInt32(&c.started, 1) != 1 {
		return nil
	}

	log.Infof("FilteredChainView starting")

	// First, we'll obtain the latest block height of the p2p node. We'll
	// start the auto-rescan from this point. Once a caller actually wishes
	// to register a chain view, the rescan state will be rewound
	// accordingly.
	startingPoint, err := c.p2pNode.BestBlock()
	if err != nil {
		return err
	}

	// Next, we'll create our set of rescan options. Currently it's
	// required that an user MUST set a addr/outpoint/txid when creating a
	// rescan. To get around this, we'll add a "zero" outpoint, that won't
	// actually be matched.
	var zeroPoint neutrino.InputWithScript
	rescanOptions := []neutrino.RescanOption{
		neutrino.StartBlock(startingPoint),
		neutrino.QuitChan(c.quit),
		neutrino.NotificationHandlers(
			rpcclient.NotificationHandlers{
				OnFilteredBlockConnected:    c.onFilteredBlockConnected,
				OnFilteredBlockDisconnected: c.onFilteredBlockDisconnected,
			},
		),
		neutrino.WatchInputs(zeroPoint),
	}

	// Finally, we'll create our rescan struct, start it, and launch all
	// the goroutines we need to operate this FilteredChainView instance.
	c.chainView = neutrino.NewRescan(
		&neutrino.RescanChainSource{
			ChainService: c.p2pNode,
		},
		rescanOptions...,
	)
	c.rescanErrChan = c.chainView.Start()

	c.blockQueue.Start()

	c.wg.Add(1)
	go c.chainFilterer()

	return nil
}
343480
func LoadValidatorRing(version int64, ringSize int,
	getImmutable func(version int64) (*storage.ImmutableForest, error)) (*validator.Ring, error) {

	// In this method we have to page through previous version of the tree in order to reconstruct the in-memory
	// ring structure. The corner cases are a little subtle but printing the buckets helps

	// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred
	// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to
	// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state
	// correct

	startVersion := version - int64(ringSize)
	if startVersion < 1 {
		// The ring will not be fully populated
		startVersion = 1
	}
	var err error
	// Read state to pull immutable forests from
	rs := &ReadState{}
	// Start with an empty ring - we want the initial bucket to have no cumulative power
	ring := validator.NewRing(nil, ringSize)
	// Load the IAVL state
	rs.Forest, err = getImmutable(startVersion)
	// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta
	err = validator.Write(ring, rs)
	if err != nil {
		return nil, err
	}
	// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]
	// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring
	_, _, err = ring.Rotate()
	if err != nil {
		return nil, err
	}

	// Rebuild validator Ring
	for v := startVersion + 1; v <= version; v++ {
		// Update IAVL read state to version of interest
		rs.Forest, err = getImmutable(v)
		if err != nil {
			return nil, err
		}
		// Calculate the difference between the rings current cum and what is in state at this version
		diff, err := validator.Diff(ring.CurrentSet(), rs)
		if err != nil {
			return nil, err
		}
		// Write that diff into the ring (just like it was when it was originally written to setPower)
		err = validator.Write(ring, diff)
		if err != nil {
			return nil, err
		}
		// Rotate just like it was on the original commit
		_, _, err = ring.Rotate()
		if err != nil {
			return nil, err
		}
	}
	// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading
	// This is the head index we would have had if we had started from version 1 like the chain did
	ring.ReIndex(int(version % int64(ringSize)))
	return ring, err
}
168924
func (v *VsccValidatorImpl) GetInfoForValidate(chdr *common.ChannelHeader, ccID string) (*sysccprovider.ChaincodeInstance, *sysccprovider.ChaincodeInstance, []byte, error) {
	cc := &sysccprovider.ChaincodeInstance{
		ChainID:          chdr.ChannelId,
		ChaincodeName:    ccID,
		ChaincodeVersion: coreUtil.GetSysCCVersion(),
	}
	vscc := &sysccprovider.ChaincodeInstance{
		ChainID:          chdr.ChannelId,
		ChaincodeName:    "vscc",                     // default vscc for system chaincodes
		ChaincodeVersion: coreUtil.GetSysCCVersion(), // Get vscc version
	}
	var policy []byte
	var err error
	if !v.sccprovider.IsSysCC(ccID) {
		// when we are validating a chaincode that is not a
		// system CC, we need to ask the CC to give us the name
		// of VSCC and of the policy that should be used

		// obtain name of the VSCC and the policy
		cd, err := v.getCDataForCC(chdr.ChannelId, ccID)
		if err != nil {
			msg := fmt.Sprintf("Unable to get chaincode data from ledger for txid %s, due to %s", chdr.TxId, err)
			logger.Errorf(msg)
			return nil, nil, nil, err
		}
		cc.ChaincodeName = cd.CCName()
		cc.ChaincodeVersion = cd.CCVersion()
		vscc.ChaincodeName, policy = cd.Validation()
	} else {
		// when we are validating a system CC, we use the default
		// VSCC and a default policy that requires one signature
		// from any of the members of the channel
		p := cauthdsl.SignedByAnyMember(v.support.GetMSPIDs(chdr.ChannelId))
		policy, err = utils.Marshal(p)
		if err != nil {
			return nil, nil, nil, err
		}
	}

	return cc, vscc, policy, nil
}
817160
func (fd *FileData) ReadyNonLeafBlocksInCopy(ctx context.Context,
	bcache BlockCache, rp ReadyProvider, bps BlockPutState,
	topBlock *FileBlock) ([]BlockInfo, error) {
	if !topBlock.IsInd {
		return nil, nil
	}

	// For indirect files, get all the paths to leaf blocks.  Note
	// that because topBlock is a deepCopy, all of the blocks are also
	// deepCopys and thus are modifiable.
	pfr, err := fd.tree.getIndirectBlocksForOffsetRange(
		ctx, topBlock, Int64Offset(0), nil)
	if err != nil {
		return nil, err
	}
	if len(pfr) == 0 {
		return nil, fmt.Errorf(
			"Indirect file %v had no indirect blocks", fd.rootBlockPointer())
	}

	newInfos, err := fd.tree.readyHelper(
		ctx, fd.tree.file.Tlf, bcache, rp, bps, pfr, nil)
	if err != nil {
		return nil, err
	}

	blockInfos := make([]BlockInfo, 0, len(newInfos))
	for newInfo := range newInfos {
		blockInfos = append(blockInfos, newInfo)
	}
	return blockInfos, nil
}
788194
func validateAffinity(affinity *core.Affinity, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	if affinity != nil {
		if affinity.NodeAffinity != nil {
			allErrs = append(allErrs, validateNodeAffinity(affinity.NodeAffinity, fldPath.Child("nodeAffinity"))...)
		}
		if affinity.PodAffinity != nil {
			allErrs = append(allErrs, validatePodAffinity(affinity.PodAffinity, fldPath.Child("podAffinity"))...)
		}
		if affinity.PodAntiAffinity != nil {
			allErrs = append(allErrs, validatePodAntiAffinity(affinity.PodAntiAffinity, fldPath.Child("podAntiAffinity"))...)
		}
	}

	return allErrs
}
769224
func ValidateNodeFieldSelectorRequirement(req core.NodeSelectorRequirement, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	switch req.Operator {
	case core.NodeSelectorOpIn, core.NodeSelectorOpNotIn:
		if len(req.Values) != 1 {
			allErrs = append(allErrs, field.Required(fldPath.Child("values"),
				"must be only one value when `operator` is 'In' or 'NotIn' for node field selector"))
		}
	default:
		allErrs = append(allErrs, field.Invalid(fldPath.Child("operator"), req.Operator, "not a valid selector operator"))
	}

	if vf, found := nodeFieldSelectorValidators[req.Key]; !found {
		allErrs = append(allErrs, field.Invalid(fldPath.Child("key"), req.Key, "not a valid field selector key"))
	} else {
		for i, v := range req.Values {
			for _, msg := range vf(v, false) {
				allErrs = append(allErrs, field.Invalid(fldPath.Child("values").Index(i), v, msg))
			}
		}
	}

	return allErrs
}
23895
func (p *Prog) findChildLeaf() string {
	for {
		if len(p.Child) == 0 {
			return p.Path
		}
		p = p.Child[p.keys()[0]]
	}
}
439753
func (ccpack *CDSPackage) InitFromPath(ccname string, ccversion string, path string) ([]byte, *pb.ChaincodeDeploymentSpec, error) {
	//incase ccpack is reused
	ccpack.reset()

	buf, err := GetChaincodePackageFromPath(ccname, ccversion, path)
	if err != nil {
		return nil, nil, err
	}

	ccdata, err := ccpack.InitFromBuffer(buf)
	if err != nil {
		return nil, nil, err
	}

	if err := ccpack.ValidateCC(ccdata); err != nil {
		return nil, nil, err
	}

	return ccpack.buf, ccpack.depSpec, nil
}
594808
func completeLeafValue(returnType Leaf, result interface{}) interface{} {
	serializedResult := returnType.Serialize(result)
	if isNullish(serializedResult) {
		return nil
	}
	return serializedResult
}
412582
func validateChaincodeProposalMessage(prop *pb.Proposal, hdr *common.Header) (*pb.ChaincodeHeaderExtension, error) {
	if prop == nil || hdr == nil {
		return nil, errors.New("nil arguments")
	}

	putilsLogger.Debugf("validateChaincodeProposalMessage starts for proposal %p, header %p", prop, hdr)

	// 4) based on the header type (assuming it's CHAINCODE), look at the extensions
	chaincodeHdrExt, err := utils.GetChaincodeHeaderExtension(hdr)
	if err != nil {
		return nil, errors.New("invalid header extension for type CHAINCODE")
	}

	if chaincodeHdrExt.ChaincodeId == nil {
		return nil, errors.New("ChaincodeHeaderExtension.ChaincodeId is nil")
	}

	putilsLogger.Debugf("validateChaincodeProposalMessage info: header extension references chaincode %s", chaincodeHdrExt.ChaincodeId)

	//    - ensure that the chaincodeID is correct (?)
	// TODO: should we even do this? If so, using which interface?

	//    - ensure that the visibility field has some value we understand
	// currently the fabric only supports full visibility: this means that
	// there are no restrictions on which parts of the proposal payload will
	// be visible in the final transaction; this default approach requires
	// no additional instructions in the PayloadVisibility field which is
	// therefore expected to be nil; however the fabric may be extended to
	// encode more elaborate visibility mechanisms that shall be encoded in
	// this field (and handled appropriately by the peer)
	if chaincodeHdrExt.PayloadVisibility != nil {
		return nil, errors.New("invalid payload visibility field")
	}

	return chaincodeHdrExt, nil
}