bitcoinjs-lib/src/address.js

65 lines
1.8 KiB
JavaScript
Raw Normal View History

var assert = require('assert')
2014-07-02 06:37:32 +02:00
var base58check = require('bs58check')
var enforceType = require('./types')
var networks = require('./networks')
2014-06-13 01:58:52 +02:00
var scripts = require('./scripts')
2014-06-17 13:05:18 +02:00
function findScriptTypeByVersion(version) {
for (var networkName in networks) {
var network = networks[networkName]
2014-06-17 13:05:18 +02:00
if (version === network.pubKeyHash) return 'pubkeyhash'
if (version === network.scriptHash) return 'scripthash'
}
}
function Address(hash, version) {
enforceType('Buffer', hash)
assert.strictEqual(hash.length, 20, 'Invalid hash length')
2014-06-17 13:05:18 +02:00
assert.strictEqual(version & 0xff, version, 'Invalid version byte')
this.hash = hash
this.version = version
2014-03-25 20:57:19 +01:00
}
// Import functions
Address.fromBase58Check = function(string) {
var payload = base58check.decode(string)
var version = payload.readUInt8(0)
var hash = payload.slice(1)
return new Address(hash, version)
2014-03-25 20:57:19 +01:00
}
Address.fromOutputScript = function(script, network) {
network = network || networks.bitcoin
if (scripts.isPubKeyHashOutput(script)) return new Address(script.chunks[2], network.pubKeyHash)
if (scripts.isScriptHashOutput(script)) return new Address(script.chunks[1], network.scriptHash)
assert(false, script.toASM() + ' has no matching Address')
}
// Export functions
Address.prototype.toBase58Check = function () {
var payload = new Buffer(21)
payload.writeUInt8(this.version, 0)
this.hash.copy(payload, 1)
return base58check.encode(payload)
2014-03-25 20:57:19 +01:00
}
Address.prototype.toOutputScript = function() {
var scriptType = findScriptTypeByVersion(this.version)
2014-06-17 13:05:18 +02:00
if (scriptType === 'pubkeyhash') return scripts.pubKeyHashOutput(this.hash)
if (scriptType === 'scripthash') return scripts.scriptHashOutput(this.hash)
2014-06-13 01:33:58 +02:00
assert(false, this.toString() + ' has no matching Script')
}
Address.prototype.toString = Address.prototype.toBase58Check
2011-05-04 18:02:56 +02:00
2014-03-25 20:57:19 +01:00
module.exports = Address