Browse Source

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.
patch-2
Ryan X. Charles 11 years ago
parent
commit
c2e5a14eed
  1. 18
      browser/bundle.js
  2. 4
      lib/Address.js
  3. 22
      test/test.Address.js

18
browser/bundle.js

File diff suppressed because one or more lines are too long

4
lib/Address.js

@ -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);
}

22
test/test.Address.js

@ -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');

Loading…
Cancel
Save