-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
transaction.go
359 lines (302 loc) · 10.5 KB
/
transaction.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
package bitcoin
import (
"context"
"fmt"
"strings"
"github.com/libsv/go-bk/bec"
"github.com/libsv/go-bt/v2"
"github.com/libsv/go-bt/v2/bscript"
"github.com/libsv/go-bt/v2/unlocker"
)
const (
// DustLimit is the minimum value for a tx that can be spent
// Note: this is being deprecated in the new node software (TBD)
DustLimit uint64 = 546
)
// Utxo is an unspent transaction output
type Utxo struct {
Satoshis uint64 `json:"satoshis"`
ScriptPubKey string `json:"string"`
TxID string `json:"tx_id"`
Vout uint32 `json:"vout"`
}
// PayToAddress is the pay-to-address
type PayToAddress struct {
Address string `json:"address"`
Satoshis uint64 `json:"satoshis"`
}
// account is a struct/interface for implementing unlocker
type account struct {
PrivateKey *bec.PrivateKey
}
// Unlocker get the correct un-locker for a given locking script
func (a *account) Unlocker(context.Context, *bscript.Script) (bt.Unlocker, error) {
return &unlocker.Simple{
PrivateKey: a.PrivateKey,
}, nil
}
// OpReturnData is the op return data to include in the tx
type OpReturnData [][]byte
// TxFromHex will return a libsv.tx from a raw hex string
func TxFromHex(rawHex string) (*bt.Tx, error) {
return bt.NewTxFromString(rawHex)
}
// CreateTxWithChange will automatically create the change output and calculate fees
//
// Use this if you don't want to figure out fees/change for a tx
// USE AT YOUR OWN RISK - this will modify a "pay-to" output to accomplish auto-fees
func CreateTxWithChange(utxos []*Utxo, payToAddresses []*PayToAddress, opReturns []OpReturnData,
changeAddress string, standardRate, dataRate *bt.Fee,
privateKey *bec.PrivateKey) (*bt.Tx, error) {
// Missing utxo(s) or change address
if len(utxos) == 0 {
return nil, ErrUtxosRequired
} else if len(changeAddress) == 0 {
return nil, ErrChangeAddressRequired
}
// Accumulate the total satoshis from all utxo(s)
var totalSatoshis uint64
var totalPayToSatoshis uint64
var remainder uint64
var hasChange bool
// Loop utxos and get total usable satoshis
for _, utxo := range utxos {
totalSatoshis += utxo.Satoshis
}
// Loop all payout address amounts
for _, address := range payToAddresses {
totalPayToSatoshis += address.Satoshis
}
// Sanity check - already not enough satoshis?
if totalPayToSatoshis > totalSatoshis {
return nil, fmt.Errorf(
"not enough in utxo(s) to cover: %d + (fee), total found: %d",
totalPayToSatoshis,
totalSatoshis,
)
}
// Add the change address as the difference (all change except 1 sat for Draft tx)
// Only if the tx is NOT for the full amount
if totalPayToSatoshis != totalSatoshis {
hasChange = true
payToAddresses = append(payToAddresses, &PayToAddress{
Address: changeAddress,
Satoshis: totalSatoshis - (totalPayToSatoshis + 1),
})
}
// Create the "Draft tx"
fee, err := draftTx(utxos, payToAddresses, opReturns, privateKey, standardRate, dataRate)
if err != nil {
return nil, err
}
// Check that we have enough to cover the fee
if (totalPayToSatoshis + fee) > totalSatoshis {
// Remove temporary change address first
if hasChange {
payToAddresses = payToAddresses[:len(payToAddresses)-1]
}
// Re-run draft tx with no change address
if fee, err = draftTx(
utxos, payToAddresses, opReturns, privateKey, standardRate, dataRate,
); err != nil {
return nil, err
}
// Get the remainder missing (handle negative overflow safer)
totalToPay := totalPayToSatoshis + fee
if totalToPay >= totalSatoshis {
remainder = totalToPay - totalSatoshis
} else {
remainder = totalSatoshis - totalToPay
}
// Remove remainder from last used payToAddress (or continue until found)
feeAdjusted := false
for i := len(payToAddresses) - 1; i >= 0; i-- { // Working backwards
if payToAddresses[i].Satoshis > remainder {
payToAddresses[i].Satoshis = payToAddresses[i].Satoshis - remainder
feeAdjusted = true
break
}
}
// Fee was not adjusted (all inputs do not cover the fee)
if !feeAdjusted {
return nil, fmt.Errorf(
"auto-fee could not be applied without removing an output (payTo %d) "+
"(amount %d) (remainder %d) (fee %d) (total %d)",
len(payToAddresses), totalPayToSatoshis, remainder, fee, totalSatoshis,
)
}
} else {
// Remove the change address (old version with original satoshis)
// Add the change address as the difference (now with adjusted fee)
if hasChange {
payToAddresses = payToAddresses[:len(payToAddresses)-1]
payToAddresses = append(payToAddresses, &PayToAddress{
Address: changeAddress,
Satoshis: totalSatoshis - (totalPayToSatoshis + fee),
})
}
}
// Create the "Final tx" (or error)
return CreateTx(utxos, payToAddresses, opReturns, privateKey)
}
// draftTx is a helper method to create a draft tx and associated fees
func draftTx(utxos []*Utxo, payToAddresses []*PayToAddress, opReturns []OpReturnData,
privateKey *bec.PrivateKey, standardRate, dataRate *bt.Fee) (uint64, error) {
// Create the "Draft tx"
tx, err := CreateTx(utxos, payToAddresses, opReturns, privateKey)
if err != nil {
return 0, err
}
// Calculate the fees for the "Draft tx"
// todo: hack to add 1 extra sat - ensuring that fee is over the minimum with rounding issues in WOC and other systems
fee := CalculateFeeForTx(tx, standardRate, dataRate) + 1
return fee, nil
}
// CreateTxWithChangeUsingWif will automatically create the change output and calculate fees
//
// Use this if you don't want to figure out fees/change for a tx
// USE AT YOUR OWN RISK - this will modify a "pay-to" output to accomplish auto-fees
func CreateTxWithChangeUsingWif(utxos []*Utxo, payToAddresses []*PayToAddress, opReturns []OpReturnData,
changeAddress string, standardRate, dataRate *bt.Fee, wif string) (*bt.Tx, error) {
// Decode the WIF
privateKey, err := WifToPrivateKey(wif)
if err != nil {
return nil, err
}
// Create the "Final tx" (or error)
return CreateTxWithChange(utxos, payToAddresses, opReturns, changeAddress, standardRate, dataRate, privateKey)
}
// CreateTx will create a basic transaction and return the raw transaction (*transaction.Transaction)
//
// Note: this will NOT create a change output (funds are sent to "addresses")
// Note: this will NOT handle fee calculation (it's assumed you have already calculated the fee)
//
// Get the raw hex version: tx.ToString()
// Get the tx id: tx.GetTxID()
func CreateTx(utxos []*Utxo, addresses []*PayToAddress,
opReturns []OpReturnData, privateKey *bec.PrivateKey) (*bt.Tx, error) {
// Start creating a new transaction
tx := bt.NewTx()
// Accumulate the total satoshis from all utxo(s)
var totalSatoshis uint64
// Loop all utxos and add to the transaction
var err error
for _, utxo := range utxos {
if err = tx.From(utxo.TxID, utxo.Vout, utxo.ScriptPubKey, utxo.Satoshis); err != nil {
return nil, err
}
totalSatoshis += utxo.Satoshis
}
// Loop any pay addresses
for _, address := range addresses {
var a *bscript.Script
a, err = bscript.NewP2PKHFromAddress(address.Address)
if err != nil {
return nil, err
}
if err = tx.PayTo(a, address.Satoshis); err != nil {
return nil, err
}
}
// Loop any op returns
for _, op := range opReturns {
if err = tx.AddOpReturnPartsOutput(op); err != nil {
return nil, err
}
}
// If inputs are supplied, make sure they are sufficient for this transaction
if len(tx.Inputs) > 0 {
// Sanity check - not enough satoshis in utxo(s) to cover all paid amount(s)
// They should never be equal, since the fee is the spread between the two amounts
totalOutputSatoshis := tx.TotalOutputSatoshis() // Does not work properly
if totalOutputSatoshis > totalSatoshis {
return nil, fmt.Errorf("not enough in utxo(s) to cover: %d + (fee) found: %d", totalOutputSatoshis, totalSatoshis)
}
}
// Sign the transaction
if privateKey != nil {
myAccount := &account{PrivateKey: privateKey}
// todo: support context (ctx)
if err = tx.FillAllInputs(context.Background(), myAccount); err != nil {
return nil, err
}
}
// Return the transaction as a raw string
return tx, nil
}
// CreateTxUsingWif will create a basic transaction and return the raw transaction (*transaction.Transaction)
//
// Note: this will NOT create a "change" address (it's assumed you have already specified an address)
// Note: this will NOT handle "fee" calculation (it's assumed you have already calculated the fee)
//
// Get the raw hex version: tx.ToString()
// Get the tx id: tx.GetTxID()
func CreateTxUsingWif(utxos []*Utxo, addresses []*PayToAddress,
opReturns []OpReturnData, wif string) (*bt.Tx, error) {
// Decode the WIF
privateKey, err := WifToPrivateKey(wif)
if err != nil {
return nil, err
}
// Create the Tx
return CreateTx(utxos, addresses, opReturns, privateKey)
}
// DefaultStandardFee returns the default standard fees offered by most miners.
// this function is not public anymore in go-bt
func DefaultStandardFee() *bt.Fee {
return &bt.Fee{
FeeType: bt.FeeTypeStandard,
MiningFee: bt.FeeUnit{
Satoshis: 5,
Bytes: 10,
},
RelayFee: bt.FeeUnit{
Satoshis: 5,
Bytes: 10,
},
}
}
// CalculateFeeForTx will estimate a fee for the given transaction
//
// If tx is nil this will panic
// Rate(s) can be derived from MinerAPI (default is DefaultDataRate and DefaultStandardRate)
// If rate is nil it will use default rates (0.5 sat per byte)
// Reference: https://tncpw.co/c215a75c
func CalculateFeeForTx(tx *bt.Tx, standardRate, dataRate *bt.Fee) uint64 {
// Set the totals
var totalFee int
var totalDataBytes int
// Set defaults if not found
if standardRate == nil {
standardRate = DefaultStandardFee()
}
if dataRate == nil {
dataRate = DefaultStandardFee()
// todo: adjusted to 5/10 for now, since all miners accept that rate
dataRate.FeeType = bt.FeeTypeData
}
// Set the total bytes of the tx
totalBytes := len(tx.Bytes())
// Loop all outputs and accumulate size (find data related outputs)
for _, out := range tx.Outputs {
outHexString := out.LockingScriptHexString()
if strings.HasPrefix(outHexString, "006a") || strings.HasPrefix(outHexString, "6a") {
totalDataBytes += len(out.Bytes())
}
}
// Got some data bytes?
if totalDataBytes > 0 {
totalBytes = totalBytes - totalDataBytes
totalFee += (dataRate.MiningFee.Satoshis * totalDataBytes) / dataRate.MiningFee.Bytes
}
// Still have regular standard bytes?
if totalBytes > 0 {
totalFee += (standardRate.MiningFee.Satoshis * totalBytes) / standardRate.MiningFee.Bytes
}
// Safety check (possible division by zero?)
if totalFee == 0 {
totalFee = 1
}
// Return the total fee as an uint (easier to use with satoshi values)
return uint64(totalFee)
}