2014-03-25 20:57:19 +01:00
|
|
|
var base58 = require('./base58')
|
2014-04-04 05:10:12 +11:00
|
|
|
var base58check = require('./base58check')
|
2014-03-25 20:57:19 +01:00
|
|
|
var convert = require('./convert')
|
2014-04-17 05:43:34 +10:00
|
|
|
var bitcoin = require('./network').bitcoin.pubKeyHash
|
2013-02-17 00:39:15 -05:00
|
|
|
|
2014-03-25 20:57:19 +01:00
|
|
|
function Address(bytes, version) {
|
2014-03-31 11:47:47 +08:00
|
|
|
if (!(this instanceof Address)) {
|
2014-03-25 20:57:19 +01:00
|
|
|
return new Address(bytes, version)
|
2014-03-31 11:47:47 +08:00
|
|
|
}
|
2013-10-21 14:00:31 -04:00
|
|
|
|
2014-03-25 20:57:19 +01:00
|
|
|
if (bytes instanceof Address) {
|
|
|
|
this.hash = bytes.hash
|
|
|
|
this.version = bytes.version
|
|
|
|
}
|
|
|
|
else if (typeof bytes === 'string') {
|
2014-04-04 05:10:12 +11:00
|
|
|
if (bytes.length <= 35) {
|
|
|
|
var decode = base58check.decode(bytes)
|
|
|
|
|
|
|
|
this.hash = decode.payload
|
|
|
|
this.version = decode.version
|
|
|
|
}
|
|
|
|
else if (bytes.length <= 40) {
|
|
|
|
this.hash = convert.hexToBytes(bytes)
|
2014-04-17 05:43:34 +10:00
|
|
|
this.version = version || bitcoin
|
2014-04-04 05:10:12 +11:00
|
|
|
}
|
|
|
|
else {
|
2014-04-08 21:53:33 +10:00
|
|
|
throw new Error('Invalid or unrecognized input')
|
2014-04-04 05:10:12 +11:00
|
|
|
}
|
2014-03-25 20:57:19 +01:00
|
|
|
}
|
|
|
|
else {
|
|
|
|
this.hash = bytes
|
2014-04-17 05:43:34 +10:00
|
|
|
this.version = version || bitcoin
|
2014-03-25 20:57:19 +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-04-04 05:10:12 +11:00
|
|
|
return base58check.encode(this.hash.slice(0), this.version)
|
2014-03-25 20:57:19 +01:00
|
|
|
}
|
2013-02-17 00:39:15 -05:00
|
|
|
|
2014-03-25 20:57:19 +01:00
|
|
|
/**
|
|
|
|
* Returns the version of an address, e.g. if the address belongs to the main
|
|
|
|
* net or the test net.
|
|
|
|
*/
|
|
|
|
Address.getVersion = function (address) {
|
|
|
|
return base58.decode(address)[0]
|
2013-10-07 08:21:00 -04:00
|
|
|
}
|
|
|
|
|
2014-03-25 20:57:19 +01:00
|
|
|
/**
|
|
|
|
* Returns true if a bitcoin address is a valid address, otherwise false.
|
|
|
|
*/
|
|
|
|
Address.validate = function (address) {
|
|
|
|
try {
|
2014-04-04 05:10:12 +11:00
|
|
|
base58check.decode(address)
|
2014-03-25 20:57:19 +01:00
|
|
|
return true
|
|
|
|
} catch (e) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
2011-05-04 17:02:56 +01:00
|
|
|
|
2014-03-25 20:57:19 +01:00
|
|
|
module.exports = Address
|