// Add a chain link to the end.
// `prevState` is moved into this function. There must exist no live references into it from now on.
// `signer` may be nil iff link is stubbed.
// If `prevState` is nil this is the first chain link.
504325
func (t *teamSigchainPlayer) appendChainLinkHelper(
	ctx context.Context, prevState *TeamSigChainState, link *ChainLinkUnpacked, signer *SignerX) (
	res TeamSigChainState, err error) {

	err = t.checkOuterLink(ctx, prevState, link)
	if err != nil {
		return res, fmt.Errorf("team sigchain outer link: %s", err)
	}

	var newState *TeamSigChainState
	if link.isStubbed() {
		if prevState == nil {
			return res, NewStubbedErrorWithNote(link, "first link cannot be stubbed")
		}
		newState2 := prevState.DeepCopy()
		newState = &newState2
	} else {
		if signer == nil || !signer.signer.Uid.Exists() {
			return res, NewInvalidLink(link, "signing user not provided for team link")
		}
		iRes, err := t.addInnerLink(prevState, link, *signer, false)
		if err != nil {
			return res, err
		}
		newState = &iRes.newState
	}

	newState.inner.LastSeqno = link.Seqno()
	newState.inner.LastLinkID = link.LinkID().Export()
	newState.inner.LinkIDs[link.Seqno()] = link.LinkID().Export()

	if link.isStubbed() {
		newState.inner.StubbedLinks[link.Seqno()] = true
	}

	// Store the head merkle sequence to the DB, for use in the audit mechanism.
	// For the purposes of testing, we disable this feature, so we can check
	// the lazy-repopulation scheme for old stored teams (without a full cache bust).
	if link.Seqno() == keybase1.Seqno(1) && !link.isStubbed() && !t.G().Env.Test.TeamNoHeadMerkleStore {
		tmp := link.inner.Body.MerkleRoot.ToMerkleRootV2()
		newState.inner.HeadMerkle = &tmp
	}

	if !link.isStubbed() && newState.inner.MerkleRoots != nil {
		newState.inner.MerkleRoots[link.Seqno()] = link.inner.Body.MerkleRoot.ToMerkleRootV2()
	}

	return *newState, nil
}
117685
func addListenerForCCEventsHandler(
	deployedCCInfoProvider ledger.DeployedChaincodeInfoProvider,
	stateListeners []ledger.StateListener) []ledger.StateListener {
	return append(stateListeners, &cceventmgmt.KVLedgerLSCCStateListener{DeployedChaincodeInfoProvider: deployedCCInfoProvider})
}
586532
func (c HandlerChain) Append(h ...Handler) HandlerChain {
	_c := make(HandlerChain, len(c)+len(h))
	copy(_c, c)
	copy(_c[len(c):], h)
	return _c
}
170232
func newStatePrefetcher(config *params.ChainConfig, bc *BlockChain, engine consensus.Engine) *statePrefetcher {
	return &statePrefetcher{
		config: config,
		bc:     bc,
		engine: engine,
	}
}
726877
func (h *Handler) Add(parts ...Constructor) *Handler {
	h.Chain = append(h.Chain, parts...)
	return h
}
565278
func (l *TeamLoader) loadUserAndKeyFromLinkInnerNoVerify(ctx context.Context,
	link *ChainLinkUnpacked) (signerUV keybase1.UserVersion, err error) {
	if !ShouldSuppressLogging(ctx) {
		defer l.G().CTraceTimed(ctx, fmt.Sprintf("TeamLoader#loadUserAndKeyFromLinkInnerNoVerify(%d)", int(link.inner.Seqno)), func() error { return err })()
	}
	keySection := link.inner.Body.Key
	if keySection == nil {
		return signerUV, libkb.NoUIDError{}
	}
	// Use the UID from the link body and EldestSeqno from the server-trust API response.
	if link.source.EldestSeqno == 0 {
		// We should never hit this case
		return signerUV, fmt.Errorf("missing server hint for team sigchain link signer")
	}
	return NewUserVersion(keySection.UID, link.source.EldestSeqno), nil
}
274049
func (cc *ChainStructure) AddToConditionalFuncs(cf ConditionCallStructure) {
	cc.chainf = append(cc.chainf, cf)
}
222583
func (pkz privKeys) signHeader(header *types.Header, first, last int) *types.Commit {
	commitSigs := make([]*types.CommitSig, len(pkz))

	// We need this list to keep the ordering.
	vset := pkz.ToValidators(1, 0)

	// Fill in the votes we want.
	for i := first; i < last && i < len(pkz); i++ {
		vote := makeVote(header, vset, pkz[i])
		commitSigs[vote.ValidatorIndex] = vote.CommitSig()
	}
	blockID := types.BlockID{Hash: header.Hash()}
	return types.NewCommit(blockID, commitSigs)
}
1092744
func (stub *ChaincodeStub) init(handler *Handler, channelId string, txid string, input *pb.ChaincodeInput, signedProposal *pb.SignedProposal) error {
	stub.TxID = txid
	stub.ChannelId = channelId
	stub.args = input.Args
	stub.handler = handler
	stub.signedProposal = signedProposal
	stub.decorations = input.Decorations
	stub.validationParameterMetakey = pb.MetaDataKeys_VALIDATION_PARAMETER.String()

	// TODO: sanity check: verify that every call to init with a nil
	// signedProposal is a legitimate one, meaning it is an internal call
	// to system chaincodes.
	if signedProposal != nil {
		var err error

		stub.proposal, err = utils.GetProposal(signedProposal.ProposalBytes)
		if err != nil {
			return errors.WithMessage(err, "failed extracting signedProposal from signed signedProposal")
		}

		// Extract creator, transient, binding...
		stub.creator, stub.transient, err = utils.GetChaincodeProposalContext(stub.proposal)
		if err != nil {
			return errors.WithMessage(err, "failed extracting signedProposal fields")
		}

		stub.binding, err = utils.ComputeProposalBinding(stub.proposal)
		if err != nil {
			return errors.WithMessage(err, "failed computing binding from signedProposal")
		}
	}

	return nil
}
1056299
func NewLink(options ...JITOption) (*LinkState, error) {
	link := &LinkState{}

	argcount, args, argvals := link.encodeArguments(options)
	err := result(C.cuLinkCreate(argcount, args, argvals, &link.state))
	return link, err
}
128905
func (l *SigChainLoader) MakeSigChain() error {
	sc := &SigChain{
		uid:                  l.user.GetUID(),
		username:             l.user.GetNormalizedName(),
		chainLinks:           l.links,
		currentSubchainStart: l.currentSubchainStart,
		Contextified:         NewContextified(l.G()),
	}
	for _, link := range l.links {
		link.SetParent(sc)
	}
	l.chain = sc
	return nil
}
806778
func (q *LinkedBlockingDeque) AddLast(e interface{}) error {
	if e == nil {
		return errors.New("e is nil")
	}
	if !q.OfferLast(e) {
		return errors.New("Deque full")
	}
	return nil
}
24235
func (n *node) prevSibling() *node {
	if n.parent == nil {
		return nil
	}
	index := n.parent.childIndex(n)
	if index == 0 {
		return nil
	}
	return n.parent.childAt(index - 1)
}
433401
func (c ChainLink) checkSpecialLinksTable(tab map[keybase1.LinkID]SpecialChainLink, uid keybase1.UID, why string) (found bool, reason string, err error) {
	var scl SpecialChainLink

	// The combination of hashVerified and chainVerified should ensure that this link
	// is only considered here after all prevs have been successfully checked.
	if !c.canTrustID() {
		return false, "", ChainLinkError{fmt.Sprintf("cannot check if a link is %q without a verified link ID (linkID=%s, uid=%s, hash=%v, chain=%v, diskVersion=%d)", why, c.id, uid, c.hashVerified, c.chainVerified, c.diskVersion)}
	}

	scl, found = tab[c.LinkID().Export()]
	if !found {
		return false, "", nil
	}
	if !c.GetSeqno().Eq(scl.Seqno) {
		return false, "", NewChainLinkWrongSeqnoError(fmt.Sprintf("malicious bad link in from server has wrong seqno in %q check: %d != %d", why, c.GetSeqno(), scl.Seqno))
	}
	if !scl.UID.Equal(uid) {
		return false, "", NewUIDMismatchError(fmt.Sprintf("malicious bad link from server in %q check; UID %s != %s", why, scl.UID, uid))
	}
	return true, scl.Reason, nil
}
432322
func (q *LinkedBlockingDeque) OfferLast(e interface{}) bool {
	if e == nil {
		return false
	}
	q.lock.Lock()
	result := q.linkLast(e)
	q.lock.Unlock()
	return result
}
784515
func (q *LinkedBlockingDeque) linkLast(e interface{}) bool {
	// assert lock.isHeldByCurrentThread();
	if q.count >= q.capacity {
		return false
	}
	l := q.last
	x := newNode(e, l, nil)
	q.last = x
	if q.first == nil {
		q.first = x
	} else {
		l.next = x
	}
	q.count = q.count + 1
	q.notEmpty.Signal()
	return true
}
884482
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) pb.Response {
	_, args := stub.GetFunctionAndParameters()
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return shim.Error("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return shim.Error("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return shim.Error("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return shim.Error(err.Error())
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return shim.Error(err.Error())
	}

	return shim.Success([]byte("OK"))
}