bitcoinjs-lib/src/address.js

61 lines
1.6 KiB
JavaScript
Raw Normal View History

var base58 = require('./base58');
var Crypto = require('./crypto-js/crypto');
var conv = require('./convert');
var util = require('./util');
var mainnet = require('./network').mainnet.addressVersion;
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 =
bytes.length <= 35 ? base58.checkDecode(bytes)
: bytes.length <= 40 ? conv.hexToBytes(bytes)
2014-01-11 13:55:21 +07:00
: util.error('Bad input');
this.version = version || this.hash.version || mainnet;
}
else {
this.hash = bytes;
this.version = version || bytes.version || mainnet;
}
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.
*/
Address.prototype.toString = function () {
return base58.checkEncode(this.hash.slice(0), this.version);
};
Address.prototype.getHash = function () {
return conv.bytesToHex(this.hash);
2011-05-04 17:02:56 +01:00
};
Address.getVersion = function(string) {
return base58.decode(string)[0];
}
Address.validate = function(string) {
try {
base58.checkDecode(string);
return true;
} catch (e) {
return false;
}
2011-05-04 17:02:56 +01:00
};
2012-01-11 10:41:52 +01:00
/**
* Parse a Bitcoin address contained in a string.
*/
Address.decodeString = function (string) {
return base58.checkDecode(string);
2011-05-04 17:02:56 +01:00
};
module.exports = Address;