bitcoinjs-lib/src/transaction_builder.js

503 lines
15 KiB
JavaScript
Raw Normal View History

var baddress = require('./address')
var bcrypto = require('./crypto')
var bscript = require('./script')
2015-09-25 08:58:48 +02:00
var bufferEquals = require('buffer-equals')
var networks = require('./networks')
var ops = require('./opcodes')
2015-11-26 02:40:06 +01:00
var typeforce = require('typeforce')
var types = require('./types')
2014-06-16 08:05:31 +02:00
2015-03-02 06:48:36 +01:00
var ECPair = require('./ecpair')
var ECSignature = require('./ecsignature')
var Transaction = require('./transaction')
2014-06-16 08:05:31 +02:00
// re-orders signatures to match pubKeys, fills undefined otherwise
function fixMSSignatures (transaction, vin, pubKeys, signatures, prevOutScript, hashType, skipPubKey) {
// maintain a local copy of unmatched signatures
var unmatched = signatures.slice()
var cache = {}
return pubKeys.map(function (pubKey) {
// skip optionally provided pubKey
2015-09-25 08:58:48 +02:00
if (skipPubKey && bufferEquals(skipPubKey, pubKey)) return undefined
var matched
var keyPair2 = ECPair.fromPublicKeyBuffer(pubKey)
// check for a matching signature
unmatched.some(function (signature, i) {
// skip if undefined || OP_0
if (!signature) return false
var signatureHash = cache[hashType] = cache[hashType] || transaction.hashForSignature(vin, prevOutScript, hashType)
if (!keyPair2.verify(signatureHash, signature)) return false
// remove matched signature from unmatched
unmatched[i] = undefined
matched = signature
return true
})
return matched || undefined
})
}
function extractInput (transaction, txIn, vin) {
var scriptSigChunks = bscript.decompile(txIn.script)
var prevOutType = bscript.classifyInput(scriptSigChunks, true)
2015-08-07 08:30:24 +02:00
if (txIn.script.length === 0) {
return {}
}
var processScript = function (scriptType, scriptSigChunks, redeemScriptChunks) {
// ensure chunks are decompiled
scriptSigChunks = bscript.decompile(scriptSigChunks)
redeemScriptChunks = redeemScriptChunks ? bscript.decompile(redeemScriptChunks) : undefined
2015-08-07 08:30:24 +02:00
var hashType, pubKeys, signatures, prevOutScript, redeemScript, redeemScriptType, result, parsed
switch (scriptType) {
case 'scripthash':
redeemScript = scriptSigChunks.slice(-1)[0]
scriptSigChunks = bscript.compile(scriptSigChunks.slice(0, -1))
redeemScriptType = bscript.classifyInput(scriptSigChunks, true)
prevOutScript = bscript.scriptHashOutput(bcrypto.hash160(redeemScript))
result = processScript(redeemScriptType, scriptSigChunks, bscript.decompile(redeemScript))
result.prevOutScript = prevOutScript
result.redeemScript = redeemScript
result.redeemScriptType = redeemScriptType
return result
case 'pubkeyhash':
parsed = ECSignature.parseScriptSignature(scriptSigChunks[0])
hashType = parsed.hashType
pubKeys = scriptSigChunks.slice(1)
signatures = [parsed.signature]
prevOutScript = bscript.pubKeyHashOutput(bcrypto.hash160(pubKeys[0]))
break
case 'pubkey':
parsed = ECSignature.parseScriptSignature(scriptSigChunks[0])
hashType = parsed.hashType
signatures = [parsed.signature]
if (redeemScriptChunks) {
pubKeys = redeemScriptChunks.slice(0, 1)
}
break
case 'multisig':
signatures = scriptSigChunks.slice(1).map(function (chunk) {
if (chunk === ops.OP_0) return undefined
parsed = ECSignature.parseScriptSignature(chunk)
hashType = parsed.hashType
return parsed.signature
})
if (redeemScriptChunks) {
pubKeys = redeemScriptChunks.slice(1, -2)
if (pubKeys.length !== signatures.length) {
signatures = fixMSSignatures(transaction, vin, pubKeys, signatures, bscript.compile(redeemScriptChunks), hashType, redeemScript)
}
}
break
}
return {
hashType: hashType,
pubKeys: pubKeys,
signatures: signatures,
prevOutScript: prevOutScript,
redeemScript: redeemScript,
redeemScriptType: redeemScriptType
}
}
// Extract hashType, pubKeys, signatures and prevOutScript
var result = processScript(prevOutType, scriptSigChunks)
return {
hashType: result.hashType,
prevOutScript: result.prevOutScript,
prevOutType: prevOutType,
pubKeys: result.pubKeys,
redeemScript: result.redeemScript,
redeemScriptType: result.redeemScriptType,
signatures: result.signatures
}
}
function TransactionBuilder (network) {
this.prevTxMap = {}
this.prevOutScripts = {}
this.prevOutTypes = {}
this.network = network || networks.bitcoin
this.inputs = []
this.tx = new Transaction()
}
2015-11-26 02:40:06 +01:00
TransactionBuilder.prototype.setLockTime = function (locktime) {
typeforce(types.UInt32, locktime)
// if any signatures exist, throw
if (this.inputs.some(function (input) {
if (!input.signatures) return false
return input.signatures.some(function (s) { return s })
})) {
throw new Error('No, this would invalidate signatures')
}
this.tx.locktime = locktime
}
TransactionBuilder.fromTransaction = function (transaction, network) {
var txb = new TransactionBuilder(network)
// 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
txb.inputs = transaction.ins.map(function (txIn, vin) {
// TODO: verify whether extractInput is sane with coinbase scripts
if (Transaction.isCoinbaseHash(txIn.hash)) {
throw new Error('coinbase inputs not supported')
}
return extractInput(transaction, txIn, vin)
})
return txb
}
2015-03-02 08:06:49 +01:00
TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) {
// is it a hex string?
2015-03-02 08:06:49 +01:00
if (typeof txHash === 'string') {
// transaction hashs's are displayed in reverse order, un-reverse it
2015-09-27 15:36:31 +02:00
txHash = [].reverse.call(new Buffer(txHash, 'hex'))
2015-03-02 08:06:49 +01:00
// is it a Transaction object?
2015-03-02 08:06:49 +01:00
} 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 prevOutScriptChunks = bscript.decompile(prevOutScript)
var prevOutType = bscript.classifyOutput(prevOutScriptChunks)
// if we can, extract pubKey information
switch (prevOutType) {
2015-08-13 06:25:32 +02:00
case 'multisig':
2015-08-07 08:30:24 +02:00
input.pubKeys = prevOutScriptChunks.slice(1, -2)
input.signatures = input.pubKeys.map(function () { return undefined })
break
2015-08-13 06:25:32 +02:00
case 'pubkey':
2015-08-07 08:30:24 +02:00
input.pubKeys = prevOutScriptChunks.slice(0, 1)
input.signatures = [undefined]
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
}
// if signatures exist, adding inputs is only acceptable if SIGHASH_ANYONECANPAY is used
// throw if any signatures *didn't* use SIGHASH_ANYONECANPAY
if (!this.inputs.every(function (otherInput) {
// no signature
if (otherInput.hashType === undefined) return true
return otherInput.hashType & Transaction.SIGHASH_ANYONECANPAY
})) {
throw new Error('No, this would invalidate signatures')
}
2014-06-16 08:05:31 +02:00
2015-03-02 08:06:49 +01:00
var prevOut = txHash.toString('hex') + ':' + vout
if (this.prevTxMap[prevOut]) throw new Error('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) {
var nOutputs = this.tx.outs.length
// if signatures exist, adding outputs is only acceptable if SIGHASH_NONE or SIGHASH_SINGLE is used
// throws if any signatures didn't use SIGHASH_NONE|SIGHASH_SINGLE
if (!this.inputs.every(function (input, index) {
// no signature
if (input.hashType === undefined) return true
var hashTypeMod = input.hashType & 0x1f
if (hashTypeMod === Transaction.SIGHASH_NONE) return true
if (hashTypeMod === Transaction.SIGHASH_SINGLE) {
// account for SIGHASH_SINGLE signing of a non-existing output, aka the "SIGHASH_SINGLE" bug
return index < nOutputs
}
return false
})) {
throw new Error('No, this would invalidate signatures')
}
2014-06-16 08:05:31 +02:00
// Attempt to get a script if it's a base58 address string
if (typeof scriptPubKey === 'string') {
scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network)
}
return this.tx.addOutput(scriptPubKey, value)
2014-06-16 08:05:31 +02:00
}
2015-02-23 00:36:57 +01:00
TransactionBuilder.prototype.build = function () {
return this.__build(false)
}
TransactionBuilder.prototype.buildIncomplete = function () {
return this.__build(true)
}
var canBuildTypes = {
2015-02-23 00:36:57 +01:00
'multisig': true,
'pubkey': true,
'pubkeyhash': true
2015-02-23 00:36:57 +01:00
}
2015-02-23 00:36:57 +01:00
TransactionBuilder.prototype.__build = function (allowIncomplete) {
2014-06-16 08:05:31 +02:00
if (!allowIncomplete) {
if (!this.tx.ins.length) throw new Error('Transaction has no inputs')
if (!this.tx.outs.length) throw new Error('Transaction has no outputs')
2014-06-16 08:05:31 +02:00
}
var tx = this.tx.clone()
// Create script signatures from inputs
2015-02-23 00:36:57 +01:00
this.inputs.forEach(function (input, index) {
var scriptType = input.redeemScriptType || input.prevOutType
var scriptSig
if (!allowIncomplete) {
if (!scriptType) throw new Error('Transaction is not complete')
if (!canBuildTypes[scriptType]) throw new Error(scriptType + ' not supported')
// XXX: only relevant to types that need signatures
if (!input.signatures) throw new Error('Transaction is missing signatures')
}
2014-06-16 08:05:31 +02:00
if (input.signatures) {
var processScript = function (scriptType, parentType, redeemScript) {
var scriptSig
var pkhSignature
switch (scriptType) {
case 'pubkeyhash':
pkhSignature = input.signatures[0].toScriptSignature(input.hashType)
scriptSig = bscript.pubKeyHashInput(pkhSignature, input.pubKeys[0])
break
case 'multisig':
var msSignatures = input.signatures.map(function (signature) {
return signature && signature.toScriptSignature(input.hashType)
})
// fill in blanks with OP_0
if (allowIncomplete) {
for (var i = 0; i < msSignatures.length; ++i) {
msSignatures[i] = msSignatures[i] || ops.OP_0
}
// remove blank signatures
} else {
msSignatures = msSignatures.filter(function (x) { return x })
2015-03-02 23:55:17 +01:00
}
scriptSig = bscript.multisigInput(msSignatures, allowIncomplete ? undefined : redeemScript)
break
2014-07-28 07:40:07 +02:00
case 'pubkey':
var pkSignature = input.signatures[0].toScriptSignature(input.hashType)
scriptSig = bscript.pubKeyInput(pkSignature)
break
}
// wrap as scriptHash if necessary
if (parentType === 'scripthash') {
scriptSig = bscript.scriptHashInput(scriptSig, redeemScript)
}
return scriptSig
}
scriptSig = processScript(scriptType, input.prevOutType, input.redeemScript)
2014-06-16 08:05:31 +02:00
}
// did we build a scriptSig? Buffer('') is allowed
if (scriptSig) {
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) {
if (keyPair.network !== this.network) throw new Error('Inconsistent network')
if (!this.inputs[index]) throw new Error('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.redeemScriptType &&
input.signatures &&
input.signatures.length === input.pubKeys.length
2015-03-02 06:48:36 +01:00
var kpPubKey = keyPair.getPublicKeyBuffer()
var signatureScript
2015-03-02 06:48:36 +01:00
// are we ready to sign?
if (canSign) {
// if redeemScript was provided, enforce consistency
if (redeemScript) {
2015-09-25 08:58:48 +02:00
if (!bufferEquals(input.redeemScript, redeemScript)) throw new Error('Inconsistent redeemScript')
}
2014-07-28 07:40:07 +02:00
if (input.hashType !== hashType) throw new Error('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) {
if (input.prevOutType !== 'scripthash') throw new Error('PrevOutScript must be P2SH')
var scriptHash = bscript.decompile(input.prevOutScript)[1]
2015-09-25 08:58:48 +02:00
if (!bufferEquals(scriptHash, bcrypto.hash160(redeemScript))) throw new Error('RedeemScript does not match ' + scriptHash.toString('hex'))
}
2014-07-28 07:40:07 +02:00
var pubKeys, pkh1, pkh2
var redeemScriptType
var processScript = function (redeemScript) {
var scriptType = bscript.classifyOutput(redeemScript)
var redeemScriptChunks = bscript.decompile(redeemScript)
switch (scriptType) {
case 'multisig':
pubKeys = redeemScriptChunks.slice(1, -2)
break
case 'pubkeyhash':
pkh1 = redeemScriptChunks[2]
pkh2 = bcrypto.hash160(keyPair.getPublicKeyBuffer())
if (!bufferEquals(pkh1, pkh2)) throw new Error('privateKey cannot sign for this input')
pubKeys = [kpPubKey]
break
case 'pubkey':
pubKeys = redeemScriptChunks.slice(0, 1)
break
default:
throw new Error('RedeemScript not supported (' + scriptType + ')')
}
return scriptType
}
redeemScriptType = processScript(redeemScript)
2015-08-07 08:30:24 +02:00
// if we don't have a prevOutScript, generate a P2SH script
if (!input.prevOutScript) {
input.prevOutScript = bscript.scriptHashOutput(bcrypto.hash160(redeemScript))
input.prevOutType = 'scripthash'
}
input.pubKeys = pubKeys
input.redeemScript = redeemScript
input.redeemScriptType = redeemScriptType
input.signatures = pubKeys.map(function () { return undefined })
} else {
// pay-to-scriptHash is not possible without a redeemScript
if (input.prevOutType === 'scripthash') throw new Error('PrevOutScript is P2SH, missing redeemScript')
// if we don't have a scriptType, assume pubKeyHash otherwise
if (!input.scriptType) {
input.prevOutScript = bscript.pubKeyHashOutput(bcrypto.hash160(keyPair.getPublicKeyBuffer()))
input.prevOutType = 'pubkeyhash'
2015-03-02 06:48:36 +01:00
input.pubKeys = [kpPubKey]
input.scriptType = input.prevOutType
input.signatures = [undefined]
} else {
// throw if we can't sign with it
if (!input.pubKeys || !input.signatures) throw new Error(input.scriptType + ' not supported')
}
}
input.hashType = hashType
}
// ready to sign?
signatureScript = signatureScript || input.redeemScript || input.prevOutScript
var signatureHash = this.tx.hashForSignature(index, signatureScript, hashType)
// enforce in order signing of public keys
var valid = input.pubKeys.some(function (pubKey, i) {
2015-09-25 08:58:48 +02:00
if (!bufferEquals(kpPubKey, pubKey)) return false
if (input.signatures[i]) throw new Error('Signature already exists')
2015-03-02 06:48:36 +01:00
input.signatures[i] = keyPair.sign(signatureHash)
return true
})
if (!valid) throw new Error('Key pair cannot sign for this input')
}
2014-06-16 08:05:31 +02:00
module.exports = TransactionBuilder