diff --git a/README.md b/README.md index e8b7aedd9..647f6d6a4 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ Validator | Description **isBefore(str [, options])** | check if the string is a date that is before the specified date.

`options` is an object that defaults to `{ comparisonDate: Date().toString() }`.

**Options:**
`comparisonDate`: Date to compare to. Defaults to `Date().toString()` (now). **isBIC(str)** | check if the string is a BIC (Bank Identification Code) or SWIFT code. **isBoolean(str [, options])** | check if the string is a boolean.
`options` is an object which defaults to `{ loose: false }`. If `loose` is set to false, the validator will strictly match ['true', 'false', '0', '1']. If `loose` is set to true, the validator will also match 'yes', 'no', and will match a valid boolean string of any case. (e.g.: ['true', 'True', 'TRUE']). -**isBtcAddress(str)** | check if the string is a valid BTC address. +**isBtcAddress(str)** | check if the string is a valid BTC address. Verifies the base58check or bech32/bech32m checksum. **isByteLength(str [, options])** | check if the string's length (in UTF-8 bytes) falls in a range.

`options` is an object which defaults to `{ min: 0, max: undefined }`. **isCreditCard(str [, options])** | check if the string is a credit card number.

`options` is an optional object that can be supplied with the following key(s): `provider` is an optional key whose value should be a string, and defines the company issuing the credit card. Valid values include `['amex', 'dinersclub', 'discover', 'jcb', 'mastercard', 'unionpay', 'visa']` or blank will check for any provider. **isCurrency(str [, options])** | check if the string is a valid currency amount.

`options` is an object which defaults to `{ symbol: '$', require_symbol: false, allow_space_after_symbol: false, symbol_after_digits: false, allow_negatives: true, parens_for_negatives: false, negative_sign_before_digits: false, negative_sign_after_digits: false, allow_negative_sign_placeholder: false, thousands_separator: ',', decimal_separator: '.', allow_decimal: true, require_decimal: false, digits_after_decimal: [2], allow_space_after_digits: false }`.
**Note:** The array `digits_after_decimal` is filled with the exact number of digits allowed not a range, for example a range 1 to 3 will be given as [1, 2, 3]. diff --git a/src/lib/isBtcAddress.js b/src/lib/isBtcAddress.js index 1a309e682..64bc3d158 100644 --- a/src/lib/isBtcAddress.js +++ b/src/lib/isBtcAddress.js @@ -3,7 +3,230 @@ import assertString from './util/assertString'; const bech32 = /^(bc1|tb1|bc1p|tb1p)[ac-hj-np-z02-9]{39,58}$/; const base58 = /^(1|2|3|m)[A-HJ-NP-Za-km-z1-9]{25,39}$/; +// BIP-173 / BIP-350. `1` is the separator and is not part of the data alphabet. +const BECH32_CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'; +const BECH32_GENERATOR = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +const BECH32M_CONST = 0x2bc830a3; + +const BASE58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +// SHA-256 round constants. Checksum math is bitwise by specification. +/* eslint-disable no-bitwise */ +const SHA256_K = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, + 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, + 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]; + +function rotr(x, n) { + return ((x >>> n) | (x << (32 - n))) >>> 0; +} + +function sha256(message) { + const hash = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]; + const bitLength = message.length * 8; + const padded = message.slice(); + padded.push(0x80); + while ((padded.length % 64) !== 56) { + padded.push(0); + } + padded.push(0, 0, 0, 0); + padded.push((bitLength >>> 24) & 0xff); + padded.push((bitLength >>> 16) & 0xff); + padded.push((bitLength >>> 8) & 0xff); + padded.push(bitLength & 0xff); + + const words = new Array(64); + for (let offset = 0; offset < padded.length; offset += 64) { + for (let t = 0; t < 16; t++) { + const i = offset + (t * 4); + words[t] = ( + (padded[i] << 24) | + (padded[i + 1] << 16) | + (padded[i + 2] << 8) | + padded[i + 3] + ) >>> 0; + } + for (let t = 16; t < 64; t++) { + const s0 = ( + rotr(words[t - 15], 7) ^ rotr(words[t - 15], 18) ^ (words[t - 15] >>> 3) + ) >>> 0; + const s1 = ( + rotr(words[t - 2], 17) ^ rotr(words[t - 2], 19) ^ (words[t - 2] >>> 10) + ) >>> 0; + words[t] = (words[t - 16] + s0 + words[t - 7] + s1) >>> 0; + } + + let a = hash[0]; + let b = hash[1]; + let c = hash[2]; + let d = hash[3]; + let e = hash[4]; + let f = hash[5]; + let g = hash[6]; + let h = hash[7]; + for (let t = 0; t < 64; t++) { + const s1 = (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) >>> 0; + const ch = ((e & f) ^ ((~e) & g)) >>> 0; + const temp1 = (h + s1 + ch + SHA256_K[t] + words[t]) >>> 0; + const s0 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) >>> 0; + const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0; + const temp2 = (s0 + maj) >>> 0; + h = g; + g = f; + f = e; + e = (d + temp1) >>> 0; + d = c; + c = b; + b = a; + a = (temp1 + temp2) >>> 0; + } + hash[0] = (hash[0] + a) >>> 0; + hash[1] = (hash[1] + b) >>> 0; + hash[2] = (hash[2] + c) >>> 0; + hash[3] = (hash[3] + d) >>> 0; + hash[4] = (hash[4] + e) >>> 0; + hash[5] = (hash[5] + f) >>> 0; + hash[6] = (hash[6] + g) >>> 0; + hash[7] = (hash[7] + h) >>> 0; + } + + const out = []; + for (let i = 0; i < 8; i++) { + out.push((hash[i] >>> 24) & 0xff); + out.push((hash[i] >>> 16) & 0xff); + out.push((hash[i] >>> 8) & 0xff); + out.push(hash[i] & 0xff); + } + return out; +} + +function decodeBase58(str) { + const digits = [0]; + for (let i = 0; i < str.length; i++) { + let carry = BASE58_ALPHABET.indexOf(str[i]); + if (carry === -1) { + return null; + } + for (let j = 0; j < digits.length; j++) { + carry += digits[j] * 58; + digits[j] = carry % 256; + carry = Math.floor(carry / 256); + } + while (carry > 0) { + digits.push(carry % 256); + carry = Math.floor(carry / 256); + } + } + + let zeros = 0; + while (zeros < str.length && str[zeros] === '1') { + zeros += 1; + } + let high = digits.length - 1; + while (high > 0 && digits[high] === 0) { + high -= 1; + } + const decoded = []; + for (let i = 0; i < zeros; i++) { + decoded.push(0); + } + for (let i = high; i >= 0; i--) { + decoded.push(digits[i]); + } + return decoded; +} + +function hasValidBase58Check(str) { + const decoded = decodeBase58(str); + if (!decoded || decoded.length < 5) { + return false; + } + const payload = decoded.slice(0, -4); + const checksum = decoded.slice(-4); + const hash = sha256(sha256(payload)); + for (let i = 0; i < 4; i++) { + if (hash[i] !== checksum[i]) { + return false; + } + } + return true; +} + +function bech32Polymod(values) { + let chk = 1; + for (let i = 0; i < values.length; i++) { + const top = chk >>> 25; + chk = ((chk & 0x1ffffff) << 5) ^ values[i]; + for (let j = 0; j < 5; j++) { + if (((top >>> j) & 1) !== 0) { + chk ^= BECH32_GENERATOR[j]; + } + } + } + return chk >>> 0; +} + +function hasValidBech32Checksum(address) { + const separator = address.lastIndexOf('1'); + const hrp = address.slice(0, separator); + const dataPart = address.slice(separator + 1); + const data = []; + for (let i = 0; i < dataPart.length; i++) { + const value = BECH32_CHARSET.indexOf(dataPart[i]); + if (value === -1) { + return false; + } + data.push(value); + } + if (data.length === 0) { + return false; + } + + const expanded = []; + for (let i = 0; i < hrp.length; i++) { + expanded.push(hrp.charCodeAt(i) >>> 5); + } + expanded.push(0); + for (let i = 0; i < hrp.length; i++) { + expanded.push(hrp.charCodeAt(i) & 31); + } + for (let i = 0; i < data.length; i++) { + expanded.push(data[i]); + } + + const spec = bech32Polymod(expanded); + const version = data[0]; + if (version === 0) { + return spec === 1; + } + return version >= 1 && version <= 16 && spec === BECH32M_CONST; +} +/* eslint-enable no-bitwise */ + export default function isBtcAddress(str) { assertString(str); - return bech32.test(str) || base58.test(str); + if (bech32.test(str)) { + return hasValidBech32Checksum(str); + } + if (base58.test(str)) { + return hasValidBase58Check(str); + } + return false; } diff --git a/test/validators.test.js b/test/validators.test.js index 98d2a12ff..f68427a67 100644 --- a/test/validators.test.js +++ b/test/validators.test.js @@ -12244,15 +12244,22 @@ describe('Validators', () => { '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy', '2NFUBBRcTJbYc1D4HSCbJhKZp6YCV4PQFpQ', 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq', - '14qViLJfdGaP4EeHnDyJbEGQysnCpwk3gd', '35bSzXvRKLpHsHMrzb82f617cV4Srnt7hS', - '17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhemt', + '17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhem', + '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa', 'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4', 'tb1qxhkl607frtvjsy9nlyeg03lf6fsq947pl2pe82', 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3297', 'tb1pzpelffrdh9ptpaqnurwx30dlewqv57rcxfeetp86hsssk30p4cws38tr9y', ], invalid: [ + '14qViLJfdGaP4EeHnDyJbEGQysnCpwk3gd', + '17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhemt', + 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdr', + '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNb', + '3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLz', + 'tb1qxhkl607frtvjsy9nlyeg03lf6fsq947pl2pe83', + 'bc1pqd7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3297', '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNL0', '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNLo', '3J98t1WpEZ73CNmQviecrnyiWrnqh0WNLI',