Checks to see if the reporting of an incident should be throttled due
to the number of times the signature has been seen in the last hour

@param signature incident signature
@return true if incidents needs to be throttled
332720
private synchronized boolean needsToThrottle(String signature)
  {
    AtomicInteger sigCount;

    // Are we already throttling this signature?
    if (throttledIncidents.containsKey(signature))
    {
      // Lazily check if it's time to unthrottle
      if (throttledIncidents.get(signature).plusHours(THROTTLE_DURATION_HRS).
          compareTo(DateTime.now()) <= 0)
      {
        // Start counting the # of times we've seen this again & stop throttling.
        throttledIncidents.remove(signature);
        incidentCounter.put(signature, new AtomicInteger(1));
        return false;
      }

      return true;
    }

    sigCount = incidentCounter.get(signature);
    if (sigCount == null)
    {
      // If there isn't an entry to track this signature, make one.
      incidentCounter.put(signature, sigCount = new AtomicInteger(0));
    }
    else if (sigCount.get() + 1 >= INCIDENT_THROTTLE_LIMIT_PER_HR)
    {
      // We've hit the limit so throttle.
      incidentCounter.remove(signature);
      throttledIncidents.put(signature, DateTime.now());
      return true;
    }

    sigCount.incrementAndGet();
    return false;
  }
1354900
public static RuleViolation isInputStandard(TransactionInput input) {
        for (ScriptChunk chunk : input.getScriptSig().getChunks()) {
            if (chunk.data != null && !chunk.isShortestPossiblePushData())
                return RuleViolation.SHORTEST_POSSIBLE_PUSHDATA;
            if (chunk.isPushData()) {
                ECDSASignature signature;
                try {
                    signature = ECKey.ECDSASignature.decodeFromDER(chunk.data);
                } catch (SignatureDecodeException x) {
                    // Doesn't look like a signature.
                    signature = null;
                }
                if (signature != null) {
                    if (!TransactionSignature.isEncodingCanonical(chunk.data))
                        return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                    if (!signature.isCanonical())
                        return RuleViolation.SIGNATURE_CANONICAL_ENCODING;
                }
            }
        }
        return RuleViolation.NONE;
    }
1272048
@Override
    public SignatureVisitor visitSuperclass() {
        if (type != CLASS_SIGNATURE || (state & (EMPTY | FORMAL | BOUND)) == 0) {
            throw new IllegalArgumentException();
        }
        state = SUPER;
        SignatureVisitor v = sv == null ? null : sv.visitSuperclass();
        return new CheckSignatureAdapter(TYPE_SIGNATURE, v);
    }
1234504
def isSelfSigned(self):
        
        if self.issuer_hash == self.subject_hash:
            return self.isIssuerCert(self)
        return False
1245205
async def message_throttled(self, message: types.Message, throttled: Throttled):
        
        handler = current_handler.get()
        dispatcher = Dispatcher.get_current()
        if handler:
            key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
        else:
            key = f"{self.prefix}_message"

        # Calculate how many time is left till the block ends
        delta = throttled.rate - throttled.delta

        # Prevent flooding
        if throttled.exceeded_count <= 2:
            await message.reply('Too many requests! ')

        # Sleep.
        await asyncio.sleep(delta)

        # Check lock status
        thr = await dispatcher.check_key(key)

        # If current message is not last with current key - do not send message
        if thr.exceeded_count == throttled.exceeded_count:
            await message.reply('Unlocked.')
682523
public function check(array $auth, array $signature, $prefix)
    {
        if (! isset($auth[$prefix . 'timestamp'])) {
            throw new SignatureTimestampException('The timestamp has not been set');
        }

        if (abs($auth[$prefix . 'timestamp'] - time()) >= $this->grace) {
            throw new SignatureTimestampException('The timestamp is invalid');
        }

        return true;
    }
687220
public boolean report(ReportRequest req) {
    if (cache == null) {
      return false;
    }
    Preconditions.checkArgument(req.getServiceName().equals(serviceName), "service name mismatch");
    if (hasHighImportanceOperation(req)) {
      return false;
    }
    Map<String, Operation> bySignature = opsBySignature(req);

    // Concurrency: all threads wait while the current thread updates the cache.
    //
    // It's better for overall latency to have one thread complete cache update at a time than have
    // multiple threads interleave updates with the increased cpu cost due to increased context
    // switching.
    //
    // No i/o or computation is occurring, so the wait time should be relatively small and
    // depend on the number of waiting threads.
    synchronized (cache) {
      for (Map.Entry<String, Operation> entry : bySignature.entrySet()) {
        String signature = entry.getKey();
        OperationAggregator agg = cache.getIfPresent(signature);
        if (agg == null) {
          cache.put(signature, new OperationAggregator(entry.getValue(), kinds));
        } else {
          agg.add(entry.getValue());
        }
      }
    }
    return true;
  }
1276349
public static void checkClassSignature(final String signature) {
        // ClassSignature:
        // FormalTypeParameters? ClassTypeSignature ClassTypeSignature*

        int pos = 0;
        if (getChar(signature, 0) == '<') {
            pos = checkFormalTypeParameters(signature, pos);
        }
        pos = checkClassTypeSignature(signature, pos);
        while (getChar(signature, pos) == 'L') {
            pos = checkClassTypeSignature(signature, pos);
        }
        if (pos != signature.length()) {
            throw new IllegalArgumentException(signature + ": error at index "
                    + pos);
        }
    }
783524
protected boolean isTicketAuthenticityVerified(final String ticketId) {
        if (this.cipherExecutor != null) {
            LOGGER.trace("Attempting to decode service ticket [{}] to verify authenticity", ticketId);
            return !StringUtils.isEmpty(this.cipherExecutor.decode(ticketId));
        }
        return !StringUtils.isEmpty(ticketId);
    }
1233995
public boolean verify() throws SignatureException {
        if (verified)
            return verifyResult;
        if (sigAttr != null) {
            sig.update(sigAttr);
            if (RSAdata != null) {
                byte msd[] = messageDigest.digest();
                messageDigest.update(msd);
            }
            verifyResult = (Arrays.equals(messageDigest.digest(), digestAttr) && sig.verify(digest));
        }
        else {
            if (RSAdata != null)
                sig.update(messageDigest.digest());
            verifyResult = sig.verify(digest);
        }
        verified = true;
        return verifyResult;
    }
919440
def check_signature(self, msgbuf, srcSystem, srcComponent):
            ''''''
            if isinstance(msgbuf, array.array):
                msgbuf = msgbuf.tostring()
            timestamp_buf = msgbuf[-12:-6]
            link_id = msgbuf[-13]
            (tlow, thigh) = struct.unpack('<IH', timestamp_buf)
            timestamp = tlow + (thigh<<32)

            # see if the timestamp is acceptable
            stream_key = (link_id,srcSystem,srcComponent)
            if stream_key in self.signing.stream_timestamps:
                if timestamp <= self.signing.stream_timestamps[stream_key]:
                    # reject old timestamp
                    # print('old timestamp')
                    return False
            else:
                # a new stream has appeared. Accept the timestamp if it is at most
                # one minute behind our current timestamp
                if timestamp + 6000*1000 < self.signing.timestamp:
                    # print('bad new stream ', timestamp/(100.0*1000*60*60*24*365), self.signing.timestamp/(100.0*1000*60*60*24*365))
                    return False
                self.signing.stream_timestamps[stream_key] = timestamp
                # print('new stream')

            h = hashlib.new('sha256')
            h.update(self.signing.secret_key)
            h.update(msgbuf[:-6])
            sig1 = str(h.digest())[:6]
            sig2 = str(msgbuf)[-6:]
            if sig1 != sig2:
                # print('sig mismatch')
                return False

            # the timestamp we next send with is the max of the received timestamp and
            # our current timestamp
            self.signing.timestamp = max(self.signing.timestamp, timestamp)
            return True
1290522
def is_throttled(e):
    
    return True if (hasattr(e, 'response') and
                    e.response is not None and
                    'Error' in e.response and
                    e.response['Error']['Code'] in ['Throttling', 'RequestLimitExceeded', 'ThrottlingException']) else \
        False
494310
private boolean shouldSendIncrementalReport(long startTime){
    boolean isPrimary = isPrimaryServiceCached() || 
        donotDelayIncrementalBlockReports;
    boolean deleteIntervalTrigger = 
        (startTime - lastDeletedReport > anode.deletedReportInterval);
    
    // by default the report should be sent if there are any received
    // acks, or the deleteInterval has passed
    boolean sendReportDefault = pendingReceivedRequests > 0
        || deleteIntervalTrigger;
    
    if(isPrimary){
      // if talking to primary, send the report with the default
      // conditions
      return sendReportDefault;
    } else {
      // if talking to standby. send the report ONLY when the 
      // retry interval has passed in addition to the default
      // condidtions
      boolean sendIfStandby = 
          (lastBlockReceivedFailed + blockReceivedRetryInterval < startTime)
          && sendReportDefault;
      return sendIfStandby;
    }
  }
803788
def isSignatureValid(expected, received):
    
    if expected:
        if not received or expected != received:
            return False
    else:
        if received:
            return False
    return True
812128
public boolean isValid() {
		NodeList nodes = xmlDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");

		if (nodes == null || nodes.getLength() == 0) {
			logger.debug("Can't find signature in document");
			return false;
		}

		if (setIdAttributeExists()) {
			tagIdAttributes(xmlDoc);
		}

		X509Certificate cert = certificate.getX509Cert();
		DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), nodes.item(0));
		XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");

		XMLSignature xmlSignature;
		try {
			xmlSignature = sigF.unmarshalXMLSignature(ctx);
		} catch (Exception e) {
			logger.debug("Could not unmarshalXMLSignature", e);
			xmlSignature = null;
		}
		if (xmlSignature == null) {
			return false;
		}
		try {
			return xmlSignature.validate(ctx);
		} catch (XMLSignatureException e) {
			logger.debug("Could not validate signature", e);
		}
		return false;
	}
762030
private boolean hasMessagesPending()
  {

    for (Map.Entry<MessageQueue, ConcurrentSkipListSet<MessageExt>> entry : messageQueueTreeSetMap.entrySet()) {
      if (!entry.getValue().isEmpty()) {
        return true;
      }
    }

    return false;
  }
399943
private void checkStability() {
    if ((_watermarksInserted.getCount() - _watermarksSwept.getCount()) > _watermarkLagThreshold) {
      log.error("Setting abort flag for Watermark tracking because the lag between the "
          + "watermarksInserted: {} and watermarksSwept: {} is greater than the threshold: {}",
          _watermarksInserted.getCount(), _watermarksSwept.getCount(), _watermarkLagThreshold);
      _abort.set(true);
    }
  }