forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
351 lines (314 loc) · 10.5 KB
/
main.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
// Copyright (c) 2015-2016 The btcsuite developers
// Copyright (c) 2016-2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrrpcclient"
"github.com/decred/dcrutil"
"github.com/decred/dcrwallet/internal/cfgutil"
"github.com/decred/dcrwallet/netparams"
"github.com/decred/dcrwallet/wallet/txauthor"
"github.com/decred/dcrwallet/wallet/txrules"
"github.com/jessevdk/go-flags"
"golang.org/x/crypto/ssh/terminal"
)
var (
walletDataDirectory = dcrutil.AppDataDir("dcrwallet", false)
newlineBytes = []byte{'\n'}
)
func fatalf(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
os.Stderr.Write(newlineBytes)
os.Exit(1)
}
func errContext(err error, context string) error {
return fmt.Errorf("%s: %v", context, err)
}
// Flags.
var opts = struct {
TestNet bool `long:"testnet" description:"Use the test decred network"`
SimNet bool `long:"simnet" description:"Use the simulation decred network"`
RPCConnect string `short:"c" long:"connect" description:"Hostname[:port] of wallet RPC server"`
RPCUsername string `short:"u" long:"rpcuser" description:"Wallet RPC username"`
RPCCertificateFile string `long:"cafile" description:"Wallet RPC TLS certificate"`
FeeRate *cfgutil.AmountFlag `long:"feerate" description:"Transaction fee per kilobyte"`
SourceAccount string `long:"sourceacct" description:"Account to sweep outputs from"`
DestinationAccount string `long:"destacct" description:"Account to send sweeped outputs to"`
RequiredConfirmations int64 `long:"minconf" description:"Required confirmations to include an output"`
}{
TestNet: false,
SimNet: false,
RPCConnect: "localhost",
RPCUsername: "",
RPCCertificateFile: filepath.Join(walletDataDirectory, "rpc.cert"),
FeeRate: cfgutil.NewAmountFlag(txrules.DefaultRelayFeePerKb),
SourceAccount: "imported",
DestinationAccount: "default",
RequiredConfirmations: 2,
}
// Parse and validate flags.
func init() {
// Unset localhost defaults if certificate file can not be found.
certFileExists, err := cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
opts.RPCConnect = ""
opts.RPCCertificateFile = ""
}
_, err = flags.Parse(&opts)
if err != nil {
os.Exit(1)
}
if opts.TestNet && opts.SimNet {
fatalf("Multiple decred networks may not be used simultaneously")
}
var activeNet = &netparams.MainNetParams
if opts.TestNet {
activeNet = &netparams.TestNet2Params
} else if opts.SimNet {
activeNet = &netparams.SimNetParams
}
if opts.RPCConnect == "" {
fatalf("RPC hostname[:port] is required")
}
rpcConnect, err := cfgutil.NormalizeAddress(opts.RPCConnect, activeNet.JSONRPCServerPort)
if err != nil {
fatalf("Invalid RPC network address `%v`: %v", opts.RPCConnect, err)
}
opts.RPCConnect = rpcConnect
if opts.RPCUsername == "" {
fatalf("RPC username is required")
}
certFileExists, err = cfgutil.FileExists(opts.RPCCertificateFile)
if err != nil {
fatalf("%v", err)
}
if !certFileExists {
fatalf("RPC certificate file `%s` not found", opts.RPCCertificateFile)
}
if opts.FeeRate.Amount > 1e8 {
fatalf("Fee rate `%v/kB` is exceptionally high", opts.FeeRate.Amount)
}
if opts.FeeRate.Amount < 1e2 {
fatalf("Fee rate `%v/kB` is exceptionally low", opts.FeeRate.Amount)
}
if opts.SourceAccount == opts.DestinationAccount {
fatalf("Source and destination accounts should not be equal")
}
if opts.RequiredConfirmations < 0 {
fatalf("Required confirmations must be non-negative")
}
}
// noInputValue describes an error returned by the input source when no inputs
// were selected because each previous output value was zero. Callers of
// txauthor.NewUnsignedTransaction need not report these errors to the user.
type noInputValue struct {
}
func (noInputValue) Error() string { return "no input value" }
// makeInputSource creates an InputSource that creates inputs for every unspent
// output with non-zero output values. The target amount is ignored since every
// output is consumed. The InputSource does not return any previous output
// scripts as they are not needed for creating the unsinged transaction and are
// looked up again by the wallet during the call to signrawtransaction.
func makeInputSource(outputs []dcrjson.ListUnspentResult) txauthor.InputSource {
var (
totalInputValue dcrutil.Amount
inputs = make([]*wire.TxIn, 0, len(outputs))
sourceErr error
)
for _, output := range outputs {
outputAmount, err := dcrutil.NewAmount(output.Amount)
if err != nil {
sourceErr = fmt.Errorf(
"invalid amount `%v` in listunspent result",
output.Amount)
break
}
if outputAmount == 0 {
continue
}
if !saneOutputValue(outputAmount) {
sourceErr = fmt.Errorf(
"impossible output amount `%v` in listunspent result",
outputAmount)
break
}
totalInputValue += outputAmount
previousOutPoint, err := parseOutPoint(&output)
if err != nil {
sourceErr = fmt.Errorf(
"invalid data in listunspent result: %v",
err)
break
}
inputs = append(inputs, wire.NewTxIn(&previousOutPoint, nil))
}
if sourceErr == nil && totalInputValue == 0 {
sourceErr = noInputValue{}
}
return func(dcrutil.Amount) (dcrutil.Amount, []*wire.TxIn, [][]byte, error) {
return totalInputValue, inputs, nil, sourceErr
}
}
// makeDestinationScriptSource creates a ChangeSource which is used to receive
// all correlated previous input value. A non-change address is created by this
// function.
func makeDestinationScriptSource(rpcClient *dcrrpcclient.Client, accountName string) txauthor.ChangeSource {
return func() ([]byte, uint16, error) {
destinationAddress, err := rpcClient.GetNewAddress(accountName)
if err != nil {
return nil, 0, err
}
script, err := txscript.PayToAddrScript(destinationAddress)
return script, txscript.DefaultScriptVersion, err
}
}
func main() {
err := sweep()
if err != nil {
fatalf("%v", err)
}
}
func sweep() error {
rpcPassword, err := promptSecret("Wallet RPC password")
if err != nil {
return errContext(err, "failed to read RPC password")
}
// Open RPC client.
rpcCertificate, err := ioutil.ReadFile(opts.RPCCertificateFile)
if err != nil {
return errContext(err, "failed to read RPC certificate")
}
rpcClient, err := dcrrpcclient.New(&dcrrpcclient.ConnConfig{
Host: opts.RPCConnect,
User: opts.RPCUsername,
Pass: rpcPassword,
Certificates: rpcCertificate,
HTTPPostMode: true,
}, nil)
if err != nil {
return errContext(err, "failed to create RPC client")
}
defer rpcClient.Shutdown()
// Fetch all unspent outputs, ignore those not from the source
// account, and group by their destination address. Each grouping of
// outputs will be used as inputs for a single transaction sending to a
// new destination account address.
unspentOutputs, err := rpcClient.ListUnspent()
if err != nil {
return errContext(err, "failed to fetch unspent outputs")
}
sourceOutputs := make(map[string][]dcrjson.ListUnspentResult)
for _, unspentOutput := range unspentOutputs {
if !unspentOutput.Spendable {
continue
}
if unspentOutput.Confirmations < opts.RequiredConfirmations {
continue
}
if unspentOutput.Account != opts.SourceAccount {
continue
}
sourceAddressOutputs := sourceOutputs[unspentOutput.Address]
sourceOutputs[unspentOutput.Address] = append(sourceAddressOutputs, unspentOutput)
}
var privatePassphrase string
if len(sourceOutputs) != 0 {
privatePassphrase, err = promptSecret("Wallet private passphrase")
if err != nil {
return errContext(err, "failed to read private passphrase")
}
}
var totalSwept dcrutil.Amount
var numErrors int
var reportError = func(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
os.Stderr.Write(newlineBytes)
numErrors++
}
for _, previousOutputs := range sourceOutputs {
inputSource := makeInputSource(previousOutputs)
destinationSource := makeDestinationScriptSource(rpcClient, opts.DestinationAccount)
tx, err := txauthor.NewUnsignedTransaction(nil, opts.FeeRate.Amount,
inputSource, destinationSource)
if err != nil {
if err != (noInputValue{}) {
reportError("Failed to create unsigned transaction: %v", err)
}
continue
}
// Unlock the wallet, sign the transaction, and immediately lock.
err = rpcClient.WalletPassphrase(privatePassphrase, 60)
if err != nil {
reportError("Failed to unlock wallet: %v", err)
continue
}
signedTransaction, complete, err := rpcClient.SignRawTransaction(tx.Tx)
_ = rpcClient.WalletLock()
if err != nil {
reportError("Failed to sign transaction: %v", err)
continue
}
if !complete {
reportError("Failed to sign every input")
continue
}
// Publish the signed sweep transaction.
txHash, err := rpcClient.SendRawTransaction(signedTransaction, false)
if err != nil {
reportError("Failed to publish transaction: %v", err)
continue
}
outputAmount := dcrutil.Amount(tx.Tx.TxOut[0].Value)
fmt.Printf("Swept %v to destination account with transaction %v\n",
outputAmount, txHash)
totalSwept += outputAmount
}
numPublished := len(sourceOutputs) - numErrors
transactionNoun := pickNoun(numErrors, "transaction", "transactions")
if numPublished != 0 {
fmt.Printf("Swept %v to destination account across %d %s\n",
totalSwept, numPublished, transactionNoun)
}
if numErrors > 0 {
return fmt.Errorf("Failed to publish %d %s", numErrors, transactionNoun)
}
return nil
}
func promptSecret(what string) (string, error) {
fmt.Printf("%s: ", what)
fd := int(os.Stdin.Fd())
input, err := terminal.ReadPassword(fd)
fmt.Println()
if err != nil {
return "", err
}
return string(input), nil
}
func saneOutputValue(amount dcrutil.Amount) bool {
return amount >= 0 && amount <= dcrutil.MaxAmount
}
func parseOutPoint(input *dcrjson.ListUnspentResult) (wire.OutPoint, error) {
txHash, err := chainhash.NewHashFromStr(input.TxID)
if err != nil {
return wire.OutPoint{}, err
}
return wire.OutPoint{Hash: *txHash, Index: input.Vout, Tree: input.Tree}, nil
}
func pickNoun(n int, singularForm, pluralForm string) string {
if n == 1 {
return singularForm
}
return pluralForm
}