bitcoinjs-lib/src/transaction_builder.js

415 lines
12 KiB
JavaScript
Raw Normal View History

2014-06-16 08:05:31 +02:00
var assert = require('assert')
2015-03-02 06:48:36 +01:00
var bufferutils = require('./bufferutils')
var ops = require('./opcodes')
2014-06-16 08:05:31 +02:00
var scripts = require('./scripts')
var Address = require('./address')
2015-03-02 06:48:36 +01:00
var ECPair = require('./ecpair')
var ECSignature = require('./ecsignature')
2014-06-16 08:05:31 +02:00
var Script = require('./script')
var Transaction = require('./transaction')
2014-06-16 08:05:31 +02:00
2015-02-23 00:36:57 +01:00
function extractInput (txIn) {
var redeemScript
var scriptSig = txIn.script
var prevOutScript
var prevOutType = scripts.classifyInput(scriptSig, true)
var scriptType
// Re-classify if scriptHash
if (prevOutType === 'scripthash') {
redeemScript = Script.fromBuffer(scriptSig.chunks.slice(-1)[0])
prevOutScript = scripts.scriptHashOutput(redeemScript.getHash())
scriptSig = Script.fromChunks(scriptSig.chunks.slice(0, -1))
scriptType = scripts.classifyInput(scriptSig, true)
} else {
scriptType = prevOutType
}
// Extract hashType, pubKeys and signatures
var hashType, parsed, pubKeys, signatures
switch (scriptType) {
case 'pubkeyhash': {
parsed = ECSignature.parseScriptSignature(scriptSig.chunks[0])
hashType = parsed.hashType
2015-03-02 06:48:36 +01:00
pubKeys = scriptSig.chunks.slice(1)
signatures = [parsed.signature]
2015-03-02 06:48:36 +01:00
prevOutScript = ECPair.fromPublicKeyBuffer(pubKeys[0]).getAddress().toOutputScript()
break
}
case 'pubkey': {
parsed = ECSignature.parseScriptSignature(scriptSig.chunks[0])
hashType = parsed.hashType
signatures = [parsed.signature]
if (redeemScript) {
2015-03-02 06:48:36 +01:00
pubKeys = redeemScript.chunks.slice(0, 1)
}
break
}
case 'multisig': {
2015-02-23 00:36:57 +01:00
signatures = scriptSig.chunks.slice(1).map(function (chunk) {
if (chunk === ops.OP_0) return chunk
var parsed = ECSignature.parseScriptSignature(chunk)
hashType = parsed.hashType
return parsed.signature
})
if (redeemScript) {
2015-03-02 06:48:36 +01:00
pubKeys = redeemScript.chunks.slice(1, -2)
}
break
}
}
return {
hashType: hashType,
prevOutScript: prevOutScript,
prevOutType: prevOutType,
pubKeys: pubKeys,
redeemScript: redeemScript,
scriptType: scriptType,
signatures: signatures
}
}
2015-02-23 00:36:57 +01:00
function TransactionBuilder () {
this.prevTxMap = {}
this.prevOutScripts = {}
this.prevOutTypes = {}
this.inputs = []
this.tx = new Transaction()
}
2015-02-23 00:36:57 +01:00
TransactionBuilder.fromTransaction = function (transaction) {
var txb = new TransactionBuilder()
// Copy other transaction fields
txb.tx.version = transaction.version
txb.tx.locktime = transaction.locktime
// Extract/add inputs
2015-02-23 00:36:57 +01:00
transaction.ins.forEach(function (txIn) {
2014-12-02 04:20:04 +01:00
txb.addInput(txIn.hash, txIn.index, txIn.sequence)
})
// Extract/add outputs
2015-02-23 00:36:57 +01:00
transaction.outs.forEach(function (txOut) {
2014-12-02 04:20:04 +01:00
txb.addOutput(txOut.script, txOut.value)
})
// Extract/add signatures
2015-02-23 00:36:57 +01:00
txb.inputs = transaction.ins.map(function (txIn) {
// TODO: remove me after testcase added
assert(!Transaction.isCoinbaseHash(txIn.hash), 'coinbase inputs not supported')
// Ignore empty scripts
2015-03-16 03:53:28 +01:00
if (txIn.script.buffer.length === 0) return {}
return extractInput(txIn)
})
return txb
}
2015-03-02 08:06:49 +01:00
TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
// is it a txId?
if (typeof txHash === 'string') {
// a txId is big-endian hex, we want a little-endian Buffer
txHash = new Buffer(txHash, 'hex')
Array.prototype.reverse.call(txHash)
// is it a Transaction?
} else if (txHash instanceof Transaction) {
prevOutScript = txHash.outs[vout].script
txHash = txHash.getHash()
2014-06-16 08:05:31 +02:00
}
var input = {}
if (prevOutScript) {
var prevOutType = scripts.classifyOutput(prevOutScript)
// if we can, extract pubKey information
switch (prevOutType) {
case 'multisig': {
2015-03-02 06:48:36 +01:00
input.pubKeys = prevOutScript.chunks.slice(1, -2)
break
}
case 'pubkey': {
2015-03-02 06:48:36 +01:00
input.pubKeys = prevOutScript.chunks.slice(0, 1)
break
}
}
if (prevOutType !== 'scripthash') {
input.scriptType = prevOutType
}
2014-06-16 08:05:31 +02:00
input.prevOutScript = prevOutScript
input.prevOutType = prevOutType
2014-06-16 08:05:31 +02:00
}
2015-02-23 00:36:57 +01:00
assert(this.inputs.every(function (input2) {
if (input2.hashType === undefined) return true
return input2.hashType & Transaction.SIGHASH_ANYONECANPAY
2014-06-16 08:05:31 +02:00
}), 'No, this would invalidate signatures')
2015-03-02 08:06:49 +01:00
var prevOut = txHash.toString('hex') + ':' + vout
assert(!(prevOut in this.prevTxMap), 'Transaction is already an input')
2014-06-16 08:05:31 +02:00
2015-03-02 08:06:49 +01:00
var vin = this.tx.addInput(txHash, vout, sequence)
this.inputs[vin] = input
this.prevTxMap[prevOut] = vin
return vin
2014-06-16 08:05:31 +02:00
}
2015-02-23 00:36:57 +01:00
TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) {
assert(this.inputs.every(function (input) {
if (input.hashType === undefined) return true
return (input.hashType & 0x1f) === Transaction.SIGHASH_SINGLE
2014-06-16 08:05:31 +02:00
}), 'No, this would invalidate signatures')
// Attempt to get a valid address if it's a base58 address string
if (typeof scriptPubKey === 'string') {
scriptPubKey = Address.fromBase58Check(scriptPubKey)
}
// Attempt to get a valid script if it's an Address object
if (scriptPubKey instanceof Address) {
scriptPubKey = scriptPubKey.toOutputScript()
}
2014-06-16 08:05:31 +02:00
return this.tx.addOutput(scriptPubKey, value)
}
2015-02-23 00:36:57 +01:00
TransactionBuilder.prototype.build = function () {
return this.__build(false)
}
TransactionBuilder.prototype.buildIncomplete = function () {
return this.__build(true)
}
2015-02-23 00:36:57 +01:00
var canSignTypes = {
'pubkeyhash': true,
'multisig': true,
'pubkey': true
}
2015-02-23 00:36:57 +01:00
TransactionBuilder.prototype.__build = function (allowIncomplete) {
2014-06-16 08:05:31 +02:00
if (!allowIncomplete) {
assert(this.tx.ins.length > 0, 'Transaction has no inputs')
assert(this.tx.outs.length > 0, 'Transaction has no outputs')
}
var tx = this.tx.clone()
// Create script signatures from signature meta-data
2015-02-23 00:36:57 +01:00
this.inputs.forEach(function (input, index) {
var scriptType = input.scriptType
var scriptSig
if (!allowIncomplete) {
assert(!!scriptType, 'Transaction is not complete')
assert(scriptType in canSignTypes, scriptType + ' not supported')
assert(input.signatures, 'Transaction is missing signatures')
}
2014-06-16 08:05:31 +02:00
if (input.signatures) {
switch (scriptType) {
case 'pubkeyhash': {
var pkhSignature = input.signatures[0].toScriptSignature(input.hashType)
scriptSig = scripts.pubKeyHashInput(pkhSignature, input.pubKeys[0])
break
}
2014-07-28 07:40:07 +02:00
case 'multisig': {
// Array.prototype.map is sparse-compatible
2015-02-23 00:36:57 +01:00
var msSignatures = input.signatures.map(function (signature) {
return signature && signature.toScriptSignature(input.hashType)
})
// fill in blanks with OP_0
2015-03-02 23:55:17 +01:00
if (allowIncomplete) {
for (var i = 0; i < msSignatures.length; ++i) {
if (msSignatures[i]) continue
msSignatures[i] = ops.OP_0
}
} else {
// Array.prototype.filter returns non-sparse array
msSignatures = msSignatures.filter(function (x) { return x })
}
var redeemScript = allowIncomplete ? undefined : input.redeemScript
scriptSig = scripts.multisigInput(msSignatures, redeemScript)
break
}
2014-07-28 07:40:07 +02:00
case 'pubkey': {
var pkSignature = input.signatures[0].toScriptSignature(input.hashType)
scriptSig = scripts.pubKeyInput(pkSignature)
break
}
}
2014-06-16 08:05:31 +02:00
}
// did we build a scriptSig?
if (scriptSig) {
// wrap as scriptHash if necessary
if (input.prevOutType === 'scripthash') {
scriptSig = scripts.scriptHashInput(scriptSig, input.redeemScript)
}
2014-06-16 08:05:31 +02:00
tx.setInputScript(index, scriptSig)
}
2014-06-16 08:05:31 +02:00
})
return tx
}
2015-03-02 06:48:36 +01:00
TransactionBuilder.prototype.sign = function (index, keyPair, redeemScript, hashType) {
assert(index in this.inputs, 'No input at index: ' + index)
hashType = hashType || Transaction.SIGHASH_ALL
var input = this.inputs[index]
var canSign = input.hashType &&
2015-02-23 00:36:57 +01:00
input.prevOutScript &&
input.prevOutType &&
input.pubKeys &&
input.scriptType &&
input.signatures
2015-03-02 06:48:36 +01:00
var kpPubKey = keyPair.getPublicKeyBuffer()
// are we almost ready to sign?
if (canSign) {
// if redeemScript was provided, enforce consistency
if (redeemScript) {
assert.deepEqual(input.redeemScript, redeemScript, 'Inconsistent redeemScript')
}
2014-07-28 07:40:07 +02:00
assert.equal(input.hashType, hashType, 'Inconsistent hashType')
// no? prepare
} else {
2015-02-23 00:36:57 +01:00
// must be pay-to-scriptHash?
if (redeemScript) {
// if we have a prevOutScript, enforce scriptHash equality to the redeemScript
if (input.prevOutScript) {
assert.equal(input.prevOutType, 'scripthash', 'PrevOutScript must be P2SH')
var scriptHash = input.prevOutScript.chunks[1]
assert.deepEqual(scriptHash, redeemScript.getHash(), 'RedeemScript does not match ' + scriptHash.toString('hex'))
}
2014-07-28 07:40:07 +02:00
var scriptType = scripts.classifyOutput(redeemScript)
assert(scriptType in canSignTypes, 'RedeemScript not supported (' + scriptType + ')')
var pubKeys = []
switch (scriptType) {
case 'multisig': {
2015-03-02 06:48:36 +01:00
pubKeys = redeemScript.chunks.slice(1, -2)
break
}
case 'pubkeyhash': {
var pkh1 = redeemScript.chunks[2]
2015-03-02 06:48:36 +01:00
var pkh2 = keyPair.getAddress().hash
assert.deepEqual(pkh1, pkh2, 'privateKey cannot sign for this input')
2015-03-02 06:48:36 +01:00
pubKeys = [kpPubKey]
break
}
case 'pubkey': {
2015-03-02 06:48:36 +01:00
pubKeys = redeemScript.chunks.slice(0, 1)
break
}
}
if (!input.prevOutScript) {
input.prevOutScript = scripts.scriptHashOutput(redeemScript.getHash())
input.prevOutType = 'scripthash'
}
input.pubKeys = pubKeys
input.redeemScript = redeemScript
input.scriptType = scriptType
2015-02-23 00:36:57 +01:00
// cannot be pay-to-scriptHash
} else {
assert.notEqual(input.prevOutType, 'scripthash', 'PrevOutScript is P2SH, missing redeemScript')
2015-02-23 00:36:57 +01:00
// can we otherwise sign this?
if (input.scriptType) {
assert(input.pubKeys, input.scriptType + ' not supported')
// we know nothin' Jon Snow, assume pubKeyHash
} else {
2015-03-02 06:48:36 +01:00
input.prevOutScript = keyPair.getAddress().toOutputScript()
input.prevOutType = 'pubkeyhash'
2015-03-02 06:48:36 +01:00
input.pubKeys = [kpPubKey]
input.scriptType = input.prevOutType
}
}
input.hashType = hashType
input.signatures = input.signatures || []
}
var signatureScript = input.redeemScript || input.prevOutScript
var signatureHash = this.tx.hashForSignature(index, signatureScript, hashType)
2015-03-10 10:34:13 +01:00
// enforce signature order matches public keys
if (input.scriptType === 'multisig' && input.redeemScript && input.signatures.length !== input.pubKeys.length) {
// maintain a local copy of unmatched signatures
var unmatched = input.signatures.slice()
input.signatures = input.pubKeys.map(function (pubKey) {
2015-03-10 10:34:13 +01:00
var match
2015-03-02 06:48:36 +01:00
var keyPair2 = ECPair.fromPublicKeyBuffer(pubKey)
2015-03-10 10:34:13 +01:00
// check for any matching signatures
unmatched.some(function (signature, i) {
2015-03-02 06:48:36 +01:00
if (!keyPair2.verify(signatureHash, signature)) return false
2015-03-10 10:34:13 +01:00
match = signature
// remove matched signature from unmatched
unmatched.splice(i, 1)
2015-03-10 10:34:13 +01:00
return true
})
2015-03-10 10:34:13 +01:00
return match || undefined
})
}
// enforce in order signing of public keys
2015-02-23 00:36:57 +01:00
assert(input.pubKeys.some(function (pubKey, i) {
2015-03-02 06:48:36 +01:00
if (!bufferutils.equal(kpPubKey, pubKey)) return false
assert(!input.signatures[i], 'Signature already exists')
2015-03-02 06:48:36 +01:00
var signature = keyPair.sign(signatureHash)
input.signatures[i] = signature
return true
2015-03-02 06:48:36 +01:00
}, this), 'key pair cannot sign for this input')
}
2014-06-16 08:05:31 +02:00
module.exports = TransactionBuilder