Address().fromBuffer(buf);

This commit is contained in:
Ryan X. Charles 2014-09-17 14:22:18 -07:00
parent 8a52e6c316
commit ac85264a28
2 changed files with 43 additions and 19 deletions

View File

@ -4,11 +4,18 @@ var Hash = require('./hash');
var Pubkey = require('./pubkey');
var Script = require('./script');
function Address(obj) {
function Address(buf) {
if (!(this instanceof Address))
return new Address(obj);
if (obj)
return new Address(buf);
if (Buffer.isBuffer(buf)) {
this.fromBuffer(buf);
} else if (typeof buf === 'string') {
var str = buf;
this.fromString(str);
} else if (buf) {
var obj = buf;
this.set(obj);
}
};
Address.prototype.set = function(obj) {
@ -18,22 +25,7 @@ Address.prototype.set = function(obj) {
return this;
};
Address.prototype.fromPubkey = function(pubkey, networkstr) {
this.hashbuf = Hash.sha256ripemd160(pubkey.toBuffer());
this.networkstr = networkstr || 'mainnet';
this.typestr = 'pubkeyhash';
return this;
};
Address.prototype.fromScript = function(script, networkstr) {
this.hashbuf = Hash.sha256ripemd160(script.toBuffer());
this.networkstr = networkstr || 'mainnet';
this.typestr = 'scripthash';
return this;
};
Address.prototype.fromString = function(str) {
var buf = base58check.decode(str);
Address.prototype.fromBuffer = function(buf) {
if (buf.length !== 1 + 20)
throw new Error('Address buffers must be exactly 21 bytes');
var version = buf[0];
@ -57,6 +49,25 @@ Address.prototype.fromString = function(str) {
this.hashbuf = buf.slice(1);
return this;
};
Address.prototype.fromPubkey = function(pubkey, networkstr) {
this.hashbuf = Hash.sha256ripemd160(pubkey.toBuffer());
this.networkstr = networkstr || 'mainnet';
this.typestr = 'pubkeyhash';
return this;
};
Address.prototype.fromScript = function(script, networkstr) {
this.hashbuf = Hash.sha256ripemd160(script.toBuffer());
this.networkstr = networkstr || 'mainnet';
this.typestr = 'scripthash';
return this;
};
Address.prototype.fromString = function(str) {
var buf = base58check.decode(str);
return this.fromBuffer(buf);
}
Address.isValid = function(addrstr) {

View File

@ -6,11 +6,16 @@ var Script = require('../lib/script');
describe('Address', function() {
var pubkeyhash = new Buffer('3c3fa3d4adcaf8f52d5b1843975e122548269937', 'hex');
var buf = Buffer.concat([new Buffer([0]), pubkeyhash]);
var str = '16VZnHwRhwrExfeHFHGjwrgEMq8VcYPs9r';
it('should create a new address object', function() {
var address = new Address();
should.exist(address);
address = Address(buf);
should.exist(address);
address = Address(str);
should.exist(address);
});
describe('@isValid', function() {
@ -25,6 +30,14 @@ describe('Address', function() {
});
describe('#fromBuffer', function() {
it('should make an address from a buffer', function() {
Address().fromBuffer(buf).toString().should.equal(str);
});
});
describe('#fromPubkey', function() {
it('should make this address from a compressed pubkey', function() {