// GetProposalResponse given proposal in bytes
187812
func GetProposalResponse(prBytes []byte) (*peer.ProposalResponse, error) {
	proposalResponse := &peer.ProposalResponse{}
	err := proto.Unmarshal(prBytes, proposalResponse)
	return proposalResponse, errors.Wrap(err, "error unmarshaling ProposalResponse")
}
878508
func (r *RiskServiceCalculationResult) GetProbabilityDecimalOrScore() *float64 {
	if r.ProbabilityDecimal != nil {
		return r.ProbabilityDecimal
	} else if r.Score != nil {
		f := float64(*r.Score)
		return &f
	}
	return nil
}
226074
func (e *Endorser) SimulateProposal(txParams *ccprovider.TransactionParams, cid *pb.ChaincodeID) (ccprovider.ChaincodeDefinition, *pb.Response, []byte, *pb.ChaincodeEvent, error) {
	endorserLogger.Debugf("[%s][%s] Entry chaincode: %s", txParams.ChannelID, shorttxid(txParams.TxID), cid)
	defer endorserLogger.Debugf("[%s][%s] Exit", txParams.ChannelID, shorttxid(txParams.TxID))
	// we do expect the payload to be a ChaincodeInvocationSpec
	// if we are supporting other payloads in future, this be glaringly point
	// as something that should change
	cis, err := putils.GetChaincodeInvocationSpec(txParams.Proposal)
	if err != nil {
		return nil, nil, nil, nil, err
	}

	var cdLedger ccprovider.ChaincodeDefinition
	var version string

	if !e.s.IsSysCC(cid.Name) {
		cdLedger, err = e.s.GetChaincodeDefinition(cid.Name, txParams.TXSimulator)
		if err != nil {
			return nil, nil, nil, nil, errors.WithMessage(err, fmt.Sprintf("make sure the chaincode %s has been successfully instantiated and try again", cid.Name))
		}
		version = cdLedger.CCVersion()

		err = e.s.CheckInstantiationPolicy(cid.Name, version, cdLedger)
		if err != nil {
			return nil, nil, nil, nil, err
		}
	} else {
		version = util.GetSysCCVersion()
	}

	// ---3. execute the proposal and get simulation results
	var simResult *ledger.TxSimulationResults
	var pubSimResBytes []byte
	var res *pb.Response
	var ccevent *pb.ChaincodeEvent
	res, ccevent, err = e.callChaincode(txParams, version, cis.ChaincodeSpec.Input, cid)
	if err != nil {
		endorserLogger.Errorf("[%s][%s] failed to invoke chaincode %s, error: %+v", txParams.ChannelID, shorttxid(txParams.TxID), cid, err)
		return nil, nil, nil, nil, err
	}

	if txParams.TXSimulator != nil {
		if simResult, err = txParams.TXSimulator.GetTxSimulationResults(); err != nil {
			txParams.TXSimulator.Done()
			return nil, nil, nil, nil, err
		}

		if simResult.PvtSimulationResults != nil {
			if cid.Name == "lscc" {
				// TODO: remove once we can store collection configuration outside of LSCC
				txParams.TXSimulator.Done()
				return nil, nil, nil, nil, errors.New("Private data is forbidden to be used in instantiate")
			}
			pvtDataWithConfig, err := e.AssemblePvtRWSet(simResult.PvtSimulationResults, txParams.TXSimulator)
			// To read collection config need to read collection updates before
			// releasing the lock, hence txParams.TXSimulator.Done()  moved down here
			txParams.TXSimulator.Done()

			if err != nil {
				return nil, nil, nil, nil, errors.WithMessage(err, "failed to obtain collections config")
			}
			endorsedAt, err := e.s.GetLedgerHeight(txParams.ChannelID)
			if err != nil {
				return nil, nil, nil, nil, errors.WithMessage(err, fmt.Sprint("failed to obtain ledger height for channel", txParams.ChannelID))
			}
			// Add ledger height at which transaction was endorsed,
			// `endorsedAt` is obtained from the block storage and at times this could be 'endorsement Height + 1'.
			// However, since we use this height only to select the configuration (3rd parameter in distributePrivateData) and
			// manage transient store purge for orphaned private writesets (4th parameter in distributePrivateData), this works for now.
			// Ideally, ledger should add support in the simulator as a first class function `GetHeight()`.
			pvtDataWithConfig.EndorsedAt = endorsedAt
			if err := e.distributePrivateData(txParams.ChannelID, txParams.TxID, pvtDataWithConfig, endorsedAt); err != nil {
				return nil, nil, nil, nil, err
			}
		}

		txParams.TXSimulator.Done()
		if pubSimResBytes, err = simResult.GetPubSimulationBytes(); err != nil {
			return nil, nil, nil, nil, err
		}
	}
	return cdLedger, res, pubSimResBytes, ccevent, nil
}
833113
func (e *Endorser) preProcess(signedProp *pb.SignedProposal) (*validateResult, error) {
	vr := &validateResult{}
	// at first, we check whether the message is valid
	prop, hdr, hdrExt, err := validation.ValidateProposalMessage(signedProp)

	if err != nil {
		e.Metrics.ProposalValidationFailed.Add(1)
		vr.resp = &pb.ProposalResponse{Response: &pb.Response{Status: 500, Message: err.Error()}}
		return vr, err
	}

	chdr, err := putils.UnmarshalChannelHeader(hdr.ChannelHeader)
	if err != nil {
		vr.resp = &pb.ProposalResponse{Response: &pb.Response{Status: 500, Message: err.Error()}}
		return vr, err
	}

	shdr, err := putils.GetSignatureHeader(hdr.SignatureHeader)
	if err != nil {
		vr.resp = &pb.ProposalResponse{Response: &pb.Response{Status: 500, Message: err.Error()}}
		return vr, err
	}

	// block invocations to security-sensitive system chaincodes
	if e.s.IsSysCCAndNotInvokableExternal(hdrExt.ChaincodeId.Name) {
		endorserLogger.Errorf("Error: an attempt was made by %#v to invoke system chaincode %s", shdr.Creator, hdrExt.ChaincodeId.Name)
		err = errors.Errorf("chaincode %s cannot be invoked through a proposal", hdrExt.ChaincodeId.Name)
		vr.resp = &pb.ProposalResponse{Response: &pb.Response{Status: 500, Message: err.Error()}}
		return vr, err
	}

	chainID := chdr.ChannelId
	txid := chdr.TxId
	endorserLogger.Debugf("[%s][%s] processing txid: %s", chainID, shorttxid(txid), txid)

	if chainID != "" {
		// labels that provide context for failure metrics
		meterLabels := []string{
			"channel", chainID,
			"chaincode", hdrExt.ChaincodeId.Name + ":" + hdrExt.ChaincodeId.Version,
		}

		// Here we handle uniqueness check and ACLs for proposals targeting a chain
		// Notice that ValidateProposalMessage has already verified that TxID is computed properly
		if _, err = e.s.GetTransactionByID(chainID, txid); err == nil {
			// increment failure due to duplicate transactions. Useful for catching replay attacks in
			// addition to benign retries
			e.Metrics.DuplicateTxsFailure.With(meterLabels...).Add(1)
			err = errors.Errorf("duplicate transaction found [%s]. Creator [%x]", txid, shdr.Creator)
			vr.resp = &pb.ProposalResponse{Response: &pb.Response{Status: 500, Message: err.Error()}}
			return vr, err
		}

		// check ACL only for application chaincodes; ACLs
		// for system chaincodes are checked elsewhere
		if !e.s.IsSysCC(hdrExt.ChaincodeId.Name) {
			// check that the proposal complies with the Channel's writers
			if err = e.s.CheckACL(signedProp, chdr, shdr, hdrExt); err != nil {
				e.Metrics.ProposalACLCheckFailed.With(meterLabels...).Add(1)
				vr.resp = &pb.ProposalResponse{Response: &pb.Response{Status: 500, Message: err.Error()}}
				return vr, err
			}
		}
	} else {
		// chainless proposals do not/cannot affect ledger and cannot be submitted as transactions
		// ignore uniqueness checks; also, chainless proposals are not validated using the policies
		// of the chain since by definition there is no chain; they are validated against the local
		// MSP of the peer instead by the call to ValidateProposalMessage above
	}

	vr.prop, vr.hdrExt, vr.chainID, vr.txid = prop, hdrExt, chainID, txid
	return vr, nil
}
945204
func (db *ProposalDB) AllProposals(offset, rowsCount int,
	filterByVoteStatus ...int) (proposals []*pitypes.ProposalInfo,
	totalCount int, err error) {
	if db == nil || db.dbP == nil {
		return nil, 0, errDef
	}

	db.mtx.RLock()
	defer db.mtx.RUnlock()

	query := db.dbP.Select()
	if len(filterByVoteStatus) > 0 {
		// Filter by the votes status
		query = db.dbP.Select(q.Eq("VoteStatus",
			pitypes.VoteStatusType(filterByVoteStatus[0])))
	}

	// Count the proposals based on the query created above.
	totalCount, err = query.Count(&pitypes.ProposalInfo{})
	if err != nil {
		return
	}

	// Return the proposals listing starting with the newest.
	err = query.Skip(offset).Limit(rowsCount).Reverse().OrderBy("Timestamp").
		Find(&proposals)

	if err != nil && err != storm.ErrNotFound {
		log.Errorf("Failed to fetch data from Proposals DB: %v", err)
	} else {
		err = nil
	}

	return
}
459258
func GetBytesResponse(res *peer.Response) ([]byte, error) {
	resBytes, err := proto.Marshal(res)
	return resBytes, errors.Wrap(err, "error marshaling Response")
}
1364325
func (lsi *LastSignedInfo) SignProposal(sign tmCryptoSigner, chainID string, proposal *types.Proposal) error {
	lsi.Lock()
	defer lsi.Unlock()
	if err := lsi.signProposal(sign, chainID, proposal); err != nil {
		return fmt.Errorf("error signing proposal: %v", err)
	}
	return nil
}
1337132
func (gov *Governmint) validateProposal(store base.KVStore, p types.Proposal, proposer *types.Entity) (res tmsp.Result) {
	// Ensure that the proposal is unique
	if _, exists := gov.GetActiveProposal(store, p.ID); exists {
		return tmsp.NewError(tmsp.CodeType_GovDuplicateProposal,
			Fmt("Proposal with id %v already exists", p.ID))
	}
	// Ensure that the voting group exists
	voteGroup, ok := gov.GetGroup(store, p.VoteGroupID)
	if !ok {
		return tmsp.NewError(tmsp.CodeType_GovUnknownGroup,
			Fmt("Vote group with id %v doesn't exist", p.VoteGroupID))
	}
	// Ensure that the proposer belongs to the voting group
	if !isMemberOf(voteGroup, proposer.Addr) {
		return tmsp.NewError(tmsp.CodeType_Unauthorized,
			Fmt("Proposer %X is not member of %v", proposer.Addr, voteGroup.ID))
	}
	// Type dependent checks
	switch pInfo := p.Info.(type) {
	case *types.GroupCreateProposalInfo:
		// Ensure that the group ID is not taken
		if _, exists := gov.GetGroup(store, pInfo.NewGroupID); exists {
			return tmsp.NewError(tmsp.CodeType_GovDuplicateGroup,
				Fmt("Group with id %v already exists", pInfo.NewGroupID))
		}
		// Ensure that the member entities are unique
		if ok, dupe := validateUniqueMembers(pInfo.Members); !ok {
			return tmsp.NewError(tmsp.CodeType_GovDuplicateMember,
				Fmt("Duplicate member %v", dupe))
		}
		// Ensure that the member voting powers are reasonable
		for _, member := range pInfo.Members {
			if member.VotingPower == 0 {
				return tmsp.NewError(tmsp.CodeType_GovInvalidVotingPower,
					Fmt("Member cannot have 0 voting power"))
			}
			if member.VotingPower > MaxVotingPower {
				return tmsp.NewError(tmsp.CodeType_GovInvalidVotingPower,
					Fmt("Member voting power too large"))
			}
		}
		// Ensure that all the entities exist
		entityAddrs := entityAddrsFromMembers(pInfo.Members)
		_, unknownEntityAddr := gov.loadEntities(store, entityAddrs)
		if unknownEntityAddr != nil {
			return tmsp.NewError(tmsp.CodeType_GovUnknownEntity,
				Fmt("Group creation with unknown entity %X", unknownEntityAddr))
		}
	case *types.GroupUpdateProposalInfo:
		// Ensure that the update group exists
		updateGroup, ok := gov.GetGroup(store, pInfo.UpdateGroupID)
		if !ok {
			return tmsp.NewError(tmsp.CodeType_GovUnknownGroup,
				Fmt("Group with id %v doesn't exist", pInfo.UpdateGroupID))
		}
		// Ensure that the update group's parent is the voting group
		// XXX Admin check?
		if updateGroup.ParentID != voteGroup.ID {
			return tmsp.NewError(tmsp.CodeType_Unauthorized,
				Fmt("Group %v cannot update %v", voteGroup.ID, updateGroup.ID))
		}
		// Ensure that the member entities are unique
		if ok, dupe := validateUniqueMembers(pInfo.ChangedMembers); !ok {
			return tmsp.NewError(tmsp.CodeType_GovDuplicateMember,
				Fmt("Duplicate member %v", dupe))
		}
		// Ensure that the member voting powers are reasonable
		for _, member := range pInfo.ChangedMembers {
			if member.VotingPower == 0 {
				// This is fine, we're removing members.
			}
			if member.VotingPower > MaxVotingPower {
				return tmsp.NewError(tmsp.CodeType_GovInvalidVotingPower,
					Fmt("Member voting power too large"))
			}
		}
		// Ensure that all the entities exist
		entityAddrs := entityAddrsFromMembers(pInfo.ChangedMembers)
		_, unknownEntityAddr := gov.loadEntities(store, entityAddrs)
		if unknownEntityAddr != nil {
			return tmsp.NewError(tmsp.CodeType_GovUnknownEntity,
				Fmt("Group creation with unknown entity %X", unknownEntityAddr))
		}
	case *types.TextProposalInfo:
		// TODO text string validation, e.g. max length
	case *types.UpgradeProposalInfo:
		// Ensure that the group is admin.
		if voteGroup.ID != types.AdminGroupID {
			return tmsp.NewError(tmsp.CodeType_Unauthorized,
				Fmt("Upgrade proposals must be voted on by admin group"))
		}
		// Ensure that the number of modules is > 0.
		if len(pInfo.Modules) == 0 {
			return tmsp.NewError(tmsp.CodeType_EncodingError,
				Fmt("Software upgrade requires > 0 modules"))
		}
	}
	return tmsp.NewResultOK(nil, "")
}
291771
func SearchResponse(ctx context.Context, requester Requester, r SearchRequest) (*http.Response, error) {
	req, err := PrepSearchRequest(r)
	if err != nil {
		return nil, err
	}
	return requester(ctx, req)
}
940248
func GetMockEndorserClient(response *pb.ProposalResponse, err error) pb.EndorserClient {
	return &mockEndorserClient{
		response: response,
		err:      err,
	}
}
557916
func (t *MockTransactor) SendTransactionProposal(proposal *fab.TransactionProposal, targets []fab.ProposalProcessor) ([]*fab.TransactionProposalResponse, error) {
	rqtx, cancel := contextImpl.NewRequest(t.Ctx, contextImpl.WithTimeout(10*time.Second))
	defer cancel()
	return txn.SendProposal(rqtx, proposal, targets)
}
794854
func (t *MockTransactor) SendTransactionProposal(proposal *fab.TransactionProposal, targets []fab.ProposalProcessor) ([]*fab.TransactionProposalResponse, error) {
	response := make([]*fab.TransactionProposalResponse, 1)
	response[0] = &fab.TransactionProposalResponse{Endorser: "example.com", Status: 200,
		ProposalResponse: &pb.ProposalResponse{Response: &pb.Response{Message: "success", Payload: []byte("abc"), Status: http.StatusOK},
			Endorsement: &pb.Endorsement{Endorser: []byte("example.com"), Signature: []byte("signature")}},
	}
	return response, nil
}
590269
func (i *Image) getResponse(path string) (*http.Response, error) {
	errors := make(map[string]error)

	for _, ep := range i.endpoints {
		resp, err := i.getResponseFromURL(fmt.Sprintf("%s://%s/%s", i.scheme, ep, path))
		if err != nil {
			errors[ep] = err
			continue
		}

		return resp, nil
	}

	return nil, combineEndpointErrors(errors)
}
407862
func (ve *SignerValidatorEndpoint) SignProposal(chainID string, proposal *types.Proposal) error {
	ve.mtx.Lock()
	defer ve.mtx.Unlock()
	return ve.signer.SignProposal(chainID, proposal)
}
24827
func (rs *RoundState) CompleteProposalEvent() types.EventDataCompleteProposal {
	// We must construct BlockID from ProposalBlock and ProposalBlockParts
	// cs.Proposal is not guaranteed to be set when this function is called
	blockId := types.BlockID{
		Hash:        rs.ProposalBlock.Hash(),
		PartsHeader: rs.ProposalBlockParts.Header(),
	}

	return types.EventDataCompleteProposal{
		Height:  rs.Height,
		Round:   rs.Round,
		Step:    rs.Step.String(),
		BlockID: blockId,
	}
}
986244
func GetFromResponse(resp *http.Response) (string, error) {
	if resp == nil {
		return "", errors.New("nil response")
	}

	nonce := resp.Header.Get("Replay-Nonce")
	if nonce == "" {
		return "", fmt.Errorf("server did not respond with a proper nonce header")
	}

	return nonce, nil
}
842756
func RetrieveAllProposals(client *http.Client, APIRootPath, URLParams string) (
	*pitypes.Proposals, error) {
	// Constructs the full vetted proposals API URL
	URLpath := APIRootPath + piapi.RouteAllVetted + URLParams
	data, err := HandleGetRequests(client, URLpath)
	if err != nil {
		return nil, err
	}

	var publicProposals pitypes.Proposals
	err = json.Unmarshal(data, &publicProposals)
	if err != nil || len(publicProposals.Data) == 0 {
		return &publicProposals, err
	}

	// Constructs the full vote status API URL
	URLpath = APIRootPath + piapi.RouteAllVoteStatus + URLParams
	data, err = HandleGetRequests(client, URLpath)
	if err != nil {
		return nil, err
	}

	var votesInfo pitypes.Votes
	err = json.Unmarshal(data, &votesInfo)
	if err != nil {
		return nil, err
	}

	// Append the votes status information to the respective proposals if it exists.
	for _, val := range publicProposals.Data {
		for k := range votesInfo.Data {
			if val.TokenVal == votesInfo.Data[k].Token {
				val.ProposalVotes = votesInfo.Data[k]
				// exits the second loop after finding a match.
				break
			}
		}
	}

	return &publicProposals, nil
}