-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathinputs.go
More file actions
450 lines (380 loc) · 13.3 KB
/
inputs.go
File metadata and controls
450 lines (380 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
package txbuilder
import (
"fmt"
"github.com/tokenized/pkg/bitcoin"
"github.com/tokenized/pkg/wire"
"github.com/pkg/errors"
)
// InputAddress returns the address that is paying to the input.
func (tx *TxBuilder) InputAddress(index int) (bitcoin.RawAddress, error) {
if index >= len(tx.Inputs) {
return bitcoin.RawAddress{}, errors.New("Input index out of range")
}
return bitcoin.RawAddressFromLockingScript(tx.Inputs[index].LockingScript)
}
// AddInputUTXO adds an input to TxBuilder using a UTXO.
func (tx *TxBuilder) AddInputUTXO(utxo bitcoin.UTXO) error {
// Check that utxo isn't already an input.
for _, input := range tx.MsgTx.TxIn {
if input.PreviousOutPoint.Hash.Equal(&utxo.Hash) &&
input.PreviousOutPoint.Index == utxo.Index {
return errors.Wrapf(ErrDuplicateInput, "%d %s", utxo.Index, utxo.Hash)
}
}
input := &InputSupplement{
LockingScript: utxo.LockingScript,
Value: utxo.Value,
KeyID: utxo.KeyID,
}
tx.Inputs = append(tx.Inputs, input)
txin := wire.TxIn{
PreviousOutPoint: wire.OutPoint{Hash: utxo.Hash, Index: utxo.Index},
Sequence: wire.MaxTxInSequenceNum,
}
tx.MsgTx.AddTxIn(&txin)
return nil
}
func (tx *TxBuilder) UpdateInputUTXO(index int, utxo bitcoin.UTXO) error {
if index > len(tx.MsgTx.TxIn) {
return errors.New("Input index out of range")
}
// Check that utxo isn't already an input.
for i, input := range tx.MsgTx.TxIn {
if i == index {
continue
}
if input.PreviousOutPoint.Hash.Equal(&utxo.Hash) &&
input.PreviousOutPoint.Index == utxo.Index {
return errors.Wrapf(ErrDuplicateInput, "%s:%d", input.PreviousOutPoint.Hash,
input.PreviousOutPoint.Index)
}
}
input := tx.Inputs[index]
input.LockingScript = utxo.LockingScript
input.Value = utxo.Value
input.KeyID = utxo.KeyID
tx.MsgTx.TxIn[index].PreviousOutPoint.Hash = utxo.Hash
tx.MsgTx.TxIn[index].PreviousOutPoint.Index = utxo.Index
return nil
}
// InsertInput inserts an input into TxBuilder at the specified index.
func (tx *TxBuilder) InsertInput(index int, utxo bitcoin.UTXO) error {
if index > len(tx.MsgTx.TxIn) {
return errors.New("Input index out of range")
}
// Check that utxo isn't already an input.
for _, input := range tx.MsgTx.TxIn {
if input.PreviousOutPoint.Hash.Equal(&utxo.Hash) &&
input.PreviousOutPoint.Index == utxo.Index {
return errors.Wrapf(ErrDuplicateInput, "%s:%d", input.PreviousOutPoint.Hash,
input.PreviousOutPoint.Index)
}
}
input := &InputSupplement{
LockingScript: utxo.LockingScript,
Value: utxo.Value,
KeyID: utxo.KeyID,
}
afterInputs := make([]*InputSupplement, len(tx.Inputs)-index)
copy(afterInputs, tx.Inputs[index:])
tx.Inputs = append(append(tx.Inputs[:index], input), afterInputs...)
txin := &wire.TxIn{
PreviousOutPoint: wire.OutPoint{Hash: utxo.Hash, Index: utxo.Index},
Sequence: wire.MaxTxInSequenceNum,
}
afterTxIn := make([]*wire.TxIn, len(tx.MsgTx.TxIn)-index)
copy(afterTxIn, tx.MsgTx.TxIn[index:])
tx.MsgTx.TxIn = append(append(tx.MsgTx.TxIn[:index], txin), afterTxIn...)
return nil
}
// AddInput adds an input to TxBuilder.
//
// outpoint - reference the output being spent.
// lockingScript - the script from the output being spent.
// value - the number of satoshis from the output being spent.
func (tx *TxBuilder) AddInput(outpoint wire.OutPoint, lockingScript bitcoin.Script,
value uint64) error {
// Check that outpoint isn't already an input.
for _, input := range tx.MsgTx.TxIn {
if input.PreviousOutPoint.Hash.Equal(&outpoint.Hash) &&
input.PreviousOutPoint.Index == outpoint.Index {
return errors.Wrapf(ErrDuplicateInput, "%d %s", outpoint.Index, outpoint.Hash)
}
}
input := InputSupplement{
LockingScript: lockingScript,
Value: value,
}
tx.Inputs = append(tx.Inputs, &input)
tx.MsgTx.AddTxIn(wire.NewTxIn(&outpoint, nil))
return nil
}
func (tx *TxBuilder) RemoveInput(index int) error {
if index >= len(tx.Inputs) || index >= len(tx.MsgTx.TxIn) {
return errors.New("Input index out of range")
}
tx.Inputs = append(tx.Inputs[:index], tx.Inputs[index+1:]...)
tx.MsgTx.TxIn = append(tx.MsgTx.TxIn[:index], tx.MsgTx.TxIn[index+1:]...)
return nil
}
// AddFunding adds inputs spending the specified UTXOs until the transaction has enough funding to
// cover the fees and outputs.
// If SendMax is set then all UTXOs are added as inputs.
func (tx *TxBuilder) AddFunding(utxos []bitcoin.UTXO) error {
inputValue := tx.InputValue()
outputValue := tx.OutputValue(true)
estFeeValue := tx.EstimatedFee()
if !tx.SendMax && inputValue > outputValue && inputValue-outputValue >= estFeeValue {
return tx.CalculateFee() // Already funded
}
if len(utxos) == 0 {
return errors.Wrap(ErrInsufficientValue, fmt.Sprintf("no more utxos: %d/%d",
inputValue, outputValue+estFeeValue))
}
// Calculate additional funding needed. Include cost of first added input.
// TODO Add support for input scripts other than P2PKH.
neededFunding := estFeeValue + outputValue - inputValue
changeOutputFee := uint64(0)
duplicateValue := uint64(0)
// Calculate the dust limit used when determining if a change output will be added
var changeDustLimit uint64
for i, output := range tx.Outputs {
if !output.IsRemainder {
continue
}
changeOutputFee = uint64(tx.MsgTx.TxOut[i].SerializeSize())
changeDustLimit = DustLimitForOutput(tx.MsgTx.TxOut[i], tx.DustFeeRate)
if changeDustLimit > 0 {
break
}
}
if changeDustLimit == 0 && len(tx.ChangeScript) > 0 {
changeOutputFee, changeDustLimit = OutputFeeAndDustForLockingScript(tx.ChangeScript,
tx.DustFeeRate, tx.FeeRate)
}
if changeDustLimit == 0 {
// Use P2PKH dust limit
changeDustLimit = DustLimit(P2PKHOutputSize, tx.DustFeeRate)
changeOutputFee = uint64(float32(P2PKHOutputSize) * tx.FeeRate)
}
for _, utxo := range utxos {
if err := tx.AddInputUTXO(utxo); err != nil {
if errors.Cause(err) == ErrDuplicateInput {
duplicateValue += utxo.Value
continue
}
return errors.Wrap(err, "adding input")
}
inputFee, err := UTXOFee(utxo, tx.FeeRate)
if err != nil {
return errors.Wrap(err, "utxo fee")
}
neededFunding += inputFee // Add cost of input
if tx.SendMax {
continue
}
if neededFunding <= utxo.Value {
// Funding complete
change := utxo.Value - neededFunding
if change > changeDustLimit {
for i, output := range tx.Outputs {
if output.IsRemainder {
// Updating existing "change" output
tx.MsgTx.TxOut[i].Value += change
return nil
}
}
if change > changeDustLimit+changeOutputFee {
// Add new change output
change -= changeOutputFee
if len(tx.ChangeScript) == 0 {
return errors.Wrap(ErrChangeAddressNeeded, fmt.Sprintf("Remaining: %d",
change))
}
if err := tx.AddOutput(tx.ChangeScript, change, true, false); err != nil {
return errors.Wrap(err, "adding change")
}
tx.Outputs[len(tx.Outputs)-1].KeyID = tx.ChangeKeyID
}
}
return nil
}
// More UTXOs required
neededFunding -= utxo.Value // Subtract the value this input added
}
if tx.SendMax {
return tx.CalculateFee()
} else {
available := uint64(0)
for _, input := range tx.Inputs {
available += input.Value
}
return errors.Wrap(ErrInsufficientValue, fmt.Sprintf("%d/%d", available,
outputValue+tx.EstimatedFee()))
}
return nil
}
// AddFundingBreakChange adds inputs spending the specified UTXOs until the transaction has enough
// funding to cover the fees and outputs.
// If SendMax is set then all UTXOs are added as inputs.
// If there is already an IsRemainder output, then it will get all of the "change" and it won't be
// broken up.
// tx.ChangeScript is ignored.
// breakValue should be a fairly low value that is the smallest UTXO you want created other than
// the remainder.
// It is recommended to provide at least 5 change addresses. More addresses means more privacy, but
// also more UTXOs and more tx fees.
func (tx *TxBuilder) AddFundingBreakChange(utxos []bitcoin.UTXO, breakValue uint64,
changeAddresses []AddressKeyID) error {
// Calculate the dust limit used when determining if a change output will be added
remainderIncluded := false
for _, output := range tx.Outputs {
if !output.IsRemainder {
continue
}
remainderIncluded = true
break
}
firstChangeOutputSize := uint64(0)
if !remainderIncluded && len(changeAddresses) > 0 {
lockingScript, err := changeAddresses[0].Address.LockingScript()
if err != nil {
return errors.Wrap(err, "first change locking script")
}
firstChangeOutputSize = uint64(OutputSize(lockingScript))
}
inputValue := tx.InputValue()
outputValue := tx.OutputValue(true)
estSize := uint64(tx.EstimatedSize()) + firstChangeOutputSize
feeRate := float64(tx.FeeRate)
estFeeValue := EstimatedFeeValue(estSize, feeRate)
changeLockingScript, err := changeAddresses[0].Address.LockingScript()
if err != nil {
return errors.Wrap(err, "change locking script")
}
outputFee, inputFee, _ := OutputTotalCost(changeLockingScript, tx.FeeRate)
// Check if tx is already funded.
if !tx.SendMax && inputValue > outputValue && inputValue-outputValue >= estFeeValue {
if !remainderIncluded {
// Ensure added change output is funded
if inputValue-outputValue >= estFeeValue+outputFee+inputFee {
if err := tx.SetChangeAddress(changeAddresses[0].Address,
changeAddresses[0].KeyID); err != nil {
return errors.Wrap(err, "set change address")
}
return tx.CalculateFee() // Already funded
}
} else {
return tx.CalculateFee() // Already funded
}
}
if len(utxos) == 0 {
return errors.Wrap(ErrInsufficientValue, fmt.Sprintf("no more utxos: %d/%d", inputValue,
outputValue+estFeeValue))
}
// Calculate additional funding needed. Include cost of first added input.
// TODO Add support for input scripts other than P2PKH.
estFeeValue = EstimatedFeeValue(estSize, feeRate)
neededFunding := estFeeValue + outputValue - inputValue
duplicateValue := uint64(0)
for _, utxo := range utxos {
if err := tx.AddInputUTXO(utxo); err != nil {
if errors.Cause(err) == ErrDuplicateInput {
duplicateValue += utxo.Value
continue
}
return errors.Wrap(err, "adding input")
}
inputSize, err := InputSize(utxo.LockingScript)
if err != nil {
return errors.Wrap(err, "input size")
}
estSize += uint64(inputSize)
estFeeValue = EstimatedFeeValue(estSize, feeRate)
neededFunding = estFeeValue + outputValue - inputValue
inputValue += utxo.Value
if tx.SendMax {
continue
}
if neededFunding <= utxo.Value {
// Funding complete
// Re-calculate fee without estimating first change output because BreakValue will take
// the fees out of the values.
finalFeeValue := EstimatedFeeValue(estSize-firstChangeOutputSize, feeRate)
finalNeededFunding := finalFeeValue + outputValue - inputValue + utxo.Value
changeValue := utxo.Value - finalNeededFunding
if remainderIncluded {
for i, output := range tx.Outputs {
if output.IsRemainder {
// Updating existing "change" output
tx.MsgTx.TxOut[i].Value += changeValue
return nil
}
}
return errors.New("Missing remainder that was previously there!")
} else {
// Break change between supplied addresses.
outputs, err := BreakValue(changeValue, breakValue, changeAddresses, tx.DustFeeRate,
tx.FeeRate, true, true)
if err != nil {
return errors.Wrap(err, "break change")
}
tx.AddOutputs(outputs)
if len(outputs) > 1 {
for _, output := range outputs[1:] {
estSize += uint64(output.TxOut.SerializeSize())
}
}
}
return nil
}
// More UTXOs required
estFeeValue = EstimatedFeeValue(estSize, feeRate)
neededFunding = estFeeValue + outputValue - inputValue
}
if tx.SendMax {
return tx.CalculateFee()
}
available := uint64(0)
for _, input := range tx.Inputs {
available += input.Value
}
return errors.Wrap(ErrInsufficientValue, fmt.Sprintf("%d/%d", available,
outputValue+tx.EstimatedFee()))
}
// UTXOFee calculates the tx fee for the input to spend the UTXO.
func UTXOFee(utxo bitcoin.UTXO, feeRate float32) (uint64, error) {
size, err := InputSize(utxo.LockingScript)
if err != nil {
return 0, errors.Wrap(err, "unlock size")
}
return EstimatedFeeValue(uint64(size), float64(feeRate)), nil
}
func UTXOInputSizeAndFee(utxo bitcoin.UTXO, feeRate float32) (int, uint64, error) {
size, err := InputSize(utxo.LockingScript)
if err != nil {
return 0, 0, errors.Wrap(err, "unlock size")
}
return size, EstimatedFeeValue(uint64(size), float64(feeRate)), nil
}
// LockingScriptInputFee returns the tx fee to spend a locking script in an input in a tx.
func LockingScriptInputFee(lockingScript bitcoin.Script, feeRate float32) (uint64, error) {
size, err := InputSize(lockingScript)
if err != nil {
return 0, errors.Wrap(err, "unlock size")
}
return EstimatedFeeValue(uint64(size), float64(feeRate)), nil
}
// AddressOutputFee returns the tx fee to include an address as an output in a tx.
func AddressOutputFee(ra bitcoin.RawAddress, feeRate float32) (uint64, error) {
lockingScript, err := ra.LockingScript()
if err != nil {
return 0, errors.Wrap(err, "locking script")
}
return LockingScriptOutputFee(lockingScript, feeRate), nil
}
// LockingScriptOutputFee returns the tx fee to include a locking script as an output in a tx.
func LockingScriptOutputFee(lockingScript bitcoin.Script, feeRate float32) uint64 {
txout := wire.TxOut{LockingScript: lockingScript}
return EstimatedFeeValue(uint64(txout.SerializeSize()), float64(feeRate))
}