Validate the credit card information via javascript (Number, Owner, and CVV Lengths)
543845
function javascript_validation() {
    $js = '  if (payment_value == "' . $this->code . '") {' . "\n" .
          '    var cc_owner = document.checkout_payment.linkpoint_api_cc_owner.value;' . "\n" .
          '    var cc_number = document.checkout_payment.linkpoint_api_cc_number.value;' . "\n" .
          '    var cc_cvv = document.checkout_payment.linkpoint_api_cc_cvv.value;' . "\n" .
          '    if (cc_owner == "" || cc_owner.length < ' . CC_OWNER_MIN_LENGTH . ') {' . "\n" .
          '      error_message = error_message + "' . MODULE_PAYMENT_LINKPOINT_API_TEXT_JS_CC_OWNER . '";' . "\n" .
          '      error = 1;' . "\n" .
          '    }' . "\n" .
          '    if (cc_number == "" || cc_number.length < ' . CC_NUMBER_MIN_LENGTH . ') {' . "\n" .
          '      error_message = error_message + "' . MODULE_PAYMENT_LINKPOINT_API_TEXT_JS_CC_NUMBER . '";' . "\n" .
          '      error = 1;' . "\n" .
          '    }' . "\n" .
          '         if (cc_cvv == "" || cc_cvv.length < "3") {' . "\n".
          '           error_message = error_message + "' . MODULE_PAYMENT_LINKPOINT_API_TEXT_JS_CC_CVV . '";' . "\n" .
          '           error = 1;' . "\n" .
          '         }' . "\n" .
          '  }' . "\n";

    return $js;
  }
1315570
public function validate()
	{
		$this->validateAttributes([
			Request::ATTRIBUTE_INTERFACE,
			Request::ATTRIBUTE_TRANSACTION_TYPE,
		]);

		$transactionType = $this->getTransactionType();

		switch ($transactionType) {
			case Request::TRANSACTION_TYPE_PURCHASE:
			case Request::TRANSACTION_TYPE_PRE_AUTH: {
				$this->validateAttributes([
					Request::ATTRIBUTE_TOTAL_AMOUNT,
					Request::ATTRIBUTE_CARD_DATA,
					Request::ATTRIBUTE_CARD_EXPIRY_DATE,
				], [
					Request::ATTRIBUTE_TRANSACTION_REFERENCE,
					Request::ATTRIBUTE_ORIGINAL_TRANSACTION_REFERENCE,
					Request::ATTRIBUTE_PRE_AUTH_NUMBER,
					Request::ATTRIBUTE_AUTH_NUMBER,
					Request::ATTRIBUTE_AUTHORISATION_CODE,
					Request::ATTRIBUTE_AUTHORISATION_NUMBER,
				]);

				break;
			}

			case Request::TRANSACTION_TYPE_REFUND: {
				$this->validateAttributes([
					Request::ATTRIBUTE_TOTAL_AMOUNT,
					Request::ATTRIBUTE_ORIGINAL_TRANSACTION_REFERENCE,
				], [
					Request::ATTRIBUTE_CARD_DATA,
					Request::ATTRIBUTE_CARD_EXPIRY_DATE,
					Request::ATTRIBUTE_TRANSACTION_REFERENCE,
					Request::ATTRIBUTE_PRE_AUTH_NUMBER,
					Request::ATTRIBUTE_AUTH_NUMBER,
					Request::ATTRIBUTE_AUTHORISATION_CODE,
					Request::ATTRIBUTE_AUTHORISATION_NUMBER,
				]);

				break;
			}

			case Request::TRANSACTION_TYPE_COMPLETION: {
				$this->validateAttributes([
					Request::ATTRIBUTE_TOTAL_AMOUNT,
					[
						Request::ATTRIBUTE_ORIGINAL_TRANSACTION_REFERENCE,
						Request::ATTRIBUTE_PRE_AUTH_NUMBER,
					],
					[
						Request::ATTRIBUTE_AUTH_CODE,
						Request::ATTRIBUTE_AUTH_NUMBER,
						Request::ATTRIBUTE_AUTHORISATION_CODE,
						Request::ATTRIBUTE_AUTHORISATION_NUMBER,
					],
				], [
					Request::ATTRIBUTE_CARD_DATA,
					Request::ATTRIBUTE_CARD_EXPIRY_DATE,
					Request::ATTRIBUTE_TRANSACTION_REFERENCE,
				]);

				break;
			}

			case Request::TRANSACTION_TYPE_STATUS: {
				$this->validateAttributes([
					Request::ATTRIBUTE_TRANSACTION_REFERENCE,
				], [
					Request::ATTRIBUTE_TOTAL_AMOUNT,
					Request::ATTRIBUTE_TAX_AMOUNT,
					Request::ATTRIBUTE_CARD_DATA,
					Request::ATTRIBUTE_CARD_EXPIRY_DATE,
					Request::ATTRIBUTE_ORIGINAL_TRANSACTION_REFERENCE,
					Request::ATTRIBUTE_PRE_AUTH_NUMBER,
					Request::ATTRIBUTE_AUTH_CODE,
					Request::ATTRIBUTE_AUTH_NUMBER,
					Request::ATTRIBUTE_AUTHORISATION_CODE,
					Request::ATTRIBUTE_AUTHORISATION_NUMBER,
					Request::ATTRIBUTE_CLIENT_REFERENCE,
					Request::ATTRIBUTE_COMMENT,
					Request::ATTRIBUTE_MERCHANT_CARD_HOLDER_NAME,
					Request::ATTRIBUTE_MERCHANT_DESCRIPTION,
					Request::ATTRIBUTE_TERMINAL_TYPE,
					Request::ATTRIBUTE_CVC2,
				]);

				break;
			}
		}

		return TRUE;
	}
135716
function validate($value, $key, $fields, $options, $exists, \CharlotteDunois\Validation\Validator $validator) {
        $finfo = \finfo_open(\FILEINFO_MIME);
        
        if(isset($_FILES[$key])) {
            if(!\file_exists($_FILES[$key]['tmp_name'])) {
                return 'formvalidator_make_invalid_file';
            }
            
            $mime = \finfo_file($finfo, $_FILES[$key]['tmp_name']);
        } else {
            if(!$exists) {
                return false;
            }
            
            $mime = \finfo_buffer($finfo, $value);
        }
        
        \finfo_close($finfo);
        
        if(!$mime) {
            return 'formvalidator_make_invalid_file'; // @codeCoverageIgnore
        }
        
        $mime = \explode(';', $mime);
        $mime = \array_shift($mime);
        
        $val = \explode(',', $options);
        $result = \explode('/', $mime);
        
        foreach($val as $mimet) {
            $mimee = \explode('/', $mimet);
            if(\count($mimee) == 2 && \count($result) == 2) {
                if(($mimee[0] == "*" || $mimee[0] == $result[0]) && ($mimee[1] == "*" || $mimee[1] == $result[1])) {
                    return true;
                }
            }
        }
        
        return 'formvalidator_make_invalid_file';
    }
920752
function isValid (type, value) {
      switch (type) {
        case 'email':
          return validator.isEmail(value);
          break;
        case 'url':
          return validator.isURL(value);
          break;
        case 'domain':
          return validator.isFQDN(value);
          break;
        case 'ip':
          return validator.isIP(value);
          break;
        case 'alpha':
          return validator.isAlpha(value);
          break;
        case 'number':
          return validator.isNumeric(value);
          break;
        case 'alphanumeric':
          return validator.isAlphanumeric(value);
          break;
        case 'base64':
          return validator.isBase64(value);
          break;
        case 'hexadecimal':
          return validator.isHexadecimal(value);
          break;
        case 'hexcolor':
          return validator.isHexColor(value);
          break;
        case 'int':
          return validator.isInt(value);
          break;
        case 'float':
          return validator.isFloat(value);
          break;
        case 'null':
          return validator.isNull(value);
          break;
        case 'uuid':
          return validator.isUUID(value);
          break;
        case 'date':
          return validator.isDate(value);
          break;
        case 'creditcard':
          return validator.isCreditCard(value);
          break;
        case 'isbn':
          return validator.isISBN(value);
          break;
        case 'mobilephone':
          return validator.isMobilePhone(value);
          break;
        case 'json':
          return validator.isJSON(value);
          break;
        case 'ascii':
          return validator.isAscii(value);
          break;
        case 'mongoid':
          return validator.isMongoId(value);
          break;
        default:
          return false;
          break;
      }
    }
1182129
function initialize() {
    var creditcard;
    // [square] @import "creditcard/index.js"
    this.lib = creditcard;

    //
    // Create references to elements.
    //
    this.number = this.$('input[name="full_number"]');
    this.cvv = this.$('input[name="cvv"]');
    this.year = this.$('select[name="expiration_year"]');
    this.month = this.$('select[name="expiration_month"]');
    this.card = this.$('.card');

    //
    // Is validation required?
    //
    this.validate = !!this.$el.get('validate');
  }
584283
protected function validateOwner()
    {
        if (0 == ($valueLength = strlen($this->owner->getValue()))) {
            return true;
        }

        $allowedLength = $this->getConfig();
        if (is_scalar($allowedLength)) {
            return $valueLength == $allowedLength;
        } else {
            return (empty($allowedLength['min']) || $valueLength >= $allowedLength['min']) &&
                   (empty($allowedLength['max']) || $valueLength <= $allowedLength['max']);
        }
    }
1155891
def validate(self,
                 _portfolio,
                 _account,
                 _algo_datetime,
                 _algo_current_data):
        
        if _account.leverage > self.max_leverage:
            self.fail()
257599
public static function get_card_type($pan, $include_sub_types = false) {
        $pan = preg_replace('/\D/i', '', $pan);
        //maximum length is not fixed now, there are growing number of CCs has more numbers in length, limiting can give false negatives atm

        //these regexps accept not whole cc numbers too
        //visa
        $visa_regex = '/^4[0-9]{0,}$/';
        $vpreca_regex = '/^428485[0-9]{0,}$/';
        $postepay_regex = '/^(402360|402361|403035|417631|529948){0,}$/';
        $cartasi_regex = '/^(432917|432930|453998)[0-9]{0,}$/';
        $entropay_regex = '/^(406742|410162|431380|459061|533844|522093)[0-9]{0,}$/';
        $o2money_regex = '/^(422793|475743)[0-9]{0,}$/';

        // MasterCard
        $mastercard_regex = '/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$/';
        $maestro_regex = '/^(5[06789]|6)[0-9]{0,}$/';
        $kukuruza_regex = '/^525477[0-9]{0,}$/';
        $yunacard_regex = '/^541275[0-9]{0,}$/';

        // American Express
        $amex_regex = '/^3[47][0-9]{0,}$/';

        // Diners Club
        $diners_regex = '/^3(?:0[0-59]{1}|[689])[0-9]{0,}$/';

        //Discover
        $discover_regex = '/^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$/';

        //JCB
        $jcb_regex = '/^(?:2131|1800|35)[0-9]{0,}$/';

        //ordering matter in detection, otherwise can give false results in rare cases
        if (preg_match($jcb_regex, $pan)) {
            return 'jcb';
        }

        if (preg_match($amex_regex, $pan)) {
            return 'amex';
        }

        if (preg_match($diners_regex, $pan)) {
            return 'diners_club';
        }

        //sub visa/mastercard cards
        if ($include_sub_types) {
            if (preg_match($vpreca_regex, $pan)) {
                return 'v-preca';
            }
            if (preg_match($postepay_regex, $pan)) {
                return 'postepay';
            }
            if (preg_match($cartasi_regex, $pan)) {
                return 'cartasi';
            }
            if (preg_match($entropay_regex, $pan)) {
                return 'entropay';
            }
            if (preg_match($o2money_regex, $pan)) {
                return 'o2money';
            }
            if (preg_match($kukuruza_regex, $pan)) {
                return 'kukuruza';
            }
            if (preg_match($yunacard_regex, $pan)) {
                return 'yunacard';
            }
        }

        if (preg_match($visa_regex, $pan)) {
            return 'visa';
        }

        if (preg_match($mastercard_regex, $pan)) {
            return 'mastercard';
        }

        if (preg_match($discover_regex, $pan)) {
            return 'discover';
        }

        if (preg_match($maestro_regex, $pan)) {
            if ($pan[0] == '5') {//started 5 must be mastercard
                return 'mastercard';
            }
                return 'maestro'; //maestro is all 60-69 which is not something else, thats why this condition in the end

        }

        return 'unknown'; //unknown for this system
    }
363307
function NUMBER_VALIDATOR(v) {
  v = (v || '').toString()
  var match = v.match(LENGTH_REGEXP)

  if (match && !match[1]) {
    return {value: parseFloat(v)}
  }

  return {
    value: null,
    reason: function reason(k, v, result) {
      return 'ERROR: property value `' + v + '` is not supported for `' + util.camelCaseToHyphened(k) + '` (only number is supported)'
    }
  }
}
818446
def iso_payment_reference_validator(v: str):
    
    num = ''
    v = STRIP_WHITESPACE.sub('', v)
    for ch in v[4:] + v[0:4]:
        x = ord(ch)
        if ord('0') <= x <= ord('9'):
            num += ch
        else:
            x -= 55
            if x < 10 or x > 35:
                raise ValidationError(_('Invalid payment reference: {}').format(v))
            num += str(x)
    res = Decimal(num) % Decimal('97')
    if res != Decimal('1'):
        raise ValidationError(_('Invalid payment reference: {}').format(v))
686390
function validateName(var_name) {
        var o = "";
        for (var i = 0; i < var_name.length; i++) {
            var code = var_name.charCodeAt(i);
            if ((code > 47 && code < 58) || // numeric (0-9)
                (code > 64 && code < 91) || // upper alpha (A-Z)
                (code > 96 && code < 123) || // lower alpha (a-z)
                var_name[i] === "$" ||
                var_name[i] === "_" ||
                var_name[i] === "." ||
                var_name[i] === "&" ||
                code > 255 // utf
                ) {
                o += var_name[i];
            } else {
                o += "_$" + code + "_";
            }
        }
        if (!isNaN(o[0])) o =  "_" + o ; // first letter is number, add _ ahead.
        return o;
    }
210650
function validatePaymentInputsAndOutputs(conn, payload, objAsset, message_index, objUnit, objValidationState, callback){
	var denomination = payload.denomination || 1;
	var arrAuthorAddresses = objUnit.authors.map(function(author) { return author.address; } );
	var arrInputAddresses = []; // used for non-transferrable assets only
	var arrOutputAddresses = [];
	var total_input = 0;
	if (payload.inputs.length > constants.MAX_INPUTS_PER_PAYMENT_MESSAGE)
		return callback("too many inputs");
	if (payload.outputs.length > constants.MAX_OUTPUTS_PER_PAYMENT_MESSAGE)
		return callback("too many outputs");
	
	if (objAsset && objAsset.fixed_denominations && payload.inputs.length !== 1)
		return callback("fixed denominations payment must have 1 input");

	var total_output = 0;
	var prev_address = ""; // if public, outputs must be sorted by address
	var prev_amount = 0;
	var count_open_outputs = 0;
	for (var i=0; i<payload.outputs.length; i++){
		var output = payload.outputs[i];
		if (hasFieldsExcept(output, ["address", "amount", "blinding", "output_hash"]))
			return callback("unknown fields in payment output");
		if (!isPositiveInteger(output.amount))
			return callback("amount must be positive integer, found "+output.amount);
		if (objAsset && objAsset.fixed_denominations && output.amount % denomination !== 0)
			return callback("output amount must be divisible by denomination");
		if (objAsset && objAsset.is_private){
			if (("output_hash" in output) !== !!objAsset.fixed_denominations)
				return callback("output_hash must be present with fixed denominations only");
			if ("output_hash" in output && !isStringOfLength(output.output_hash, constants.HASH_LENGTH))
				return callback("invalid output hash");
			if (!objAsset.fixed_denominations && !(("blinding" in output) && ("address" in output)))
				return callback("no blinding or address");
			if ("blinding" in output && !isStringOfLength(output.blinding, 16))
				return callback("bad blinding");
			if (("blinding" in output) !== ("address" in output))
				return callback("address and bilinding must come together");
			if ("address" in output && !ValidationUtils.isValidAddressAnyCase(output.address))
				return callback("output address "+output.address+" invalid");
			if (output.address)
				count_open_outputs++;
		}
		else{
			if ("blinding" in output)
				return callback("public output must not have blinding");
			if ("output_hash" in output)
				return callback("public output must not have output_hash");
			if (!ValidationUtils.isValidAddressAnyCase(output.address))
				return callback("output address "+output.address+" invalid");
			if (prev_address > output.address)
				return callback("output addresses not sorted");
			else if (prev_address === output.address && prev_amount > output.amount)
				return callback("output amounts for same address not sorted");
			prev_address = output.address;
			prev_amount = output.amount;
		}
		if (output.address && arrOutputAddresses.indexOf(output.address) === -1)
			arrOutputAddresses.push(output.address);
		total_output += output.amount;
	}
	if (objAsset && objAsset.is_private && count_open_outputs !== 1)
		return callback("found "+count_open_outputs+" open outputs, expected 1");

	var bIssue = false;
	// pow add
	var bCoinbase = false;

	
	// same for both public and private
	function validateIndivisibleIssue(input, cb){
	//	if (objAsset)
	//		profiler2.start();
		conn.query(
			"SELECT count_coins FROM asset_denominations WHERE asset=? AND denomination=?", 
			[payload.asset, denomination], 
			function(rows){
				if (rows.length === 0)
					return cb("invalid denomination: "+denomination);
				if (rows.length > 1)
					throw Error("more than one record per denomination?");
				var denomInfo = rows[0];
				if (denomInfo.count_coins === null){ // uncapped
					if (input.amount % denomination !== 0)
						return cb("issue amount must be multiple of denomination");
				}
				else{
					if (input.amount !== denomination * denomInfo.count_coins)
						return cb("wrong size of issue of denomination "+denomination);
				}
			//	if (objAsset)
			//		profiler2.stop('validateIndivisibleIssue');
				cb();
			}
		);
	}
	
	// max 1 issue must come first, then transfers, then hc, then witnessings
	// no particular sorting order within the groups
	async.forEachOfSeries(
		payload.inputs,
		function(input, input_index, cb){
			if (objAsset){
				if ("type" in input && input.type !== "issue")
					return cb("non-base input can have only type=issue");
			}
			else{
				if ("type" in input && !isNonemptyString(input.type))
					return cb("bad input type");
			}
			var type = input.type || "transfer";

			var doubleSpendFields = "unit, address, message_index, input_index, main_chain_index, sequence, is_stable";
			var doubleSpendWhere;
			var doubleSpendVars = [];

			function checkInputDoubleSpend(cb2){
			//	if (objAsset)
			//		profiler2.start();
				doubleSpendWhere += " AND unit != " + conn.escape(objUnit.unit);
				if (objAsset){
					doubleSpendWhere += " AND asset=?";
					doubleSpendVars.push(payload.asset);
				}
				else
					doubleSpendWhere += " AND asset IS NULL";
				var doubleSpendQuery = "SELECT "+doubleSpendFields+" FROM inputs JOIN units USING(unit) WHERE "+doubleSpendWhere;
				checkForDoublespends(
					conn, "divisible input", 
					doubleSpendQuery, doubleSpendVars, 
					objUnit, objValidationState, 
					function acceptDoublespends(cb3){
						// console.log("--- accepting doublespend on unit "+objUnit.unit);
						var sql = "UPDATE inputs SET is_unique=NULL WHERE "+doubleSpendWhere+
							" AND (SELECT is_stable FROM units WHERE units.unit=inputs.unit)=0";
						if (!(objAsset && objAsset.is_private)){
							objValidationState.arrAdditionalQueries.push({sql: sql, params: doubleSpendVars});
							objValidationState.arrDoubleSpendInputs.push({message_index: message_index, input_index: input_index});
							return cb3();
						}
						mutex.lock(["private_write"], function(unlock){
							// console.log("--- will ununique the conflicts of unit "+objUnit.unit);
							conn.query(
								sql, 
								doubleSpendVars, 
								function(){
									// console.log("--- ununique done unit "+objUnit.unit);
									objValidationState.arrDoubleSpendInputs.push({message_index: message_index, input_index: input_index});
									unlock();
									cb3();
								}
							);
						});
					}, 
					function onDone(err){
						if (err && objAsset && objAsset.is_private)
							throw Error("spend proof didn't help: "+err);
					//	if (objAsset)
					//		profiler2.stop('checkInputDoubleSpend');
						cb2(err);
					}
				);
			}

			switch (type){
				case "issue":
				//	if (objAsset)
				//		profiler2.start();
					if (input_index !== 0)
						return cb("issue must come first");
					if (hasFieldsExcept(input, ["type", "address", "amount", "serial_number"]))
						return cb("unknown fields in issue input");
					if (!isPositiveInteger(input.amount))
						return cb("amount must be positive");
					if (!isPositiveInteger(input.serial_number))
						return cb("serial_number must be positive");
					if (!objAsset || objAsset.cap){
						if (input.serial_number !== 1)
							return cb("for capped asset serial_number must be 1");
					}
					if (bIssue)
						return cb("only one issue per message allowed");
					bIssue = true;
					
					var address = null;
					if (arrAuthorAddresses.length === 1){
						if ("address" in input)
							return cb("when single-authored, must not put address in issue input");
						address = arrAuthorAddresses[0];
					}
					else{
						if (typeof input.address !== "string")
							return cb("when multi-authored, must put address in issue input");
						if (arrAuthorAddresses.indexOf(input.address) === -1)
							return cb("issue input address "+input.address+" is not an author");
						address = input.address;
					}
					
					arrInputAddresses = [address];
					if (objAsset){
						if (objAsset.cap && !objAsset.fixed_denominations && input.amount !== objAsset.cap)
							return cb("issue must be equal to cap");
					}
					else{
						if (!storage.isGenesisUnit(objUnit.unit))
							return cb("only genesis can issue base asset");
						if (input.amount !== constants.TOTAL_WHITEBYTES)
							return cb("issue must be equal to cap");
					}
					total_input += input.amount;
					
					var input_key = (payload.asset || "base") + "-" + denomination + "-" + address + "-" + input.serial_number;
					if (objValidationState.arrInputKeys.indexOf(input_key) >= 0)
						return callback("input "+input_key+" already used");
					objValidationState.arrInputKeys.push(input_key);
					doubleSpendWhere = "type='issue'";
					doubleSpendVars = [];
					if (objAsset && objAsset.fixed_denominations){
						doubleSpendWhere += " AND denomination=?";
						doubleSpendVars.push(denomination);
					}
					if (objAsset){
						doubleSpendWhere += " AND serial_number=?";
						doubleSpendVars.push(input.serial_number);
					}
					if (objAsset && !objAsset.issued_by_definer_only){
						doubleSpendWhere += " AND address=?";
						doubleSpendVars.push(address);
					}
				//	if (objAsset)
				//		profiler2.stop('validate issue');
					if (objAsset && objAsset.fixed_denominations){
						validateIndivisibleIssue(input, function(err){
							if (err)
								return cb(err);
							checkInputDoubleSpend(cb);
						});
					}
					else
						checkInputDoubleSpend(cb);
					// attestations and issued_by_definer_only already checked before
					break;
				// Pow add
				case "coinbase":
						if (input_index !== 0)
							return cb("coinbase must come first");
						if (hasFieldsExcept(input, ["type", "address", "amount"]))
							return cb("unknown fields in issue input");
						if (!isPositiveInteger(input.amount))
							return cb("amount must be positive");
						if (bCoinbase)
							return cb("only one coinbase per message allowed");
							bCoinbase = true;

						if (arrAuthorAddresses.length !== 1){
								return cb("coin base author must be one");
						}

						total_input += input.amount;
						// Check author come from n-2 round pow units authors
						if (objUnit.round_index === 1 )
							return cb("can not send coinbase unit in first round ");

						round.getWitnessesByRoundIndex(conn, objUnit.round_index -1,function (witnessesOFLastTwoRound){
							if(witnessesOFLastTwoRound.indexOf(objUnit.authors[0].address) === -1){
								return cb("coinbase unit author is invalid witness  ");
							}
							// Check duplicate coinbase unit in current round if exists(simialr to doublespend check)
							round.checkIfCoinBaseUnitByRoundIndexAndAddressExists(conn, objUnit.round_index, objUnit.authors[0].address,function(isExisted){
								if(isExisted){
									return cb("coinbase unit by each author can not sent more than once ");
								}
								// check amount is valid
								//if()
								round.getCoinbaseByRoundIndexAndAddress(conn,objUnit.round_index -1,objUnit.authors[0].address,
								function(commission){
									if (commission != input.amount){
										return cb("coinbase unit amount is incorrect ");
									}
									// coinbase unit can only consist of one message 
									if(objUnit.messages.length !== 1 )
										return cb("coinbase unit contains more than one mssage body, pls. check it ");
									 // two outputs for coinbase unit: one is for author self ,the other is for foundation
									if(payload.outputs.length !== 2 )
										return cb("coinbase units must have two outputs");
									var founddation_outputs= payload.outputs.filter(function(output) {return output.address == constants.FOUNDATION_ADDRESS });
									if(founddation_outputs.length !== 1)
										return cb("moe than one outputs to foundation address occured");
									var coinbase_foundation_amount = Math.floor(input.amount * constants.FOUNDATION_RATIO);
									if(founddation_outputs[0].amount !== coinbase_foundation_amount )
										return cb("foundation share is incoorect in coinbase unit Expected: "+ coinbase_foundation_amount + "Actual :" + founddation_outputs[0].amount);
									return cb();
								});
							});
						})
						break;

				case "transfer":
					if (hasFieldsExcept(input, ["type", "unit", "message_index", "output_index"]))
						return cb("unknown fields in payment input");
					if (!isStringOfLength(input.unit, constants.HASH_LENGTH))
						return cb("wrong unit length in payment input");
					if (!isNonnegativeInteger(input.message_index))
						return cb("no message_index in payment input");
					if (!isNonnegativeInteger(input.output_index))
						return cb("no output_index in payment input");
					
					var input_key = (payload.asset || "base") + "-" + input.unit + "-" + input.message_index + "-" + input.output_index;
					if (objValidationState.arrInputKeys.indexOf(input_key) >= 0)
						return cb("input "+input_key+" already used");
					objValidationState.arrInputKeys.push(input_key);
					
					doubleSpendWhere = "type=? AND src_unit=? AND src_message_index=? AND src_output_index=?";
					doubleSpendVars = [type, input.unit, input.message_index, input.output_index];
					
					// for private fixed denominations assets, we can't look up src output in the database 
					// because we validate the entire chain before saving anything.
					// Instead we prepopulate objValidationState with denomination and src_output 
					if (objAsset && objAsset.is_private && objAsset.fixed_denominations){
						if (!objValidationState.src_coin)
							throw Error("no src_coin");
						var src_coin = objValidationState.src_coin;
						if (!src_coin.src_output)
							throw Error("no src_output");
						if (!isPositiveInteger(src_coin.denomination))
							throw Error("no denomination in src coin");
						if (!isPositiveInteger(src_coin.amount))
							throw Error("no src coin amount");
						var owner_address = src_coin.src_output.address;
						if (arrAuthorAddresses.indexOf(owner_address) === -1)
							return cb("output owner is not among authors");
						if (denomination !== src_coin.denomination)
							return cb("private denomination mismatch");
						if (objAsset.auto_destroy && owner_address === objAsset.definer_address)
							return cb("this output was destroyed by sending to definer address");
						if (objAsset.spender_attested && objAsset.arrAttestedAddresses.indexOf(owner_address) === -1)
							return cb("owner address is not attested");
						if (arrInputAddresses.indexOf(owner_address) === -1)
							arrInputAddresses.push(owner_address);
						total_input += src_coin.amount;
						// console.log("-- val state "+JSON.stringify(objValidationState));
					//	if (objAsset)
					//		profiler2.stop('validate transfer');
						return checkInputDoubleSpend(cb);
					}
					
					conn.query(
						"SELECT amount, is_stable, sequence, address, main_chain_index, denomination, asset \n\
						FROM outputs \n\
						JOIN units USING(unit) \n\
						WHERE outputs.unit=? AND message_index=? AND output_index=?",
						[input.unit, input.message_index, input.output_index],
						function(rows){
							if (rows.length > 1)
								throw Error("more than 1 src output");
							if (rows.length === 0)
								return cb("input unit "+input.unit+" not found");
							var src_output = rows[0];
							if (typeof src_output.amount !== 'number')
								throw Error("src output amount is not a number");
							if (!(!payload.asset && !src_output.asset || payload.asset === src_output.asset))
								return cb("asset mismatch");
							//if (src_output.is_stable !== 1) // we allow immediate spends, that's why the error is transient
							//    return cb(createTransientError("input unit is not on stable MC yet, unit "+objUnit.unit+", input "+input.unit));
							if (!objAsset || !objAsset.is_private){
								// for public payments, you can't spend unconfirmed transactions
								if (src_output.main_chain_index > objValidationState.last_ball_mci || src_output.main_chain_index === null)
									return cb("src output must be before last ball");
							}
							if (src_output.sequence !== 'good') // it is also stable or private
								return cb("input unit "+input.unit+" is not serial");
							var owner_address = src_output.address;
							if (arrAuthorAddresses.indexOf(owner_address) === -1)
								return cb("output owner is not among authors");
							if (denomination !== src_output.denomination)
								return cb("denomination mismatch");
							if (objAsset && objAsset.auto_destroy && owner_address === objAsset.definer_address)
								return cb("this output was destroyed by sending it to definer address");
							if (objAsset && objAsset.spender_attested && objAsset.arrAttestedAddresses.indexOf(owner_address) === -1)
								return cb("owner address is not attested");
							if (arrInputAddresses.indexOf(owner_address) === -1)
								arrInputAddresses.push(owner_address);
							total_input += src_output.amount;
							
							if (!objAsset || !objAsset.is_private)
								return checkInputDoubleSpend(checkDepositAddressSpend);
							// for private payments only, unit already saved (if public, we are already before last ball)
							// when divisible, the asset is also non-transferrable and auto-destroy, 
							// then this transfer is a transfer back to the issuer 
							// and input.unit is known both to payer and the payee (issuer), even if light
							graph.determineIfIncluded(conn, input.unit, [objUnit.unit], function(bIncluded){
								if (!bIncluded)
									return cb("input "+input.unit+" is not in your genes");
								checkInputDoubleSpend(checkDepositAddressSpend);
							});
							
						    // Deposit add : if owner_address is deposit address , additional check if user has rights to spend it now.
							 function checkDepositAddressSpend(){
								if (objUnit.authors.length !== 2)
									return cb();	
									
								// console.log("===================Start to check spend deposit balance");
								var supernodes = objUnit.authors.filter( function (author) { return author.address != owner_address });
								var coAuthorAddr = supernodes[0].address ;
								// Check owner address is kind of deposit address  
								// console.log("===================coAuthorAddr: "+ coAuthorAddr +" | owner_address: " +owner_address);
								deposit.getSupernodeByDepositAddress(conn, owner_address, function(err, supernodeinfo){
									if(err){
										// no correspont supernode which indicates owner_address is not deposit address
										return cb();
									}
									// console.log("===================Deposit address: " + owner_address + "  supernode address: "+ supernodeinfo[0].address);
									// owner_address is deposit address
									deposit.hasInvalidUnitsFromHistory(conn, supernodeinfo[0].address, function (err, isInvalid){
										if(err) //normal tranaction
											return cb(err);
										
										round.getLastCoinbaseUnitRoundIndex(conn, supernodeinfo[0].address, function(err, lastCoinBaseRound){
											if(err)
												return cb(err);
											// console.log("===================got last coin base round is : "+ lastCoinBaseRound);
											round.getCurrentRoundIndex(conn, function(latestRoundIndex){
												if (constants.FOUNDATION_SAFE_ADDRESS === coAuthorAddr){ // foundation spend deposit condition
													if(!isInvalid) // supernode is good condition
														return cb("supernode [" + supernodeinfo[0].address + "] don not submit bad joints, Foundation can not spend its deposit balance ");
													if(lastCoinBaseRound === 0 ) // never participate in minning and no coinbase  record
														return cb("supernode [" + supernodeinfo[0].address + "] don not submit coinbase unit,  Foundation can not spend its deposit balance ");
													
													// console.log("===================got current  round is : "+ latestRoundIndex);
													// check if delay n round to spend 
													if((latestRoundIndex - lastCoinBaseRound) < constants.COUNT_ROUNDS_FOR_FOUNDATION_SPEND_DEPOSIT){
														return cb("Foundation safe address can not spend deposit contract balance before ")
													}
													return cb(); // OK condition
												}
												else if(coAuthorAddr === supernodeinfo[0].safe_address){ // condition for supernode spend the deposit balance
													if(lastCoinBaseRound === 0 ) // not mine at all, take it anytime
														return cb();
													if(isInvalid)
														return cb("supernode [" + supernodeinfo[0].address + "] submit bad joints, can not spend its deposit balance ");
													
													// console.log("===================got current  round is : "+ latestRoundIndex);
													if((latestRoundIndex - lastCoinBaseRound) < constants.COUNT_ROUNDS_FOR_SUPERNODE_SPEND_DEPOSIT){
														return cb("supernode can not spend deposit contract balance before round " + (lastCoinBaseRound + constants.COUNT_ROUNDS_FOR_SUPERNODE_SPEND_DEPOSIT));
													}

													// console.log("===================OK to spend deposit balance");
													return cb();  // OK condition
												}
												return cb("unknown user:" + coAuthorAddr +" try to spend deposit :" + owner_address );
											});
										});
										
									});		
								});
							}
						});
					break;
				default:
					return cb("unrecognized input type: "+input.type);
			}
		},
		function(err){ // async.forEachOfSeries callback
			// console.log("inputs done "+payload.asset, arrInputAddresses, arrOutputAddresses);
			if (err)
				return callback(err);
			if (objAsset){
				if (total_input !== total_output)
					return callback("inputs and outputs do not balance: "+total_input+" !== "+total_output);
				if (!objAsset.is_transferrable){ // the condition holds for issues too
					if (arrInputAddresses.length === 1 && arrInputAddresses[0] === objAsset.definer_address
					   || arrOutputAddresses.length === 1 && arrOutputAddresses[0] === objAsset.definer_address
						// sending payment to the definer and the change back to oneself
					   || !(objAsset.fixed_denominations && objAsset.is_private) 
							&& arrInputAddresses.length === 1 && arrOutputAddresses.length === 2 
							&& arrOutputAddresses.indexOf(objAsset.definer_address) >= 0
							&& arrOutputAddresses.indexOf(arrInputAddresses[0]) >= 0
					   ){
						// good
					}
					else
						return callback("the asset is not transferrable");
				}
				var arrCondition = bIssue ? objAsset.issue_condition : objAsset.transfer_condition;
				if (arrCondition){
					Definition.evaluateAssetCondition(
						conn, payload.asset, arrCondition, objUnit, objValidationState, 
						function(cond_err, bSatisfiesCondition){
							if (cond_err)
								return callback(cond_err);
							if (!bSatisfiesCondition)
								return callback("transfer or issue condition not satisfied");
							console.log("validatePaymentInputsAndOutputs with transfer/issue conditions done");
							callback();
						}
					);
					return;
				}
			}
			else{ // base asset
				if (total_input !== total_output + objUnit.headers_commission + objUnit.payload_commission)
					return callback("inputs and outputs do not balance: "+total_input+" !== "+total_output+" + "+objUnit.headers_commission+" + "+objUnit.payload_commission);
			}
			console.log("validatePaymentInputsAndOutputs done");
		//	if (objAsset)
		//		profiler2.stop('validate IO');
			callback();
		}
	);
}
1033073
@Override
  public final boolean isValid(final String pvalue, final ConstraintValidatorContext pcontext) {
    if (StringUtils.isEmpty(pvalue)) {
      return true;
    }
    if (pvalue.length() > LENGTH_CREDIT_CARDNUMBER) {
      // credit card number is to long, but that's handled by size annotation
      return true;
    }
    return CHECK_CREDIT_CARD.isValid(pvalue);
  }
628498
function validateLength(attr, conf, err) {
    if (nullCheck.call(this, attr, conf, err)) return;

    var len = this[attr].length;
    if (conf.min && len < conf.min) {
        err('min');
    }
    if (conf.max && len > conf.max) {
        err('max');
    }
    if (conf.is && len !== conf.is) {
        err('is');
    }
}
902128
function pre_confirmation_check() {
    global $db, $messageStack;

    include(DIR_WS_CLASSES . 'cc_validation.php');

    $cc_validation = new cc_validation();
    $result = $cc_validation->validate($_POST['linkpoint_api_cc_number'], $_POST['linkpoint_api_cc_expires_month'], $_POST['linkpoint_api_cc_expires_year']);
    $error = '';
    switch ($result) {
      case -1:
        $error = sprintf(TEXT_CCVAL_ERROR_UNKNOWN_CARD, substr($cc_validation->cc_number, 0, 4));
        break;
      case -2:
      case -3:
      case -4:
        $error = TEXT_CCVAL_ERROR_INVALID_DATE;
        break;
      case false:
        $error = TEXT_CCVAL_ERROR_INVALID_NUMBER;
        break;
    }

    // save record of errors which occur during checkout_payment validation phase but haven't been sent to gateway yet
    if ( ($result == false) || ($result < 1) ) {
      $payment_error_return = 'payment_error=' . $this->code ;
      $error_info2 = '&error=' . urlencode($error) . '&linkpoint_api_cc_owner=' . urlencode($_POST['linkpoint_api_cc_owner']) . '&linkpoint_api_cc_expires_month=' . $_POST['linkpoint_api_cc_expires_month'] . '&linkpoint_api_cc_expires_year=' . $_POST['linkpoint_api_cc_expires_year'];
      $messageStack->add_session('checkout_payment', $error . '<!-- ['.$this->code.'] -->', 'error');

      if (MODULE_PAYMENT_LINKPOINT_API_STORE_DATA == 'True') {
        $cc_type = $cc_validation->cc_type;
        $cc_number_clean = $cc_validation->cc_number;
        $cc_expiry_month = $_POST['linkpoint_api_cc_expires_month'];
        $cc_expiry_year = $_POST['linkpoint_api_cc_expires_year'];
        $error_returned = $payment_error_return . $error_info2;

        $cc_number = (strlen($cc_number_clean) > 8) ? substr($cc_number_clean, 0, 4) . str_repeat('X', (strlen($cc_number_clean) - 8)) . substr($cc_number_clean, -4) : substr($cc_number_clean, 0, 3) . '**short**';

        while (strstr($error_returned, '%3A')) $error_returned = str_replace('%3A', ' ', $error_returned);
        while (strstr($error_returned, '%2C')) $error_returned = str_replace('%2C', ' ', $error_returned);
        while (strstr($error_returned, '+')) $error_returned = str_replace('+', ' ', $error_returned);
        $error_returned = str_replace('&', ' &amp;', $error_returned);
        $cust_info =  $error_returned;

        $message = addslashes($message);
        $cust_info = addslashes($cust_info);
        $all_response_info = addslashes($all_response_info);


        //  Store Transaction history in Database
        $sql_data_array= array(array('fieldName'=>'lp_trans_num', 'value'=>'', 'type'=>'string'),
                               array('fieldName'=>'order_id', 'value'=>0, 'type'=>'integer'),
                               array('fieldName'=>'approval_code', 'value'=>'N/A', 'type'=>'string'),
                               array('fieldName'=>'transaction_response_time', 'value'=>'N/A', 'type'=>'string'),
                               array('fieldName'=>'r_error', 'value'=>'**CC Info Failed Validation during pre-processing**', 'type'=>'string'),
                               array('fieldName'=>'customer_id', 'value'=>$_SESSION['customer_id'] , 'type'=>'integer'),
                               array('fieldName'=>'avs_response', 'value'=>'', 'type'=>'string'),
                               array('fieldName'=>'transaction_result', 'value'=>'*CUSTOMER ERROR*', 'type'=>'string'),
                               array('fieldName'=>'message', 'value'=>$message . ' -- ' . $all_response_info, 'type'=>'string'),
                               array('fieldName'=>'transaction_time', 'value'=>time(), 'type'=>'string'),
                               array('fieldName'=>'transaction_reference_number', 'value'=>'', 'type'=>'string'),
                               array('fieldName'=>'fraud_score', 'value'=>0, 'type'=>'integer'),
                               array('fieldName'=>'cc_number', 'value'=>$cc_number, 'type'=>'string'),
                               array('fieldName'=>'cust_info', 'value'=>$cust_info, 'type'=>'string'),
                               array('fieldName'=>'chargetotal', 'value'=>0, 'type'=>'string'),
                               array('fieldName'=>'cc_expire', 'value'=>$cc_month . '/' . $cc_year, 'type'=>'string'),
                               array('fieldName'=>'ordertype', 'value'=>'N/A', 'type'=>'string'),
                               array('fieldName'=>'date_added', 'value'=>'now()', 'type'=>'noquotestring'));
        $db->perform(TABLE_LINKPOINT_API, $sql_data_array);
      }
      zen_redirect(zen_href_link(FILENAME_CHECKOUT_PAYMENT, '', 'SSL', true, false));
    }

    // if no error, continue with validated data:
    $this->cc_card_type = $cc_validation->cc_type;
    $this->cc_card_number = $cc_validation->cc_number;
    $this->cc_expiry_month = $cc_validation->cc_expiry_month;
    $this->cc_expiry_year = $cc_validation->cc_expiry_year;
  }
678349
def validate_v_rgb(value):
    """"""
    if len(value) != 6:
        raise vol.Invalid(
            '{} is not six characters long'.format(value))
    return validate_hex(value)
830179
function maskProps(obj, props, maskCreditCards = true, isHeaders = false) {
  return mapValues(obj, (val, key) => {
    if (isObject(val)) return maskProps(val, props, maskCreditCards, isHeaders);
    if (!isString(val)) return val;
    // if it was a credit card then replace all digits with asterisk
    if (!isHeaders && maskCreditCards && isCreditCard(val))
      return val.replace(/[^\D\s]/g, '*');
    if (!props.includes(key)) return val;
    // replace only the authentication <credentials> portion with asterisk
    // Authorization: <type> <credentials>
    if (isHeaders && key === 'Authorization')
      return `${val.split(' ')[0]} ${val
        .substring(val.indexOf(' ') + 1)
        .replace(/./g, '*')}`;
    return val.replace(/./g, '*');
  });
}