UNPKG

multicoin-address-validator-ts

Version:

Multicoin address validator for Bitcoin and other Altcoins. TS version

52 lines (51 loc) 2.71 kB
"use strict"; var cryptoUtils = require('./crypto/utils'); // from https://github.com/paritytech/substrate/wiki/External-Address-Format-(SS58) var addressFormats = [ { addressLength: 3, accountIndexLength: 1, checkSumLength: 1 }, { addressLength: 4, accountIndexLength: 2, checkSumLength: 1 }, { addressLength: 5, accountIndexLength: 2, checkSumLength: 2 }, { addressLength: 6, accountIndexLength: 4, checkSumLength: 1 }, { addressLength: 7, accountIndexLength: 4, checkSumLength: 2 }, { addressLength: 8, accountIndexLength: 4, checkSumLength: 3 }, { addressLength: 9, accountIndexLength: 4, checkSumLength: 4 }, { addressLength: 10, accountIndexLength: 8, checkSumLength: 1 }, { addressLength: 11, accountIndexLength: 8, checkSumLength: 2 }, { addressLength: 12, accountIndexLength: 8, checkSumLength: 3 }, { addressLength: 13, accountIndexLength: 8, checkSumLength: 4 }, { addressLength: 14, accountIndexLength: 8, checkSumLength: 5 }, { addressLength: 15, accountIndexLength: 8, checkSumLength: 6 }, { addressLength: 16, accountIndexLength: 8, checkSumLength: 7 }, { addressLength: 17, accountIndexLength: 8, checkSumLength: 8 }, { addressLength: 34, accountIndexLength: 32, checkSumLength: 2 }, ]; module.exports = { isValidAddress: function (address, currency, opts) { if (opts === void 0) { opts = {}; } var _a = opts.networkType, networkType = _a === void 0 ? 'prod' : _a; return this.verifyChecksum(address); }, verifyChecksum: function (address) { try { var preImage = '53533538505245'; var decoded = cryptoUtils.base58(address); var addressType = cryptoUtils.byteArray2hexStr(decoded.slice(0, 1)); var addressAndChecksum_1 = decoded.slice(1); // get the address format var addressFormat = addressFormats.find(function (af) { return af.addressLength === addressAndChecksum_1.length; }); if (!addressFormat) { throw new Error('Invalid address length'); } var decodedAddress = cryptoUtils.byteArray2hexStr(addressAndChecksum_1.slice(0, addressFormat.accountIndexLength)); var checksum = cryptoUtils.byteArray2hexStr(addressAndChecksum_1.slice(-addressFormat.checkSumLength)); var calculatedHash = cryptoUtils .blake2b(preImage + addressType + decodedAddress, 64) .substr(0, addressFormat.checkSumLength * 2) .toUpperCase(); return calculatedHash == checksum; } catch (err) { return false; } } };