2013-02-17 00:39:15 -05:00
|
|
|
var base58 = require('./base58');
|
2014-03-11 09:52:48 +08:00
|
|
|
var convert = require('./convert');
|
2013-10-21 14:00:31 -04:00
|
|
|
var util = require('./util');
|
2014-02-28 16:05:43 +08:00
|
|
|
var mainnet = require('./network').mainnet.addressVersion;
|
2013-02-17 00:39:15 -05:00
|
|
|
|
2013-10-21 14:00:31 -04:00
|
|
|
var Address = function (bytes, version) {
|
2014-01-10 15:17:53 -05:00
|
|
|
if (!(this instanceof Address)) { return new Address(bytes, version); }
|
2013-10-21 15:27:50 -04:00
|
|
|
if (arguments[0] instanceof Address) {
|
|
|
|
this.hash = arguments[0].hash;
|
|
|
|
this.version = arguments[0].version;
|
|
|
|
}
|
|
|
|
else if (typeof bytes === 'string') {
|
2014-01-11 13:55:21 +07:00
|
|
|
this.hash =
|
2014-03-05 16:53:29 -05:00
|
|
|
bytes.length <= 35 ? base58.checkDecode(bytes)
|
2014-03-11 09:52:48 +08:00
|
|
|
: bytes.length <= 40 ? convert.hexToBytes(bytes)
|
2014-03-06 17:21:42 -06:00
|
|
|
: util.error('invalid or unrecognized input');
|
2013-10-21 14:00:31 -04:00
|
|
|
|
2014-02-28 16:05:43 +08:00
|
|
|
this.version = version || this.hash.version || mainnet;
|
2013-10-07 08:21:00 -04:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
this.hash = bytes;
|
2014-02-28 16:05:43 +08:00
|
|
|
this.version = version || bytes.version || mainnet;
|
2013-10-07 08:21:00 -04:00
|
|
|
}
|
2011-05-04 17:02:56 +01:00
|
|
|
};
|
|
|
|
|
2012-01-11 10:41:52 +01:00
|
|
|
/**
|
|
|
|
* Serialize this object as a standard Bitcoin address.
|
|
|
|
*
|
|
|
|
* Returns the address as a base58-encoded string in the standardized format.
|
|
|
|
*/
|
2013-02-17 00:39:15 -05:00
|
|
|
Address.prototype.toString = function () {
|
2014-02-28 16:05:43 +08:00
|
|
|
return base58.checkEncode(this.hash.slice(0), this.version);
|
2013-02-17 00:39:15 -05:00
|
|
|
};
|
|
|
|
|
2013-10-07 08:21:00 -04:00
|
|
|
Address.getVersion = function(string) {
|
2013-10-21 14:00:31 -04:00
|
|
|
return base58.decode(string)[0];
|
2013-10-07 08:21:00 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
Address.validate = function(string) {
|
2013-10-21 14:00:31 -04:00
|
|
|
try {
|
|
|
|
base58.checkDecode(string);
|
|
|
|
return true;
|
|
|
|
} catch (e) {
|
|
|
|
return false;
|
|
|
|
}
|
2011-05-04 17:02:56 +01:00
|
|
|
};
|
|
|
|
|
2013-02-17 00:39:15 -05:00
|
|
|
module.exports = Address;
|