bitcoinjs-lib/src/address.js

63 lines
1.4 KiB
JavaScript
Raw Normal View History

2014-03-25 20:57:19 +01:00
var base58 = require('./base58')
var convert = require('./convert')
var error = require('./util').error
var mainnet = require('./network').mainnet.addressVersion
2014-03-25 20:57:19 +01:00
function Address(bytes, version) {
if (!(this instanceof Address))
return new Address(bytes, version)
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') {
this.hash = stringToHash(bytes)
this.version = version || this.hash.version || mainnet
}
else {
this.hash = bytes
this.version = version || mainnet
}
}
function stringToHash(str) {
if (str.length <= 35) {
return base58.checkDecode(str)
}
if (str.length <= 40) {
return convert.hexToBytes(str)
}
error('invalid or unrecognized input')
}
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 () {
2014-03-25 20:57:19 +01:00
return base58.checkEncode(this.hash.slice(0), this.version)
}
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]
}
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 {
base58.checkDecode(address)
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