UNPKG

12.4 kBMarkdownView Raw
1# Transaction
2Bitcore provides a very simple API for creating transactions. We expect this API to be accessible for developers without knowing the working internals of bitcoin in deep detail. What follows is a small introduction to transactions with some basic knowledge required to use this API.
3
4A Transaction contains a set of inputs and a set of outputs. Each input contains a reference to another transaction's output, and a signature that allows the value referenced in that output to be used in this transaction.
5
6Note also that an output can be used only once. That's why there's a concept of "change address" in the bitcoin ecosystem: if an output of 10 BSV is available for me to spend, but I only need to transmit 1 BSV, I'll create a transaction with two outputs, one with 1 BSV that I want to spend, and the other with 9 BSV to a change address, so I can spend this 9 BSV with another private key that I own.
7
8So, in order to transmit a valid transaction, you must know what other transactions on the network store outputs that have not been spent and that are available for you to spend (meaning that you have the set of keys that can validate you own those funds). The unspent outputs are usually referred to as "utxo"s.
9
10Let's take a look at some very simple transactions:
11
12```javascript
13var transaction = new Transaction()
14 .from(utxos) // Feed information about what unspent outputs one can use
15 .to(address, amount) // Add an output with the given amount of satoshis
16 .change(address) // Sets up a change address where the rest of the funds will go
17 .sign(privkeySet) // Signs all the inputs it can
18```
19
20You can obtain the input and output total amounts of the transaction in satoshis by accessing the fields `inputAmount` and `outputAmount`.
21
22Now, this could just be serialized to hexadecimal ASCII values (`transaction.serialize()`) and sent over to the bitcoind reference client.
23
24```bash
25bitcoin-cli sendrawtransaction <serialized transaction>
26```
27
28You can also override the fee estimation with another amount, specified in satoshis:
29
30```javascript
31var transaction = new Transaction().fee(546); // Minimum non-dust amount
32var transaction = new Transaction().fee(1e8); // Generous fee of 1 BSV
33```
34
35## Multisig Transactions
36To send a transaction to a multisig address, the API is the same as in the above example. To spend outputs that require multiple signatures, the process needs extra information: the public keys of the signers that can unlock that output.
37
38```javascript
39var multiSigTx = new Transaction()
40 .from(utxo, publicKeys, threshold)
41 .change(address)
42 .sign(myKeys);
43
44var serialized = multiSigTx.toObject();
45```
46
47This can be serialized and sent to another party, to complete with the needed signatures:
48
49```javascript
50var multiSigTx = new Transaction(serialized)
51 .sign(anotherSetOfKeys);
52
53assert(multiSigTx.isFullySigned());
54```
55
56Also, you can just send over the signature for your private key:
57
58```javascript
59var multiSigTx = new Transaction()
60 .from(utxo, publicKeys, threshold)
61 .change(address);
62
63var signature = multiSigTx.getSignatures(privateKey)[0];
64console.log(JSON.stringify(signature));
65console.log(signature.toObject());
66console.log(signature.signature.toString()); // Outputs a DER signature
67console.log(signature.sigtype);
68```
69
70Transfer that over the wire, and on the other side, apply it to a transaction:
71
72```javascript
73assert(transaction.isValidSignature(receivedSig));
74transaction.applySignature(receivedSig);
75```
76
77## Adding inputs
78Transaction inputs are instances of either [Input](https://github.com/bitpay/bsv/tree/master/lib/transaction/input) or its subclasses. `Input` has some abstract methods, as there is no actual concept of a "signed input" in the bitcoin scripting system (just valid signatures for <tt>OP_CHECKSIG</tt> and similar opcodes). They are stored in the `input` property of `Transaction` instances.
79
80Bitcore contains two implementations of `Input`, one for spending _Pay to Public Key Hash_ outputs (called `PublicKeyHashInput`) and another to spend _Pay to Script Hash_ outputs for which the redeem script is a Multisig script (called `MultisigScriptHashInput`).
81
82All inputs have the following five properties:
83- `prevTxId`: a `Buffer` with the id of the transaction with the output this input is spending
84- `outputIndex`: a `number` the index of the output in the previous transaction
85- `sequenceNumber`: a `number`, the sequence number, see [bitcoin's developer guide on nLockTime and the sequence number](https://bitcoin.org/en/developer-guide#locktime-and-sequence-number).
86- `script`: the `Script` instance for this input. Usually called `scriptSig` in the bitcoin community.
87- `output`: if available, a `Output` instance of the output associated with this input.
88
89Both `PublicKeyHashInput` and `MultisigScriptHashInput` cache the information about signatures, even though this information could somehow be encoded in the script. Both need to have the `output` property set in order to calculate the `sighash` so signatures can be created.
90
91Some methods related to adding inputs are:
92- `from`: A high level interface to add an input from a UTXO. It has a series of variants:
93 - `from(utxo)`: add an input from an [Unspent Transaction Output](http://bsv.io/guide/unspentoutput.html). Currently, only P2PKH outputs are supported.
94 - `from(utxos)`: same as above, but passing in an array of Unspent Outputs.
95 - `from(utxo, publicKeys, threshold)`: add an input that spends a UTXO with a P2SH output for a Multisig script. The `publicKeys` argument is an array of public keys, and `threshold` is the number of required signatures in the Multisig script.
96
97- `addInput`: Performs a series of checks on an input and appends it to the end of the `input` vector and updates the amount of incoming bitcoins of the transaction.
98- `uncheckedAddInput`: adds an input to the end of the `input` vector and updates the `inputAmount` without performing any checks.
99
100### PublicKeyHashInput
101This input uses the `script` property to mark the input as unsigned if the script is empty.
102
103### MultisigScriptHashInput
104This input contains a set of signatures in a `signatures` property, and each time a signature is added, a potentially partial and/or invalid script is created. The `isFullySigned` method will only return true if all needed signatures are already added and valid. If `addSignature` is added after all need signatures are already set, an exception will be thrown.
105
106## Signing a Transaction
107The following methods are used to manage signatures for a transaction:
108- `getSignatures`: takes an array of `PrivateKey` or strings from which a `PrivateKey` can be instantiated; the transaction to be signed; the kind of [signature hash to use](https://bitcoin.org/en/developer-guide#signature-hash-types). Returns an array of objects with the following properties:
109 - `signature`: an instance of [Signature](https://github.com/bitpay/bsv/blob/master/lib/crypto/signature.js)
110 - `prevTxId`: this input's `prevTxId`,
111 - `outputIndex`: this input's `outputIndex`,
112 - `inputIndex`: this input's index in the transaction
113 - `sigtype`: the "sighash", the type of transaction hash used to calculate the signature
114 - `publicKey`: a `PublicKey` of the `PrivateKey` used to create the signature
115
116- `addSignature`: takes an element outputed by `getSignatures` and applies the signature to this input (modifies the script to include the new signature).
117- `clearSignatures`: removes all signatures for this input
118- `isFullySigned`: returns true if the input is fully signed
119
120## Handling Outputs
121Outputs can be added by:
122- The `addOutput(output)` method, which pushes an `Output` to the end of the `outputs` property and updates the `outputAmount` field. It also clears signatures (as the hash of the transaction may have changed) and updates the change output.
123- The `to(address, amount)` method, that adds an output with the script that corresponds to the given address. Builds an output and calls the `addOutput` method.
124- Specifying a [change address](#Fee_calculation)
125
126To remove all outputs, you can use `clearOutputs()`, which preserves change output configuration.
127
128## Serialization
129There are a series of methods used for serialization:
130- `toObject`: Returns a plain JavaScript object with no methods and enough information to fully restore the state of this transaction. Using other serialization methods (except for `toJSON`) will cause a some information to be lost.
131- `toJSON`: Will be called when using `JSON.stringify` to return JSON-encoded string using the output from `toObject`.
132- `toString` or `uncheckedSerialize`: Returns an hexadecimal serialization of the transaction, in the [serialization format for bitcoin](https://bitcoin.org/en/developer-reference#raw-transaction-format).
133- `serialize`: Does a series of checks before serializing the transaction
134- `inspect`: Returns a string with some information about the transaction (currently a string formatted as `<Transaction 000...000>`, that only shows the serialized value of the transaction.
135- `toBuffer`: Serializes the transaction for sending over the wire in the bitcoin network
136- `toBufferWriter`: Uses an already existing BufferWriter to copy over the serialized transaction
137
138## Serialization Checks
139When serializing, the bsv library performs a series of checks. These can be disabled by providing an object to the `serialize` method with the checks that you'll like to skip.
140- `disableLargeFees` avoids checking that the fee is no more than `Transaction.FEE_PER_KB * Transaction.FEE_SECURITY_MARGIN * size_in_kb`.
141- `disableSmallFees` avoids checking that the fee is less than `Transaction.FEE_PER_KB * size_in_kb / Transaction.FEE_SECURITY_MARGIN`.
142- `disableIsFullySigned` does not check if all inputs are fully signed
143- `disableDustOutputs` does not check for dust outputs being generated
144- `disableMoreOutputThanInput` avoids checking that the sum of the output amounts is less than or equal to the sum of the amounts for the outputs being spent in the transaction
145
146These are the current default values in the bsv library involved on these checks:
147- `Transaction.FEE_PER_KB`: `10000` (satoshis per kilobyte)
148- `Transaction.FEE_SECURITY_MARGIN`: `15`
149- `Transaction.DUST_AMOUNT`: `546` (satoshis)
150
151## Fee calculation
152When outputs' value don't sum up to the same amount that inputs, the difference in bitcoins goes to the miner of the block that includes this transaction. The concept of a "change address" usually is associated with this: an output with an address that can be spent by the creator of the transaction.
153
154For this reason, some methods in the Transaction class are provided:
155- `change(address)`: Set up the change address. This will set an internal `_changeScript` property that will store the change script associated with that address.
156- `fee(amount)`: Sets up the exact amount of fee to pay. If no change address is provided, this will raise an exception.
157- `getFee()`: returns the estimated fee amount to be paid, based on the size of the transaction, but disregarding the priority of the outputs.
158
159Internally, a `_changeIndex` property stores the index of the change output (so it can get updated when a new input or output is added).
160
161## Time-Locking transaction
162All bitcoin transactions contain a locktime field. The locktime indicates the earliest time a transaction can be added to the blockchain. Locktime allows signers to create time-locked transactions which will only become valid in the future, giving the signers a chance to change their minds. Locktime can be set in the form of a bitcoin block height (the transaction can only be included in a block with a higher height than specified) or a linux timestamp (transaction can only be confirmed after that time). For more information see [bitcoin's development guide section on locktime](https://bitcoin.org/en/developer-guide#locktime-and-sequence-number).
163
164In bsv, you can set a `Transaction`'s locktime by using the methods `Transaction#lockUntilDate` and `Transaction#lockUntilBlockHeight`. You can also get a friendly version of the locktime field via `Transaction#getLockTime`;
165
166For example:
167
168```javascript
169var future = new Date(2025,10,30); // Sun Nov 30 2025
170var transaction = new Transaction()
171 .lockUntilDate(future);
172console.log(transaction.getLockTime());
173// output similar to: Sun Nov 30 2025 00:00:00 GMT-0300 (ART)
174```