diff --git a/README.md b/README.md
index e8b7aedd9..e889816a1 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. Validates base58check and bech32/bech32m checksums.
**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..562a0729f 100644
--- a/src/lib/isBtcAddress.js
+++ b/src/lib/isBtcAddress.js
@@ -1,9 +1,119 @@
+/* eslint-disable no-bitwise */
+
import assertString from './util/assertString';
+import sha256 from './util/sha256';
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}$/;
+const bech32Charset = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
+const bech32Generators = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
+const bech32mConstant = 0x2bc830a3;
+const base58Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+const validBase58Versions = [0x00, 0x05, 0x6f, 0xc4];
+
+function bech32Polymod(values) {
+ let checksum = 1;
+
+ values.forEach((value) => {
+ const top = checksum >>> 25;
+ checksum = ((checksum & 0x1ffffff) << 5) ^ value;
+
+ for (let i = 0; i < 5; i++) {
+ if ((top >>> i) & 1) {
+ checksum ^= bech32Generators[i];
+ }
+ }
+ });
+
+ return checksum;
+}
+
+function bech32HrpExpand(hrp) {
+ 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);
+ }
+
+ return expanded;
+}
+
+function isValidBech32Address(str) {
+ const hrp = str.slice(0, 2);
+ const data = str.slice(3).split('').map(char => bech32Charset.indexOf(char));
+
+ if (data[0] > 16) {
+ return false;
+ }
+
+ const checksum = bech32Polymod(bech32HrpExpand(hrp).concat(data));
+ return data[0] === 0 ? checksum === 1 : checksum === bech32mConstant;
+}
+
+function decodeBase58(str) {
+ const bytes = [0];
+
+ for (let i = 0; i < str.length; i++) {
+ let carry = base58Alphabet.indexOf(str[i]);
+
+ for (let j = 0; j < bytes.length; j++) {
+ carry += bytes[j] * 58;
+ bytes[j] = carry & 0xff;
+ carry >>= 8;
+ }
+
+ while (carry > 0) {
+ bytes.push(carry & 0xff);
+ carry >>= 8;
+ }
+ }
+
+ let leadingZeroes = 0;
+ while (str[leadingZeroes] === '1') {
+ leadingZeroes += 1;
+ }
+
+ const decoded = [];
+ for (let i = 0; i < leadingZeroes; i++) {
+ decoded.push(0);
+ }
+ for (let i = bytes.length - 1; i >= 0; i--) {
+ decoded.push(bytes[i]);
+ }
+
+ return decoded;
+}
+
+function isValidBase58CheckAddress(str) {
+ const decoded = decodeBase58(str);
+
+ if (decoded.length !== 25 || validBase58Versions.indexOf(decoded[0]) === -1) {
+ return false;
+ }
+
+ const checksum = sha256(sha256(decoded.slice(0, 21)));
+ for (let i = 0; i < 4; i++) {
+ if (decoded[21 + i] !== checksum[i]) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
export default function isBtcAddress(str) {
assertString(str);
- return bech32.test(str) || base58.test(str);
+
+ if (bech32.test(str)) {
+ return isValidBech32Address(str);
+ }
+ if (base58.test(str)) {
+ return isValidBase58CheckAddress(str);
+ }
+ return false;
}
diff --git a/src/lib/util/sha256.js b/src/lib/util/sha256.js
new file mode 100644
index 000000000..765f7fbff
--- /dev/null
+++ b/src/lib/util/sha256.js
@@ -0,0 +1,116 @@
+/* eslint-disable no-bitwise */
+
+const initialHash = [
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+ 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
+];
+
+const roundConstants = [
+ 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 rotateRight(value, bits) {
+ return (value >>> bits) | (value << (32 - bits));
+}
+
+export default function sha256(bytes) {
+ const message = bytes.slice();
+ const bitLength = bytes.length * 8;
+ const bitLengthHigh = Math.floor(bitLength / 0x100000000);
+ const bitLengthLow = bitLength >>> 0;
+
+ message.push(0x80);
+ while (message.length % 64 !== 56) {
+ message.push(0);
+ }
+
+ for (let i = 24; i >= 0; i -= 8) {
+ message.push((bitLengthHigh >>> i) & 0xff);
+ }
+ for (let i = 24; i >= 0; i -= 8) {
+ message.push((bitLengthLow >>> i) & 0xff);
+ }
+
+ const hash = initialHash.slice();
+ const words = new Array(64);
+
+ for (let block = 0; block < message.length; block += 64) {
+ for (let i = 0; i < 16; i++) {
+ const offset = block + (i * 4);
+ words[i] = (message[offset] << 24)
+ | (message[offset + 1] << 16)
+ | (message[offset + 2] << 8)
+ | message[offset + 3];
+ }
+
+ for (let i = 16; i < 64; i++) {
+ const sigma0 = rotateRight(words[i - 15], 7)
+ ^ rotateRight(words[i - 15], 18)
+ ^ (words[i - 15] >>> 3);
+ const sigma1 = rotateRight(words[i - 2], 17)
+ ^ rotateRight(words[i - 2], 19)
+ ^ (words[i - 2] >>> 10);
+ words[i] = (words[i - 16] + sigma0 + words[i - 7] + sigma1) | 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 i = 0; i < 64; i++) {
+ const sigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
+ const choice = (e & f) ^ ((~e) & g);
+ const temp1 = (h + sigma1 + choice + roundConstants[i] + words[i]) | 0;
+ const sigma0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
+ const majority = (a & b) ^ (a & c) ^ (b & c);
+ const temp2 = (sigma0 + majority) | 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 result = [];
+ hash.forEach((word) => {
+ for (let i = 24; i >= 0; i -= 8) {
+ result.push((word >>> i) & 0xff);
+ }
+ });
+
+ return result;
+}
diff --git a/test/validators.test.js b/test/validators.test.js
index 98d2a12ff..917fa8522 100644
--- a/test/validators.test.js
+++ b/test/validators.test.js
@@ -12244,9 +12244,9 @@ describe('Validators', () => {
'3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy',
'2NFUBBRcTJbYc1D4HSCbJhKZp6YCV4PQFpQ',
'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq',
- '14qViLJfdGaP4EeHnDyJbEGQysnCpwk3gd',
+ '14qViLJfdGaP4EeHnDyJbEGQysnCpwn1gZ',
'35bSzXvRKLpHsHMrzb82f617cV4Srnt7hS',
- '17VZNX1SN5NtKa8UQFxwQbFeFc3iqRYhemt',
+ '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
'bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4',
'tb1qxhkl607frtvjsy9nlyeg03lf6fsq947pl2pe82',
'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3297',
@@ -12261,6 +12261,8 @@ describe('Validators', () => {
'0x56F0B8A998425c53c75C4A303D4eF987533c5597',
'pp8skudq3x5hzw8ew7vzsw8tn4k8wxsqsv0lt0mf3g',
'17VZNX1SN5NlKa8UQFxwQbFeFc3iqRYhem',
+ '11111111111111111111111111',
+ 'mCpJBmKn7DBzrEfhjKLAxS3NBZvYEFv2u',
'BC1QW508D6QEJXTDG4Y5R3ZARVAYR0C5XW7KV8F3T4',
'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3291',
'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg329b',
@@ -12268,6 +12270,10 @@ describe('Validators', () => {
'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg329o',
'BC1P5D7RJQ7G6RDK2YHZKS9SMLAQTEDR4DEKQ08GE8ZTWAC72SFR9RUSXG3297',
'TB1PZPELFFRDH9PTPAQNURWX30DLEWQV57RCXFEETP86HSSSK30P4CWS38TR9Y',
+ 'bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdr',
+ 'bc13qqqsyqcyq5rqwzqfpg9scrgwpugpzysnlzezjf',
+ 'bc1p5d7rjq7g6rdk2yhzks9smlaqtedr4dekq08ge8ztwac72sfr9rusxg3298',
+ '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNb',
],
});
});