bitcoinjs-lib/src/address.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

2014-03-25 20:57:19 +01:00
var base58 = require('./base58')
var base58check = require('./base58check')
2014-03-25 20:57:19 +01:00
var convert = require('./convert')
2014-04-16 21:43:34 +02:00
var bitcoin = require('./network').bitcoin.pubKeyHash
2014-03-25 20:57:19 +01:00
function Address(bytes, version) {
2014-03-31 05:47:47 +02:00
if (!(this instanceof Address)) {
2014-03-25 20:57:19 +01:00
return new Address(bytes, version)
2014-03-31 05:47:47 +02: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') {
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-16 21:43:34 +02:00
this.version = version || bitcoin
}
else {
throw new Error('Invalid or unrecognized input')
}
2014-03-25 20:57:19 +01:00
}
else {
this.hash = bytes
2014-04-16 21:43:34 +02: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.
*/
Address.prototype.toString = function () {
return base58check.encode(this.hash.slice(0), this.version)
2014-03-25 20:57:19 +01: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]
}
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 {
base58check.decode(address)
2014-03-25 20:57:19 +01:00
return true
} catch (e) {
return false
}
}
2011-05-04 18:02:56 +02:00
2014-03-25 20:57:19 +01:00
module.exports = Address