bitcoinjs-lib/src/address.js

63 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')
2014-12-23 05:08:20 +01:00
var typeForce = require('typeforce')
var networks = require('./networks')
2014-06-13 01:58:52 +02:00
var scripts = require('./scripts')
2015-02-23 00:36:57 +01: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'
}
}
2015-02-23 00:36:57 +01:00
function Address (hash, version) {
2014-12-23 05:08:20 +01:00
typeForce('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
}
2015-02-23 00:36:57 +01:00
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
}
2015-02-23 00:36:57 +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)
throw new Error(script.toASM() + ' has no matching Address')
}
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
}
2015-02-23 00:36:57 +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)
throw new Error(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