bitcoinjs-lib/src/transaction.js

456 lines
12 KiB
JavaScript
Raw Normal View History

// FIXME: To all ye that enter here, be weary of Buffers, Arrays and Hex interchanging between the outpoints
2014-04-17 11:08:16 +02:00
var assert = require('assert')
var Address = require('./address')
2014-03-31 05:47:47 +02:00
var BigInteger = require('./jsbn/jsbn')
var Script = require('./script')
var convert = require('./convert')
var crypto = require('./crypto')
2014-03-31 05:47:47 +02:00
var ECKey = require('./eckey').ECKey
2014-04-08 19:58:55 +02:00
var ecdsa = require('./ecdsa')
var Network = require('./network')
var Transaction = function (doc) {
2014-03-31 05:47:47 +02:00
if (!(this instanceof Transaction)) { return new Transaction(doc) }
this.version = 1
this.locktime = 0
this.ins = []
this.outs = []
this.defaultSequence = [255, 255, 255, 255] // 0xFFFFFFFF
if (doc) {
if (typeof doc == "string" || Array.isArray(doc)) {
doc = Transaction.deserialize(doc)
2012-01-11 02:40:45 +01:00
}
2014-03-31 05:47:47 +02:00
if (doc.hash) this.hash = doc.hash;
if (doc.version) this.version = doc.version;
if (doc.locktime) this.locktime = doc.locktime;
if (doc.ins && doc.ins.length) {
doc.ins.forEach(function(input) {
this.addInput(new TransactionIn(input))
}, this)
}
if (doc.outs && doc.outs.length) {
doc.outs.forEach(function(output) {
this.addOutput(new TransactionOut(output))
}, this)
}
this.hash = this.hash || this.getHash()
}
}
/**
* Create a new txin.
*
2013-10-21 20:07:38 +02:00
* Can be called with any of:
*
2014-03-17 10:49:37 +01:00
* - An existing TransactionIn object
2013-10-21 20:07:38 +02:00
* - A transaction and an index
* - A transaction hash and an index
* - A single string argument of the form txhash:index
*
* Note that this method does not sign the created input.
*/
Transaction.prototype.addInput = function (tx, outIndex) {
2014-03-31 05:47:47 +02:00
if (arguments[0] instanceof TransactionIn) {
this.ins.push(arguments[0])
}
else if (arguments[0].length > 65) {
var args = arguments[0].split(':')
return this.addInput(args[0], args[1])
}
else {
var hash = typeof tx === "string" ? tx : tx.hash
hash = Array.isArray(hash) ? convert.bytesToHex(hash) : hash
this.ins.push(new TransactionIn({
outpoint: {
hash: hash,
index: outIndex
},
script: new Script(),
sequence: this.defaultSequence
}))
}
}
/**
* Create a new txout.
*
* Can be called with:
*
* i) An existing TransactionOut object
* ii) An address object or an address and a value
* iii) An address:value string
*
*/
Transaction.prototype.addOutput = function (address, value) {
2014-03-31 05:47:47 +02:00
if (arguments[0] instanceof TransactionOut) {
this.outs.push(arguments[0])
return
}
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
if (arguments[0].indexOf(':') >= 0) {
var args = arguments[0].split(':')
address = args[0]
value = parseInt(args[1])
}
2014-03-23 20:01:33 +01:00
// FIXME: Stricter Transaction API
address = Address.fromBase58Check(address)
2014-03-31 05:47:47 +02:00
this.outs.push(new TransactionOut({
value: value,
script: Script.createOutputScript(address)
}))
}
/**
* Serialize this transaction.
*
* Returns the transaction as a byte array in the standard Bitcoin binary
* format. This method is byte-perfect, i.e. the resulting byte array can
* be hashed to get the transaction's standard Bitcoin hash.
*/
Transaction.prototype.serialize = function () {
2014-03-31 05:47:47 +02:00
var buffer = []
buffer = buffer.concat(convert.numToBytes(parseInt(this.version), 4))
buffer = buffer.concat(convert.numToVarInt(this.ins.length))
2013-03-02 18:00:14 +01:00
2014-03-31 05:47:47 +02:00
this.ins.forEach(function(txin) {
// Why do blockchain.info, blockexplorer.com, sx and just about everybody
// else use little-endian hashes? No idea...
buffer = buffer.concat(convert.hexToBytes(txin.outpoint.hash).reverse())
2013-03-02 18:00:14 +01:00
2014-03-31 05:47:47 +02:00
buffer = buffer.concat(convert.numToBytes(parseInt(txin.outpoint.index), 4))
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
var scriptBytes = txin.script.buffer
buffer = buffer.concat(convert.numToVarInt(scriptBytes.length))
buffer = buffer.concat(scriptBytes)
buffer = buffer.concat(txin.sequence)
})
2014-03-31 05:47:47 +02:00
buffer = buffer.concat(convert.numToVarInt(this.outs.length))
2014-03-31 05:47:47 +02:00
this.outs.forEach(function(txout) {
buffer = buffer.concat(convert.numToBytes(txout.value,8))
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
var scriptBytes = txout.script.buffer
buffer = buffer.concat(convert.numToVarInt(scriptBytes.length))
buffer = buffer.concat(scriptBytes)
})
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
buffer = buffer.concat(convert.numToBytes(parseInt(this.locktime), 4))
2014-03-31 05:47:47 +02:00
return buffer
}
Transaction.prototype.serializeHex = function() {
2014-03-31 05:47:47 +02:00
return convert.bytesToHex(this.serialize())
}
2014-03-31 05:47:47 +02:00
//var OP_CODESEPARATOR = 171
2014-03-31 05:47:47 +02:00
var SIGHASH_ALL = 1
var SIGHASH_NONE = 2
var SIGHASH_SINGLE = 3
var SIGHASH_ANYONECANPAY = 80
/**
* Hash transaction for signing a specific input.
*
* Bitcoin uses a different hash for each signed transaction input. This
* method copies the transaction, makes the necessary changes based on the
* hashType, serializes and finally hashes the result. This hash can then be
* used to sign the transaction input in question.
*/
Transaction.prototype.hashTransactionForSignature =
2014-03-31 05:47:47 +02:00
function (connectedScript, inIndex, hashType)
{
2014-03-31 05:47:47 +02:00
var txTmp = this.clone()
// In case concatenating two scripts ends up with two codeseparators,
// or an extra one at the end, this prevents all those possible
// incompatibilities.
/*scriptCode = scriptCode.filter(function (val) {
2014-03-31 05:47:47 +02:00
return val !== OP_CODESEPARATOR
});*/
// Blank out other inputs' signatures
txTmp.ins.forEach(function(txin) {
2014-03-31 05:47:47 +02:00
txin.script = new Script()
})
2014-03-31 05:47:47 +02:00
txTmp.ins[inIndex].script = connectedScript
2014-03-21 03:15:15 +01:00
// Blank out some of the outputs
if ((hashType & 0x1f) == SIGHASH_NONE) {
2014-03-31 05:47:47 +02:00
txTmp.outs = []
2014-03-21 03:15:15 +01:00
// Let the others update at will
txTmp.ins.forEach(function(txin, i) {
if (i != inIndex) {
2014-03-31 05:47:47 +02:00
txTmp.ins[i].sequence = 0
}
2014-03-31 05:47:47 +02:00
})
2014-03-21 03:15:15 +01:00
} else if ((hashType & 0x1f) == SIGHASH_SINGLE) {
// TODO: Implement
}
// Blank out other inputs completely, not recommended for open transactions
if (hashType & SIGHASH_ANYONECANPAY) {
2014-03-31 05:47:47 +02:00
txTmp.ins = [txTmp.ins[inIndex]]
2014-03-21 03:15:15 +01:00
}
2014-03-31 05:47:47 +02:00
var buffer = txTmp.serialize()
buffer = buffer.concat(convert.numToBytes(parseInt(hashType), 4))
2014-03-23 20:01:33 +01:00
return crypto.hash256(buffer)
2014-03-31 05:47:47 +02:00
}
/**
* Calculate and return the transaction's hash.
2013-10-08 19:41:20 +02:00
* Reverses hash since blockchain.info, blockexplorer.com and others
* use little-endian hashes for some stupid reason
*/
Transaction.prototype.getHash = function ()
{
var buffer = this.serialize()
var hash = crypto.hash256(buffer)
2014-04-17 11:08:16 +02:00
return Array.prototype.slice.call(hash).reverse()
2014-03-31 05:47:47 +02:00
}
Transaction.prototype.clone = function ()
{
2014-03-31 05:47:47 +02:00
var newTx = new Transaction()
newTx.version = this.version
newTx.locktime = this.locktime
this.ins.forEach(function(txin) {
2014-03-31 05:47:47 +02:00
newTx.addInput(txin.clone())
})
this.outs.forEach(function(txout) {
2014-03-31 05:47:47 +02:00
newTx.addOutput(txout.clone())
})
2014-03-31 05:47:47 +02:00
return newTx
}
Transaction.deserialize = function(buffer) {
2014-03-31 05:47:47 +02:00
if (typeof buffer == "string") {
buffer = convert.hexToBytes(buffer)
}
var pos = 0
var readAsInt = function(bytes) {
if (bytes === 0) return 0;
pos++;
return buffer[pos-1] + readAsInt(bytes-1) * 256
}
var readVarInt = function() {
var bytes = buffer.slice(pos, pos + 9) // maximum possible number of bytes to read
var result = convert.varIntToNum(bytes)
2014-03-26 09:11:37 +01:00
2014-03-31 05:47:47 +02:00
pos += result.bytes.length
return result.number
}
var readBytes = function(bytes) {
pos += bytes
return buffer.slice(pos - bytes, pos)
}
var readVarString = function() {
var size = readVarInt()
return readBytes(size)
}
var obj = {
ins: [],
outs: []
}
obj.version = readAsInt(4)
var ins = readVarInt()
var i
for (i = 0; i < ins; i++) {
obj.ins.push({
outpoint: {
hash: convert.bytesToHex(readBytes(32).reverse()),
index: readAsInt(4)
},
script: new Script(readVarString()),
sequence: readBytes(4)
})
}
var outs = readVarInt()
2014-03-23 20:02:31 +01:00
2014-03-31 05:47:47 +02:00
for (i = 0; i < outs; i++) {
obj.outs.push({
value: convert.bytesToNum(readBytes(8)),
script: new Script(readVarString())
})
}
2014-03-23 20:02:31 +01:00
2014-03-31 05:47:47 +02:00
obj.locktime = readAsInt(4)
2014-03-31 05:47:47 +02:00
return new Transaction(obj)
}
/**
* Signs a standard output at some index with the given key
* FIXME: network support is ugly
*/
Transaction.prototype.sign = function(index, key, type, network) {
2014-04-17 11:08:16 +02:00
assert(key instanceof ECKey)
2014-03-31 05:47:47 +02:00
type = type || SIGHASH_ALL
network = network || Network.bitcoin
var address = key.pub.getAddress(network.pubKeyHash)
var script = Script.createOutputScript(address, network)
var hash = this.hashTransactionForSignature(script, index, type)
var sig = key.sign(hash).concat([type])
this.ins[index].script = Script.createInputScript(sig, key.pub)
}
// Takes outputs of the form [{ output: 'txhash:index', address: 'address' },...]
Transaction.prototype.signWithKeys = function(keys, outputs, type) {
2014-03-31 05:47:47 +02:00
type = type || SIGHASH_ALL
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
var addrdata = keys.map(function(key) {
2014-04-17 11:08:16 +02:00
assert(key instanceof ECKey)
2014-03-31 05:47:47 +02:00
return {
key: key,
address: key.getAddress().toString()
}
})
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
var hmap = {}
outputs.forEach(function(o) {
hmap[o.output] = o
})
2014-03-31 05:47:47 +02:00
for (var i = 0; i < this.ins.length; i++) {
var outpoint = this.ins[i].outpoint.hash + ':' + this.ins[i].outpoint.index
var histItem = hmap[outpoint]
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
if (!histItem) continue;
2014-03-23 20:01:33 +01:00
2014-03-31 05:47:47 +02:00
var thisInputAddrdata = addrdata.filter(function(a) {
return a.address == histItem.address
})
2014-03-23 20:04:43 +01:00
2014-03-31 05:47:47 +02:00
if (thisInputAddrdata.length === 0) continue;
2014-03-23 20:04:43 +01:00
2014-03-31 05:47:47 +02:00
this.sign(i,thisInputAddrdata[0].key)
}
}
/**
* Signs a P2SH output at some index with the given key
*/
Transaction.prototype.p2shsign = function(index, script, key, type) {
2014-03-31 05:47:47 +02:00
script = new Script(script)
key = new ECKey(key)
type = type || SIGHASH_ALL
var hash = this.hashTransactionForSignature(script, index, type),
sig = key.sign(hash).concat([type])
return sig
}
2014-03-31 05:47:47 +02:00
Transaction.prototype.multisign = Transaction.prototype.p2shsign
2014-03-23 20:00:16 +01:00
Transaction.prototype.applyMultisigs = function(index, script, sigs/*, type*/) {
2014-03-31 05:47:47 +02:00
this.ins[index].script = Script.createMultiSigInputScript(sigs, script)
2013-11-02 11:20:09 +01:00
}
Transaction.prototype.validateSig = function(index, script, sig, pub) {
2014-03-31 05:47:47 +02:00
script = new Script(script)
var hash = this.hashTransactionForSignature(script,index,1)
2014-04-08 19:58:55 +02:00
return ecdsa.verify(hash, convert.coerceToBytes(sig),
2014-03-31 05:47:47 +02:00
convert.coerceToBytes(pub))
}
2014-03-22 16:48:21 +01:00
Transaction.feePerKb = 20000
Transaction.prototype.estimateFee = function(feePerKb){
var uncompressedInSize = 180
var outSize = 34
var fixedPadding = 34
2014-03-26 01:37:07 +01:00
2014-03-31 05:47:47 +02:00
if(feePerKb == undefined) feePerKb = Transaction.feePerKb;
var size = this.ins.length * uncompressedInSize + this.outs.length * outSize + fixedPadding
2014-03-22 16:48:21 +01:00
return feePerKb * Math.ceil(size / 1000)
2014-03-22 16:48:21 +01:00
}
var TransactionIn = function (data) {
2014-03-31 05:47:47 +02:00
if (typeof data == "string") {
this.outpoint = { hash: data.split(':')[0], index: data.split(':')[1] }
} else if (data.outpoint) {
this.outpoint = data.outpoint
} else {
this.outpoint = { hash: data.hash, index: data.index }
}
if (data.scriptSig) {
this.script = Script.fromScriptSig(data.scriptSig)
} else if (data.script) {
this.script = data.script
} else {
this.script = new Script(data.script)
}
this.sequence = data.sequence || this.defaultSequence
}
TransactionIn.prototype.clone = function () {
2014-03-31 05:47:47 +02:00
return new TransactionIn({
outpoint: {
hash: this.outpoint.hash,
index: this.outpoint.index
},
script: this.script.clone(),
sequence: this.sequence
})
}
var TransactionOut = function (data) {
2014-03-31 05:47:47 +02:00
this.script =
data.script instanceof Script ? data.script.clone()
: Array.isArray(data.script) ? new Script(data.script)
: typeof data.script == "string" ? new Script(convert.hexToBytes(data.script))
: data.scriptPubKey ? Script.fromScriptSig(data.scriptPubKey)
: data.address ? Script.createOutputScript(data.address)
: new Script()
if (this.script.buffer.length > 0) this.address = this.script.getToAddress();
this.value =
Array.isArray(data.value) ? convert.bytesToNum(data.value)
: "string" == typeof data.value ? parseInt(data.value)
: data.value instanceof BigInteger ? parseInt(data.value.toString())
: data.value
}
2014-03-23 14:34:52 +01:00
TransactionOut.prototype.clone = function() {
var newTxout = new TransactionOut({
script: this.script.clone(),
value: this.value
2014-03-31 05:47:47 +02:00
})
return newTxout
}
2014-03-23 14:34:52 +01:00
TransactionOut.prototype.scriptPubKey = function() {
return convert.bytesToHex(this.script.buffer)
}
2014-03-23 20:01:33 +01:00
module.exports = {
Transaction: Transaction,
TransactionIn: TransactionIn,
TransactionOut: TransactionOut
}