forked from planetdecred/dcrlibwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtxauthor.go
410 lines (344 loc) · 11.3 KB
/
txauthor.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
package dcrlibwallet
import (
"bytes"
"context"
"fmt"
"strconv"
"strings"
"time"
"decred.org/dcrwallet/v2/errors"
w "decred.org/dcrwallet/v2/wallet"
"decred.org/dcrwallet/v2/wallet/txauthor"
"decred.org/dcrwallet/v2/wallet/txrules"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/wire"
"github.com/planetdecred/dcrlibwallet/txhelper"
)
type TxAuthor struct {
sourceWallet *Wallet
sourceAccountNumber uint32
destinations []TransactionDestination
changeAddress string
inputs []*wire.TxIn
changeDestination *TransactionDestination
unsignedTx *txauthor.AuthoredTx
needsConstruct bool
}
func (mw *MultiWallet) NewUnsignedTx(walletID int, sourceAccountNumber int32) (*TxAuthor, error) {
sourceWallet := mw.WalletWithID(walletID)
if sourceWallet == nil {
return nil, fmt.Errorf(ErrWalletNotFound)
}
_, err := sourceWallet.GetAccount(sourceAccountNumber)
if err != nil {
return nil, err
}
return &TxAuthor{
sourceWallet: sourceWallet,
sourceAccountNumber: uint32(sourceAccountNumber),
destinations: make([]TransactionDestination, 0),
needsConstruct: true,
}, nil
}
func (tx *TxAuthor) AddSendDestination(address string, atomAmount int64, sendMax bool) error {
_, err := stdaddr.DecodeAddress(address, tx.sourceWallet.chainParams)
if err != nil {
return translateError(err)
}
if err := tx.validateSendAmount(sendMax, atomAmount); err != nil {
return err
}
tx.destinations = append(tx.destinations, TransactionDestination{
Address: address,
AtomAmount: atomAmount,
SendMax: sendMax,
})
tx.needsConstruct = true
return nil
}
func (tx *TxAuthor) UpdateSendDestination(index int, address string, atomAmount int64, sendMax bool) error {
if err := tx.validateSendAmount(sendMax, atomAmount); err != nil {
return err
}
if len(tx.destinations) < index {
return errors.New(ErrIndexOutOfRange)
}
tx.destinations[index] = TransactionDestination{
Address: address,
AtomAmount: atomAmount,
SendMax: sendMax,
}
tx.needsConstruct = true
return nil
}
func (tx *TxAuthor) RemoveSendDestination(index int) {
if len(tx.destinations) > index {
tx.destinations = append(tx.destinations[:index], tx.destinations[index+1:]...)
tx.needsConstruct = true
}
}
func (tx *TxAuthor) SendDestination(atIndex int) *TransactionDestination {
return &tx.destinations[atIndex]
}
func (tx *TxAuthor) SetChangeDestination(address string) {
tx.changeDestination = &TransactionDestination{
Address: address,
}
tx.needsConstruct = true
}
func (tx *TxAuthor) RemoveChangeDestination() {
tx.changeDestination = nil
tx.needsConstruct = true
}
func (tx *TxAuthor) TotalSendAmount() *Amount {
var totalSendAmountAtom int64 = 0
for _, destination := range tx.destinations {
totalSendAmountAtom += destination.AtomAmount
}
return &Amount{
AtomValue: totalSendAmountAtom,
DcrValue: dcrutil.Amount(totalSendAmountAtom).ToCoin(),
}
}
func (tx *TxAuthor) EstimateFeeAndSize() (*TxFeeAndSize, error) {
unsignedTx, err := tx.unsignedTransaction()
if err != nil {
return nil, translateError(err)
}
feeToSendTx := txrules.FeeForSerializeSize(txrules.DefaultRelayFeePerKb, unsignedTx.EstimatedSignedSerializeSize)
feeAmount := &Amount{
AtomValue: int64(feeToSendTx),
DcrValue: feeToSendTx.ToCoin(),
}
var change *Amount
if unsignedTx.ChangeIndex >= 0 {
txOut := unsignedTx.Tx.TxOut[unsignedTx.ChangeIndex]
change = &Amount{
AtomValue: txOut.Value,
DcrValue: AmountCoin(txOut.Value),
}
}
return &TxFeeAndSize{
EstimatedSignedSize: unsignedTx.EstimatedSignedSerializeSize,
Fee: feeAmount,
Change: change,
}, nil
}
func (tx *TxAuthor) EstimateMaxSendAmount() (*Amount, error) {
txFeeAndSize, err := tx.EstimateFeeAndSize()
if err != nil {
return nil, err
}
spendableAccountBalance, err := tx.sourceWallet.SpendableForAccount(int32(tx.sourceAccountNumber))
if err != nil {
return nil, err
}
maxSendableAmount := spendableAccountBalance - txFeeAndSize.Fee.AtomValue
return &Amount{
AtomValue: maxSendableAmount,
DcrValue: dcrutil.Amount(maxSendableAmount).ToCoin(),
}, nil
}
func (tx *TxAuthor) UseInputs(utxoKeys []string) error {
// first clear any previously set inputs
// so that an outdated set of inputs isn't used if an error occurs from this function
tx.inputs = nil
inputs := make([]*wire.TxIn, 0, len(utxoKeys))
for _, utxoKey := range utxoKeys {
idx := strings.Index(utxoKey, ":")
hash := utxoKey[:idx]
hashIndex := utxoKey[idx+1:]
index, err := strconv.Atoi(hashIndex)
if err != nil {
return fmt.Errorf("no valid utxo found for '%s' in the source account at index %d", utxoKey, index)
}
txHash, err := chainhash.NewHashFromStr(hash)
if err != nil {
return err
}
op := &wire.OutPoint{
Hash: *txHash,
Index: uint32(index),
}
outputInfo, err := tx.sourceWallet.Internal().OutputInfo(tx.sourceWallet.shutdownContext(), op)
if err != nil {
return fmt.Errorf("no valid utxo found for '%s' in the source account", utxoKey)
}
input := wire.NewTxIn(op, int64(outputInfo.Amount), nil)
inputs = append(inputs, input)
}
tx.inputs = inputs
tx.needsConstruct = true
return nil
}
func (tx *TxAuthor) Broadcast(privatePassphrase []byte) ([]byte, error) {
defer func() {
for i := range privatePassphrase {
privatePassphrase[i] = 0
}
}()
n, err := tx.sourceWallet.Internal().NetworkBackend()
if err != nil {
log.Error(err)
return nil, err
}
unsignedTx, err := tx.unsignedTransaction()
if err != nil {
return nil, translateError(err)
}
if unsignedTx.ChangeIndex >= 0 {
unsignedTx.RandomizeChangePosition()
}
var txBuf bytes.Buffer
txBuf.Grow(unsignedTx.Tx.SerializeSize())
err = unsignedTx.Tx.Serialize(&txBuf)
if err != nil {
log.Error(err)
return nil, err
}
var msgTx wire.MsgTx
err = msgTx.Deserialize(bytes.NewReader(txBuf.Bytes()))
if err != nil {
log.Error(err)
//Bytes do not represent a valid raw transaction
return nil, err
}
lock := make(chan time.Time, 1)
defer func() {
lock <- time.Time{}
}()
ctx := tx.sourceWallet.shutdownContext()
err = tx.sourceWallet.Internal().Unlock(ctx, privatePassphrase, lock)
if err != nil {
log.Error(err)
return nil, errors.New(ErrInvalidPassphrase)
}
var additionalPkScripts map[wire.OutPoint][]byte
invalidSigs, err := tx.sourceWallet.Internal().SignTransaction(ctx, &msgTx, txscript.SigHashAll, additionalPkScripts, nil, nil)
if err != nil {
log.Error(err)
return nil, err
}
invalidInputIndexes := make([]uint32, len(invalidSigs))
for i, e := range invalidSigs {
invalidInputIndexes[i] = e.InputIndex
}
var serializedTransaction bytes.Buffer
serializedTransaction.Grow(msgTx.SerializeSize())
err = msgTx.Serialize(&serializedTransaction)
if err != nil {
log.Error(err)
return nil, err
}
err = msgTx.Deserialize(bytes.NewReader(serializedTransaction.Bytes()))
if err != nil {
//Invalid tx
log.Error(err)
return nil, err
}
txHash, err := tx.sourceWallet.Internal().PublishTransaction(ctx, &msgTx, n)
if err != nil {
return nil, translateError(err)
}
return txHash[:], nil
}
func (tx *TxAuthor) unsignedTransaction() (*txauthor.AuthoredTx, error) {
if tx.needsConstruct || tx.unsignedTx == nil {
unsignedTx, err := tx.constructTransaction()
if err != nil {
return nil, err
}
tx.needsConstruct = false
tx.unsignedTx = unsignedTx
}
return tx.unsignedTx, nil
}
func (tx *TxAuthor) constructTransaction() (*txauthor.AuthoredTx, error) {
if len(tx.inputs) != 0 {
return tx.constructCustomTransaction()
}
var err error
var outputs = make([]*wire.TxOut, 0)
var outputSelectionAlgorithm w.OutputSelectionAlgorithm = w.OutputSelectionAlgorithmDefault
var changeSource txauthor.ChangeSource
ctx := tx.sourceWallet.shutdownContext()
for _, destination := range tx.destinations {
if err := tx.validateSendAmount(destination.SendMax, destination.AtomAmount); err != nil {
return nil, err
}
// check if multiple destinations are set to receive max amount
if destination.SendMax && changeSource != nil {
return nil, fmt.Errorf("cannot send max amount to multiple recipients")
}
if destination.SendMax {
// This is a send max destination, set output selection algo to all.
outputSelectionAlgorithm = w.OutputSelectionAlgorithmAll
// Use this destination address to make a changeSource rather than a tx output.
changeSource, err = txhelper.MakeTxChangeSource(destination.Address, tx.sourceWallet.chainParams)
if err != nil {
log.Errorf("constructTransaction: error preparing change source: %v", err)
return nil, fmt.Errorf("max amount change source error: %v", err)
}
} else {
output, err := txhelper.MakeTxOutput(destination.Address, destination.AtomAmount, tx.sourceWallet.chainParams)
if err != nil {
log.Errorf("constructTransaction: error preparing tx output: %v", err)
return nil, fmt.Errorf("make tx output error: %v", err)
}
outputs = append(outputs, output)
}
}
if changeSource == nil {
// dcrwallet should ordinarily handle cases where a nil changeSource
// is passed to `wallet.NewUnsignedTransaction` but the changeSource
// generated there errors on internal gap address limit exhaustion
// instead of wrapping around to a previously returned address.
//
// Generating a changeSource manually here, ensures that the gap address
// limit exhaustion error is avoided.
changeSource, err = tx.changeSource(ctx)
if err != nil {
return nil, err
}
}
requiredConfirmations := tx.sourceWallet.RequiredConfirmations()
return tx.sourceWallet.Internal().NewUnsignedTransaction(ctx, outputs, txrules.DefaultRelayFeePerKb, tx.sourceAccountNumber,
requiredConfirmations, outputSelectionAlgorithm, changeSource, nil)
}
// changeSource derives an internal address from the source wallet and account
// for this unsigned tx, if a change address had not been previously derived.
// The derived (or previously derived) address is used to prepare a
// change source for receiving change from this tx back into the wallet.
func (tx *TxAuthor) changeSource(ctx context.Context) (txauthor.ChangeSource, error) {
if tx.changeAddress == "" {
var changeAccount uint32
// MixedAccountNumber would be -1 if mixer config isn't set.
if tx.sourceAccountNumber == uint32(tx.sourceWallet.MixedAccountNumber()) ||
tx.sourceWallet.AccountMixerMixChange() {
changeAccount = uint32(tx.sourceWallet.UnmixedAccountNumber())
} else {
changeAccount = tx.sourceAccountNumber
}
address, err := tx.sourceWallet.Internal().NewChangeAddress(ctx, changeAccount)
if err != nil {
return nil, fmt.Errorf("change address error: %v", err)
}
tx.changeAddress = address.String()
}
changeSource, err := txhelper.MakeTxChangeSource(tx.changeAddress, tx.sourceWallet.chainParams)
if err != nil {
log.Errorf("constructTransaction: error preparing change source: %v", err)
return nil, fmt.Errorf("change source error: %v", err)
}
return changeSource, nil
}
// validateSendAmount validate the amount to send to a destination address
func (tx *TxAuthor) validateSendAmount(sendMax bool, atomAmount int64) error {
if !sendMax && (atomAmount <= 0 || atomAmount > MaxAmountAtom) {
return errors.E(errors.Invalid, "invalid amount")
}
return nil
}