forked from libsv/go-bt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtx.go
433 lines (343 loc) · 11.5 KB
/
tx.go
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
package bt
import (
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"github.com/libsv/go-bt/bscript"
"github.com/libsv/go-bt/crypto"
)
/*
General format of a Bitcoin transaction (inside a block)
--------------------------------------------------------
Field Description Size
Version no currently 1 4 bytes
In-counter positive integer VI = VarInt 1 - 9 bytes
list of inputs the first input of the first transaction is also called "coinbase" <in-counter>-many inputs
(its content was ignored in earlier versions)
Out-counter positive integer VI = VarInt 1 - 9 bytes
list of outputs the outputs of the first transaction spend the mined <out-counter>-many outputs
bitcoins for the block
lock_time if non-zero and sequence numbers are < 0xFFFFFFFF: block height or 4 bytes
timestamp when transaction is final
--------------------------------------------------------
*/
// Tx wraps a bitcoin transaction
//
// DO NOT CHANGE ORDER - Optimized memory via malign
//
type Tx struct {
// TODO: make variables private?
Inputs []*Input
Outputs []*Output
Version uint32
LockTime uint32
}
// NewTx creates a new transaction object with default values.
func NewTx() *Tx {
return &Tx{Version: 1, LockTime: 0}
}
// NewTxFromString takes a toBytesHelper string representation of a bitcoin transaction
// and returns a Tx object.
func NewTxFromString(str string) (*Tx, error) {
bytes, err := hex.DecodeString(str)
if err != nil {
return nil, err
}
return NewTxFromBytes(bytes)
}
// NewTxFromBytes takes an array of bytes, constructs a Tx and returns it.
func NewTxFromBytes(b []byte) (*Tx, error) {
if len(b) < 10 {
return nil, fmt.Errorf("too short to be a tx - even an empty tx has 10 bytes")
}
var offset = 0
t := Tx{
Version: binary.LittleEndian.Uint32(b[offset:4]),
}
offset += 4
inputCount, size := DecodeVarInt(b[offset:])
offset += size
// create inputs
var i uint64
var err error
var input *Input
for ; i < inputCount; i++ {
input, size, err = NewInputFromBytes(b[offset:])
if err != nil {
return nil, err
}
offset += size
t.Inputs = append(t.Inputs, input)
}
// create outputs
var outputCount uint64
var output *Output
outputCount, size = DecodeVarInt(b[offset:])
offset += size
for i = 0; i < outputCount; i++ {
output, size, err = NewOutputFromBytes(b[offset:])
if err != nil {
return nil, err
}
offset += size
t.Outputs = append(t.Outputs, output)
}
nLT := b[offset:]
if len(nLT) != 4 {
return nil, fmt.Errorf("nLockTime length must be 4 bytes long")
}
t.LockTime = binary.LittleEndian.Uint32(b[offset:])
// offset += 4 // @mrz I commented this out, as it was ineffectual
return &t, nil
}
// AddInput adds a new input to the transaction.
func (tx *Tx) AddInput(input *Input) {
tx.Inputs = append(tx.Inputs, input)
}
// From adds a new input to the transaction from the specified UTXO fields.
func (tx *Tx) From(txID string, vout uint32, prevTxLockingScript string, satoshis uint64) error {
pts, err := bscript.NewFromHexString(prevTxLockingScript)
if err != nil {
return err
}
tx.AddInput(&Input{
PreviousTxID: txID,
PreviousTxOutIndex: vout,
PreviousTxSatoshis: satoshis,
PreviousTxScript: pts,
SequenceNumber: DefaultSequenceNumber,
})
return nil
}
// InputCount returns the number of transaction inputs.
func (tx *Tx) InputCount() int {
return len(tx.Inputs)
}
// OutputCount returns the number of transaction inputs.
func (tx *Tx) OutputCount() int {
return len(tx.Outputs)
}
// AddOutput adds a new output to the transaction.
func (tx *Tx) AddOutput(output *Output) {
tx.Outputs = append(tx.Outputs, output)
}
// PayTo creates a new P2PKH output from a BitCoin address (base58)
// and the satoshis amount and adds that to the transaction.
func (tx *Tx) PayTo(addr string, satoshis uint64) error {
o, err := NewP2PKHOutputFromAddress(addr, satoshis)
if err != nil {
return err
}
tx.AddOutput(o)
return nil
}
// ChangeToAddress calculates the amount of fees needed to cover the transaction
// and adds the left over change in a new P2PKH output using the address provided.
func (tx *Tx) ChangeToAddress(addr string, f []*Fee) error {
s, err := bscript.NewP2PKHFromAddress(addr)
if err != nil {
return err
}
return tx.Change(s, f)
}
// Change calculates the amount of fees needed to cover the transaction
// and adds the left over change in a new output using the script provided.
func (tx *Tx) Change(s *bscript.Script, f []*Fee) error {
inputAmount := tx.GetTotalInputSatoshis()
outputAmount := tx.GetTotalOutputSatoshis()
if inputAmount < outputAmount {
return errors.New("satoshis inputted to the tx are less than the outputted satoshis")
}
available := inputAmount - outputAmount
standardFees, err := GetStandardFee(f)
if err != nil {
return err
}
if !tx.canAddChange(available, standardFees) {
return nil
}
tx.AddOutput(&Output{Satoshis: 0, LockingScript: s})
var preSignedFeeRequired uint64
if preSignedFeeRequired, err = tx.getPreSignedFeeRequired(f); err != nil {
return err
}
var expectedUnlockingScriptFees uint64
if expectedUnlockingScriptFees, err = tx.getExpectedUnlockingScriptFees(f); err != nil {
return err
}
available -= preSignedFeeRequired + expectedUnlockingScriptFees
// add rest of available sats to the change output
tx.Outputs[len(tx.GetOutputs())-1].Satoshis = available
return nil
}
func (tx *Tx) canAddChange(available uint64, standardFees *Fee) bool {
varIntUpper := VarIntUpperLimitInc(uint64(tx.OutputCount()))
if varIntUpper == -1 {
return false // upper limit of outputs in one tx reached
}
changeOutputFee := uint64(varIntUpper)
changeP2pkhByteLen := 8 + 25 // 8 bytes for satoshi value + 25 bytes for p2pkh script (e.g. 76a914cc...05388ac)
changeOutputFee += uint64(changeP2pkhByteLen * standardFees.MiningFee.Satoshis / standardFees.MiningFee.Bytes)
// not enough change to add a whole change output so don't add anything and return
return available >= changeOutputFee
}
func (tx *Tx) getPreSignedFeeRequired(f []*Fee) (uint64, error) {
standardBytes, dataBytes := tx.getStandardAndDataBytes()
standardFee, err := GetStandardFee(f)
if err != nil {
return 0, err
}
fr := standardBytes * standardFee.MiningFee.Satoshis / standardFee.MiningFee.Bytes
var dataFee *Fee
if dataFee, err = GetDataFee(f); err != nil {
return 0, err
}
fr += dataBytes * dataFee.MiningFee.Satoshis / dataFee.MiningFee.Bytes
return uint64(fr), nil
}
func (tx *Tx) getExpectedUnlockingScriptFees(f []*Fee) (uint64, error) {
standardFee, err := GetStandardFee(f)
if err != nil {
return 0, err
}
var expectedBytes int
for _, in := range tx.GetInputs() {
if !in.PreviousTxScript.IsP2PKH() {
return 0, errors.New("non-P2PKH input used in the tx - unsupported")
}
expectedBytes += 109 // = 1 oppushdata + 70-73 sig + 1 sighash + 1 oppushdata + 33 public key
}
return uint64(expectedBytes * standardFee.MiningFee.Satoshis / standardFee.MiningFee.Bytes), nil
}
func (tx *Tx) getStandardAndDataBytes() (standardBytes, dataBytes int) {
// Subtract the value of each output as well as keeping track of data outputs
for _, out := range tx.GetOutputs() {
if out.LockingScript.IsData() && len(*out.LockingScript) > 0 {
dataBytes += len(*out.LockingScript)
}
}
standardBytes = len(tx.ToBytes()) - dataBytes
return
}
// HasDataOutputs returns true if the transaction has
// at least one data (OP_RETURN) output in it.
func (tx *Tx) HasDataOutputs() bool {
for _, out := range tx.GetOutputs() {
if out.LockingScript.IsData() {
return true
}
}
return false
}
// IsCoinbase determines if this transaction is a coinbase by
// checking if the tx input is a standard coinbase input.
func (tx *Tx) IsCoinbase() bool {
if len(tx.Inputs) != 1 {
return false
}
// todo: make constant(s)?
if tx.Inputs[0].PreviousTxID != "0000000000000000000000000000000000000000000000000000000000000000" {
return false
}
if tx.Inputs[0].PreviousTxOutIndex == DefaultSequenceNumber || tx.Inputs[0].SequenceNumber == DefaultSequenceNumber {
return true
}
return false
}
// GetInputs returns an array of all inputs in the transaction.
func (tx *Tx) GetInputs() []*Input {
return tx.Inputs
}
// GetTotalInputSatoshis returns the total Satoshis inputted to the transaction.
func (tx *Tx) GetTotalInputSatoshis() (total uint64) {
for _, in := range tx.GetInputs() {
total += in.PreviousTxSatoshis
}
return
}
// GetOutputs returns an array of all outputs in the transaction.
func (tx *Tx) GetOutputs() []*Output {
return tx.Outputs
}
// GetTotalOutputSatoshis returns the total Satoshis outputted from the transaction.
func (tx *Tx) GetTotalOutputSatoshis() (total uint64) {
for _, o := range tx.GetOutputs() {
total += o.Satoshis
}
return
}
// GetTxID returns the transaction ID of the transaction
// (which is also the transaction hash).
func (tx *Tx) GetTxID() string {
return hex.EncodeToString(ReverseBytes(crypto.Sha256d(tx.ToBytes())))
}
// ToString encodes the transaction into a hex string.
func (tx *Tx) ToString() string {
return hex.EncodeToString(tx.ToBytes())
}
// ToBytes encodes the transaction into a byte array.
// See https://chainquery.com/bitcoin-cli/decoderawtransaction
func (tx *Tx) ToBytes() []byte {
return tx.toBytesHelper(0, nil)
}
// ToBytesWithClearedInputs encodes the transaction into a byte array but clears its inputs first.
// This is used when signing transactions.
func (tx *Tx) ToBytesWithClearedInputs(index int, lockingScript []byte) []byte {
return tx.toBytesHelper(index, lockingScript)
}
func (tx *Tx) toBytesHelper(index int, lockingScript []byte) []byte {
h := make([]byte, 0)
h = append(h, GetLittleEndianBytes(tx.Version, 4)...)
h = append(h, VarInt(uint64(len(tx.GetInputs())))...)
for i, in := range tx.GetInputs() {
s := in.ToBytes(lockingScript != nil)
if i == index && lockingScript != nil {
h = append(h, VarInt(uint64(len(lockingScript)))...)
h = append(h, lockingScript...)
} else {
h = append(h, s...)
}
}
h = append(h, VarInt(uint64(len(tx.GetOutputs())))...)
for _, out := range tx.GetOutputs() {
h = append(h, out.ToBytes()...)
}
lt := make([]byte, 4)
binary.LittleEndian.PutUint32(lt, tx.LockTime)
return append(h, lt...)
}
// Sign is used to sign the transaction at a specific input index.
// It takes a Signed interface as a parameter so that different
// signing implementations can be used to sign the transaction -
// for example internal/local or external signing.
func (tx *Tx) Sign(index uint32, s Signer) error {
signedTx, err := s.Sign(index, tx)
if err != nil {
return err
}
*tx = *signedTx
return nil
}
// SignAuto is used to automatically check which P2PKH inputs are
// able to be signed (match the public key) and then sign them.
// It takes a Signed interface as a parameter so that different
// signing implementations can be used to sign the transaction -
// for example internal/local or external signing.
func (tx *Tx) SignAuto(s Signer) error {
signedTx, err := s.SignAuto(tx)
if err != nil {
return err
}
*tx = *signedTx
return nil
}
// ApplyUnlockingScript applies a script to the transaction at a specific index in
// unlocking script field.
func (tx *Tx) ApplyUnlockingScript(index uint32, s *bscript.Script) error {
if tx.Inputs[index] != nil {
tx.Inputs[index].UnlockingScript = s
return nil
}
return fmt.Errorf("no input at index %d", index)
}