// Poll until the proof succeeds, limited to an hour.
424661
func (p *Prove) verifyLoop(m libkb.MetaContext) (err error) {
	timeout := time.Hour
	m, cancel := m.WithTimeout(timeout)
	defer cancel()
	uierr := m.UIs().ProveUI.Checking(m.Ctx(), keybase1.CheckingArg{
		Name: p.serviceType.DisplayName(),
	})
	if uierr != nil {
		m.Warning("prove ui Checking call error: %s", uierr)
	}
	for i := 0; ; i++ {
		if shouldContinue, uierr := m.UIs().ProveUI.ContinueChecking(m.Ctx(), 0); !shouldContinue || uierr != nil {
			if uierr != nil {
				m.Warning("prove ui ContinueChecking call error: %s", uierr)
			}
			return libkb.CanceledError{}
		}
		found, status, _, err := libkb.CheckPosted(m, p.sigID)
		if err != nil {
			return err
		}
		m.Debug("Prove.verifyLoop round:%v found:%v status:%v", i, found, status)
		if found {
			return nil
		}
		wakeAt := m.G().Clock().Now().Add(2 * time.Second)
		err = libkb.SleepUntilWithContext(m.Ctx(), m.G().Clock(), wakeAt)
		if err != nil {
			if err == context.DeadlineExceeded {
				return fmt.Errorf("Timed out looking a proof after %v", timeout)
			}
			return err
		}
	}
}
1283913
func (b *Build) Poll(options ...interface{}) (int, error) {
	depth := "-1"

	for _, o := range options {
		switch v := o.(type) {
		case string:
			depth = v
		case int:
			depth = strconv.Itoa(v)
		case int64:
			depth = strconv.FormatInt(v, 10)
		}
	}
	if depth == "-1" {
		depth = strconv.Itoa(b.Depth)
	}

	qr := map[string]string{
		"depth": depth,
	}
	response, err := b.Jenkins.Requester.GetJSON(b.Base, b.Raw, qr)
	if err != nil {
		return 0, err
	}
	return response.StatusCode, nil
}
1011988
func (s *suspicion) Confirm(from string) bool {
	// If we've got enough confirmations then stop accepting them.
	if atomic.LoadInt32(&s.n) >= s.k {
		return false
	}

	// Only allow one confirmation from each possible peer.
	if _, ok := s.confirmations[from]; ok {
		return false
	}
	s.confirmations[from] = struct{}{}

	// Compute the new timeout given the current number of confirmations and
	// adjust the timer. If the timeout becomes negative *and* we can cleanly
	// stop the timer then we will call the timeout function directly from
	// here.
	n := atomic.AddInt32(&s.n, 1)
	elapsed := time.Since(s.start)
	remaining := remainingSuspicionTime(n, s.k, elapsed, s.min, s.max)
	if s.timer.Stop() {
		if remaining > 0 {
			s.timer.Reset(remaining)
		} else {
			go s.timeoutFn()
		}
	}
	return true
}
223022
func (dve *DuplicateVoteEvidence) Verify(chainID string, pubKey crypto.PubKey) error {
	// H/R/S must be the same
	if dve.VoteA.Height != dve.VoteB.Height ||
		dve.VoteA.Round != dve.VoteB.Round ||
		dve.VoteA.Type != dve.VoteB.Type {
		return fmt.Errorf("DuplicateVoteEvidence Error: H/R/S does not match. Got %v and %v", dve.VoteA, dve.VoteB)
	}

	// Address must be the same
	if !bytes.Equal(dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress) {
		return fmt.Errorf("DuplicateVoteEvidence Error: Validator addresses do not match. Got %X and %X", dve.VoteA.ValidatorAddress, dve.VoteB.ValidatorAddress)
	}

	// Index must be the same
	if dve.VoteA.ValidatorIndex != dve.VoteB.ValidatorIndex {
		return fmt.Errorf("DuplicateVoteEvidence Error: Validator indices do not match. Got %d and %d", dve.VoteA.ValidatorIndex, dve.VoteB.ValidatorIndex)
	}

	// BlockIDs must be different
	if dve.VoteA.BlockID.Equals(dve.VoteB.BlockID) {
		return fmt.Errorf("DuplicateVoteEvidence Error: BlockIDs are the same (%v) - not a real duplicate vote", dve.VoteA.BlockID)
	}

	// pubkey must match address (this should already be true, sanity check)
	addr := dve.VoteA.ValidatorAddress
	if !bytes.Equal(pubKey.Address(), addr) {
		return fmt.Errorf("DuplicateVoteEvidence FAILED SANITY CHECK - address (%X) doesn't match pubkey (%v - %X)",
			addr, pubKey, pubKey.Address())
	}

	// Signatures must be valid
	if !pubKey.VerifyBytes(dve.VoteA.SignBytes(chainID), dve.VoteA.Signature) {
		return fmt.Errorf("DuplicateVoteEvidence Error verifying VoteA: %v", ErrVoteInvalidSignature)
	}
	if !pubKey.VerifyBytes(dve.VoteB.SignBytes(chainID), dve.VoteB.Signature) {
		return fmt.Errorf("DuplicateVoteEvidence Error verifying VoteB: %v", ErrVoteInvalidSignature)
	}

	return nil
}
1123062
func (p *DecisionTaskPoller) Poll(taskReady func(*swf.PollForDecisionTaskOutput) bool) (*swf.PollForDecisionTaskOutput, error) {
	var (
		resp   *swf.PollForDecisionTaskOutput
		page   int
		pollId = uuid.New()
	)

	eachPage := func(out *swf.PollForDecisionTaskOutput, _ bool) bool {
		page++

		var (
			firstEventId *int64
			lastEventId  *int64
			workflowId   string
		)

		if len(out.Events) > 0 {
			firstEventId = out.Events[0].EventId
			lastEventId = out.Events[len(out.Events)-1].EventId
		}

		if out.WorkflowExecution != nil {
			workflowId = LS(out.WorkflowExecution.WorkflowId)
		} else {
			workflowId = "no-workflow-execution"
		}

		Log.Printf("component=DecisionTaskPoller at=decision-task-page poll-id=%q task-list=%q workflow=%q page=%d "+
			"PreviousStartedEventId=%s StartedEventId=%s NumEvents=%d FirstEventId=%s LastEventId=%s",
			pollId, p.TaskList, workflowId, page,
			LL(out.PreviousStartedEventId), LL(out.StartedEventId), len(out.Events), LL(firstEventId), LL(lastEventId))

		if resp == nil {
			resp = out
		} else {
			resp.Events = append(resp.Events, out.Events...)
		}

		return !taskReady(resp)
	}

	err := p.client.PollForDecisionTaskPages(&swf.PollForDecisionTaskInput{
		Domain:       aws.String(p.Domain),
		Identity:     aws.String(p.Identity),
		ReverseOrder: aws.Bool(true),
		TaskList:     &swf.TaskList{Name: aws.String(p.TaskList)},
	}, eachPage)

	if err != nil {
		Log.Printf("component=DecisionTaskPoller poll-id=%q task-list=%q at=error error=%q",
			pollId, p.TaskList, err.Error())
		return nil, errors.Trace(err)
	}
	if resp != nil && resp.TaskToken != nil {
		Log.Printf("component=DecisionTaskPoller poll-id=%q at=decision-task-received task-list=%q workflow=%q",
			pollId, p.TaskList, LS(resp.WorkflowExecution.WorkflowId))
		p.logTaskLatency(resp)
		return resp, nil
	}
	Log.Printf("component=DecisionTaskPoller at=decision-task-empty-response poll-id=%q task-list=%q", pollId, p.TaskList)
	return nil, nil
}
624374
func pollParent(t time.Duration) {
	for initial := os.Getppid(); initial == os.Getppid(); time.Sleep(t) {
	}
}
1208585
func (c *crontime) nextValidSecond(baseTime time.Time) {
	for _, sec := range c.second {
		if !c.minuteHasPassed(baseTime) {
			// check if sec is in the past. <= prevents triggering the same event twice
			if sec > c.calculatedTime.Second() {
				c.calculatedTime = setSecond(c.calculatedTime, sec)
				return
			}
		} else {
			c.calculatedTime = setSecond(c.calculatedTime, sec)
			return
		}
	}
	c.calculatedTime = c.calculatedTime.Add(1 * time.Minute)
	c.calculatedTime = setSecond(c.calculatedTime, 0)
	//log.Println("Cronbee: Second", c.calculatedTime, baseTime)
	c.nextValidMinute(baseTime)
	c.nextValidSecond(baseTime)
}
838111
func (agent *Agent) poll(ctx context.Context) error {
	// Metadata tells us which Machine Provider instance to talk to
	// and how to authenticate.
	for {
		logging.Infof(ctx, "Polling.")
		instruction, err := agent.mp.poll(ctx, agent.hostname, "GCE")
		if err != nil {
			// Log error but don't return. Keep polling.
			logging.Errorf(ctx, "%s", err.Error())
		} else {
			if err = agent.handle(ctx, instruction); err != nil {
				return err
			}
		}
		tsmon.Flush(ctx)
		time.Sleep(time.Minute)
	}
}
407931
func (*CredRequest) Verify(credentialRequest []byte, ipk handlers.IssuerPublicKey, nonce []byte) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = errors.Errorf("failure [%s]", r)
		}
	}()

	credRequest := &cryptolib.CredRequest{}
	err = proto.Unmarshal(credentialRequest, credRequest)
	if err != nil {
		return err
	}

	iipk, ok := ipk.(*IssuerPublicKey)
	if !ok {
		return errors.Errorf("invalid issuer public key, expected *IssuerPublicKey, got [%T]", ipk)
	}

	err = credRequest.Check(iipk.PK)
	if err != nil {
		return err
	}

	// Nonce checks
	if len(nonce) != cryptolib.FieldBytes {
		return errors.Errorf("invalid issuer nonce, expected length %d, got %d", cryptolib.FieldBytes, len(nonce))
	}
	if !bytes.Equal(nonce, credRequest.IssuerNonce) {
		return errors.Errorf("invalid nonce, expected [%v], got [%v]", nonce, credRequest.IssuerNonce)
	}

	return nil
}
1100214
func (m *CredRequest) Check(ipk *IssuerPublicKey) error {
	Nym := EcpFromProto(m.GetNym())
	IssuerNonce := m.GetIssuerNonce()
	ProofC := FP256BN.FromBytes(m.GetProofC())
	ProofS := FP256BN.FromBytes(m.GetProofS())

	HSk := EcpFromProto(ipk.HSk)

	if Nym == nil || IssuerNonce == nil || ProofC == nil || ProofS == nil {
		return errors.Errorf("one of the proof values is undefined")
	}

	// Verify Proof

	// Recompute t-values using s-values
	t := HSk.Mul(ProofS)
	t.Sub(Nym.Mul(ProofC)) // t = h_{sk}^s / Nym^C

	// Recompute challenge
	proofData := make([]byte, len([]byte(credRequestLabel))+3*(2*FieldBytes+1)+2*FieldBytes)
	index := 0
	index = appendBytesString(proofData, index, credRequestLabel)
	index = appendBytesG1(proofData, index, t)
	index = appendBytesG1(proofData, index, HSk)
	index = appendBytesG1(proofData, index, Nym)
	index = appendBytes(proofData, index, IssuerNonce)
	copy(proofData[index:], ipk.Hash)

	if *ProofC != *HashModOrder(proofData) {
		return errors.Errorf("zero knowledge proof is invalid")
	}

	return nil
}
43050
func (r *EchoRequest) VerifyTimestamp() bool {
	reqTimestamp, _ := time.Parse("2006-01-02T15:04:05Z", r.Request.Timestamp)
	if time.Since(reqTimestamp) < time.Duration(150)*time.Second {
		return true
	}

	return false
}
725033
func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
	ctx, cancel := contextForChannel(stopCh)
	defer cancel()
	return WaitFor(poller(interval, 0), condition, ctx.Done())
}
489417
func (p *MiddlewarePoller) Poll(b *Bot, dest chan Update, stop chan struct{}) {
	cap := 1
	if p.Capacity > 1 {
		cap = p.Capacity
	}

	middle := make(chan Update, cap)
	stopPoller := make(chan struct{})

	go p.Poller.Poll(b, middle, stopPoller)

	for {
		select {
		// call to stop
		case <-stop:
			stopPoller <- struct{}{}

		// poller is done
		case <-stopPoller:
			close(stop)
			return

		case upd := <-middle:
			if p.Filter(&upd) {
				dest <- upd
			}
		}
	}
}
968337
func (shard *ringShard) Vote(up bool) bool {
	if up {
		changed := shard.IsDown()
		atomic.StoreInt32(&shard.down, 0)
		return changed
	}

	if shard.IsDown() {
		return false
	}

	atomic.AddInt32(&shard.down, 1)
	return shard.IsDown()
}
181894
func (tally *VoteTally) Status() ([]int, int) {
	votes := []int{}
	var up, down, consensus int
	for _, affirmed := range tally.Marks {
		if affirmed {
			up++
			votes = append(votes, VoteAffirm)
		} else {
			down++
			votes = append(votes, VoteReject)
		}
	}
	for i := len(votes); i < tally.TicketsPerBlock; i++ {
		votes = append(votes, VoteMissing)
	}
	threshold := tally.TicketsPerBlock / 2
	if up > threshold {
		consensus = VoteAffirm
	} else if down > threshold {
		consensus = VoteReject
	}
	return votes, consensus
}
1236785
func (s *Server) Poll(ttl time.Duration) {
	containers, err := s.DockerClient.ListContainers(docker.ListContainersOptions{})
	if err != nil {
		log.Fatal(err)
	}
	var wg sync.WaitGroup
	for _, container := range containers {
		wg.Add(1)
		go func(container docker.APIContainers, ttl time.Duration) {
			defer wg.Done()
			// send container to channel for processing
			s.publishContainer(&container, ttl)
		}(container, ttl)
	}
	// Wait for all publish operations to complete.
	wg.Wait()
}
987032
func pollTaskAndWait(task enamlbosh.BoshTask, client *enamlbosh.Client, tries int) error {
	UIPrint("polling task...")
	defer UIPrint(fmt.Sprintf("Finished with Task %s", task.Description))
	ticker := time.Tick(time.Second)
	count := 0
	for {
		<-ticker
		var err error
		task, err = client.GetTask(task.ID)
		if err != nil {
			return err
		}
		switch task.State {
		case enamlbosh.StatusDone:
			UIPrintStatus(fmt.Sprintf("task state %s", task.State))
			return nil
		case enamlbosh.StatusCancelled, enamlbosh.StatusError:
			err := fmt.Errorf("%s - %s", task.State, task.Description)
			lo.G.Error("task error: " + err.Error())
			return err
		default:
			UIPrintStatus(fmt.Sprintf("task '%s' is %s", task.Description, task.State))
		}
		count++

		if tries != -1 && count >= tries {
			UIPrintStatus("hit poll limit, exiting task poller without error")
			return nil
		}
	}
}