From 1a4000cc98a23cf77705333a98bc99a89948276d Mon Sep 17 00:00:00 2001 From: Daniel Cousens Date: Tue, 21 Jul 2015 12:29:35 +1000 Subject: [PATCH] address: throw Invalid address instead of hash/version for fromBase58Check --- src/address.js | 17 ++++++++++------- test/bitcoin.core.js | 2 +- test/fixtures/address.json | 4 ++-- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/address.js b/src/address.js index 0fb9383..1b419a6 100644 --- a/src/address.js +++ b/src/address.js @@ -14,12 +14,11 @@ function findScriptTypeByVersion (version) { function fromBase58Check (string) { var payload = base58check.decode(string) + if (payload.length !== 21) throw new TypeError('Invalid address length') + var version = payload.readUInt8(0) var hash = payload.slice(1) - if (hash.length !== 20) throw new TypeError('Invalid hash length') - if (version & ~0xff) throw new TypeError('Invalid version byte') - return { hash: hash, version: version } } @@ -46,11 +45,15 @@ function toBase58Check (hash, version) { } function toOutputScript (address) { - var decode = fromBase58Check(address) - var scriptType = findScriptTypeByVersion(decode.version) + var payload = base58check.decode(address) + if (payload.length !== 21) throw new TypeError('Invalid hash length') - if (scriptType === 'pubkeyhash') return scripts.pubKeyHashOutput(decode.hash) - if (scriptType === 'scripthash') return scripts.scriptHashOutput(decode.hash) + var version = payload.readUInt8(0) + var hash = payload.slice(1) + var scriptType = findScriptTypeByVersion(version) + + if (scriptType === 'pubkeyhash') return scripts.pubKeyHashOutput(hash) + if (scriptType === 'scripthash') return scripts.scriptHashOutput(hash) throw new Error(address + ' has no matching Script') } diff --git a/test/bitcoin.core.js b/test/bitcoin.core.js index 613fc99..2c058b5 100644 --- a/test/bitcoin.core.js +++ b/test/bitcoin.core.js @@ -89,7 +89,7 @@ describe('Bitcoin-core', function () { var address = Address.fromBase58Check(string) assert.notEqual(allowedNetworks.indexOf(address.version), -1, 'Invalid network') - }, /Invalid (checksum|hash length|network)/) + }, /Invalid (checksum|address length|network)/) }) }) }) diff --git a/test/fixtures/address.json b/test/fixtures/address.json index ec82861..02c36a1 100644 --- a/test/fixtures/address.json +++ b/test/fixtures/address.json @@ -34,12 +34,12 @@ { "description": "hash too short", "base58check": "7SeEnXWPaCCALbVrTnszCVGfRU8cGfx", - "exception": "Invalid hash length" + "exception": "Invalid address length" }, { "description": "hash too long", "base58check": "j9ywUkWg2fTQrouxxh5rSZhRvrjMkEUfuiKe", - "exception": "Invalid hash length" + "exception": "Invalid address length" } ], "fromOutputScript": [