throw error when using invalid length hash in Address

I have often made the error of using a public key rather than the hash of the
public key when creating an address, leading to invalid addresses. I'm sure I'm
not the only one. This commit follows the principle of "fail early, fail often"
and simply throws an error if you try to insert something other than 20 bytes
long when creating an address, which would be the case when using a public key.
This way that common mistake should be reduced.
This commit is contained in:
Ryan X. Charles 2014-06-11 18:13:39 -07:00
parent 772b12e471
commit c2e5a14eed
3 changed files with 34 additions and 10 deletions

File diff suppressed because one or more lines are too long

View File

@ -36,7 +36,9 @@ var parent = imports.parent || require('../util/VersionedData');
var networks = imports.networks || require('../networks');
var Script = imports.Script || require('./Script');
function Address() {
function Address(version, hash) {
if (hash && hash.length && hash.length != 20)
throw new Error('Hash must be 20 bytes');
Address.super(this, arguments);
}

View File

@ -4,6 +4,7 @@ var chai = chai || require('chai');
var bitcore = bitcore || require('../bitcore');
var should = chai.should();
var expect = chai.expect;
var Address = bitcore.Address;
var Key = bitcore.Key;
@ -79,6 +80,27 @@ describe('Address', function() {
new Address('2NBSBcf2KfjPEEqVusmrWdmUeNHRiUTS3Li').isScript().should.equal(true);
});
describe('#Address constructor', function() {
it('should produce a valid address from a hash', function() {
var privkey = bitcore.util.sha256('test');
var key = new bitcore.Key();
key.private = privkey;
key.regenerateSync();
var hash = bitcore.util.sha256ripe160(key.public);
var addr = new bitcore.Address(0, hash);
addr.isValid().should.equal(true);
});
it('should throw an error if you try to use a public key instead of a hash', function() {
var privkey = bitcore.util.sha256('test');
var key = new bitcore.Key();
key.private = privkey;
key.regenerateSync();
var f = function() {new bitcore.Address(0, key.public);};
expect(f).to.throw(Error);
});
});
describe('#fromPubKey', function() {
it('should make pubkeyhash address from an uncompressed public key', function() {
var pubkey = new Buffer('04fa05ce8b25010cb6e17a30e0b66668bf083c40687547748ec330ee77adf53a42abd3d26148cbacfcf79c907ddefeb2c37f8bebc0a695ba79d634449d871de218', 'hex');