bitcoinjs-lib/src/address.js

53 lines
1.7 KiB
JavaScript
Raw Normal View History

2015-08-20 13:31:29 +10:00
var bs58check = require('bs58check')
var bscript = require('./script')
var networks = require('./networks')
2015-08-14 11:16:17 +10:00
var typeforce = require('typeforce')
2015-08-11 17:01:47 +10:00
var types = require('./types')
function fromBase58Check (address) {
2015-08-20 13:31:29 +10:00
var payload = bs58check.decode(address)
if (payload.length < 21) throw new TypeError(address + ' is too short')
if (payload.length > 21) throw new TypeError(address + ' is too long')
var version = payload[0]
var hash = payload.slice(1)
2015-07-21 10:55:47 +10:00
return { hash: hash, version: version }
2014-03-25 20:57:19 +01:00
}
2015-07-21 10:55:47 +10:00
function toBase58Check (hash, version) {
2015-08-11 17:01:47 +10:00
typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments)
2015-07-21 10:55:47 +10:00
var payload = new Buffer(21)
2015-07-21 10:55:47 +10:00
payload.writeUInt8(version, 0)
hash.copy(payload, 1)
2015-08-20 13:31:29 +10:00
return bs58check.encode(payload)
2014-03-25 20:57:19 +01:00
}
function fromOutputScript (scriptPubKey, network) {
network = network || networks.bitcoin
if (bscript.pubKeyHash.output.check(scriptPubKey)) return toBase58Check(bscript.compile(scriptPubKey).slice(3, 23), network.pubKeyHash)
if (bscript.scriptHash.output.check(scriptPubKey)) return toBase58Check(bscript.compile(scriptPubKey).slice(2, 22), network.scriptHash)
throw new Error(bscript.toASM(scriptPubKey) + ' has no matching Address')
}
2015-07-24 11:59:48 +10:00
function toOutputScript (address, network) {
network = network || networks.bitcoin
var decode = fromBase58Check(address)
if (decode.version === network.pubKeyHash) return bscript.pubKeyHash.output.encode(decode.hash)
if (decode.version === network.scriptHash) return bscript.scriptHash.output.encode(decode.hash)
2015-07-21 10:55:47 +10:00
throw new Error(address + ' has no matching Script')
}
2015-07-21 10:55:47 +10:00
module.exports = {
fromBase58Check: fromBase58Check,
fromOutputScript: fromOutputScript,
toBase58Check: toBase58Check,
toOutputScript: toOutputScript
}