/
mixing.go
284 lines (261 loc) · 7.76 KB
/
mixing.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
// Copyright (c) 2019 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"context"
"crypto/rand"
"crypto/tls"
"net"
"github.com/Decred-Next/cspp/v8"
"github.com/Decred-Next/cspp/v8/coinjoin"
"github.com/Decred-Next/dcrnd/dcrutil/version2/v8"
"github.com/Decred-Next/dcrnd/wire/v8"
"github.com/Decred-Next/dcrnwallet/errors/version2/v8"
"github.com/Decred-Next/dcrnwallet/wallet/version3/v8/txauthor"
"github.com/Decred-Next/dcrnwallet/wallet/version3/v8/txrules"
"github.com/Decred-Next/dcrnwallet/wallet/version3/v8/txsizes"
"github.com/Decred-Next/dcrnwallet/wallet/version3/v8/udb"
"github.com/Decred-Next/dcrnwallet/wallet/version3/v8/walletdb"
"github.com/Decred-Next/go-socks/v8/socks"
"golang.org/x/sync/errgroup"
)
// must be sorted large to small
var splitPoints = [...]dcrutil.Amount{
1 << 36, // 687.19476736
1 << 34, // 171.79869184
1 << 32, // 042.94967296
1 << 30, // 010.73741824
1 << 28, // 002.68435456
1 << 26, // 000.67108864
1 << 24, // 000.16777216
1 << 22, // 000.04194304
1 << 20, // 000.01048576
1 << 18, // 000.00262144
}
var splitSems = [len(splitPoints)]chan struct{}{}
func init() {
for i := range splitSems {
splitSems[i] = make(chan struct{}, 10)
}
}
var errNoSplitDenomination = errors.New("no suitable split denomination")
// DialFunc provides a method to dial a network connection.
// If the dialed network connection is secured by TLS, TLS
// configuration is provided by the method, not the caller.
type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error)
func (w *Wallet) MixOutput(ctx context.Context, dialTLS DialFunc, csppserver string, output *wire.OutPoint, changeAccount, mixAccount, mixBranch uint32) error {
op := errors.Opf("wallet.MixOutput(%v)", output)
var updates []func(walletdb.ReadWriteTx) error
hold, err := w.holdUnlock()
if err != nil {
return errors.E(op, err)
}
defer hold.release()
var prevScript []byte
var amount dcrutil.Amount
err = walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
txDetails, err := w.TxStore.TxDetails(txmgrNs, &output.Hash)
if err != nil {
return err
}
prevScript = txDetails.MsgTx.TxOut[output.Index].PkScript
amount = dcrutil.Amount(txDetails.MsgTx.TxOut[output.Index].Value)
return nil
})
if err != nil {
return errors.E(op, err)
}
w.lockedOutpointMu.Lock()
w.lockedOutpoints[*output] = struct{}{}
w.lockedOutpointMu.Unlock()
defer func() {
w.lockedOutpointMu.Lock()
delete(w.lockedOutpoints, *output)
w.lockedOutpointMu.Unlock()
}()
var count int
var mixValue, remValue dcrutil.Amount
for i, v := range splitPoints {
count = int(amount / v)
if count > 0 {
remValue = amount - dcrutil.Amount(count)*v
mixValue = v
select {
case <-ctx.Done():
return errors.E(op, ctx.Err())
case splitSems[i] <- struct{}{}:
defer func() { <-splitSems[i] }()
}
break
}
}
if mixValue == splitPoints[len(splitPoints)-1] {
remValue = 0
}
if mixValue == 0 {
err := errors.Errorf("output %v (%v): %w", output, amount, errNoSplitDenomination)
return errors.E(op, err)
}
const (
txVersion = 1
locktime = 0
expiry = 0
)
pairing := coinjoin.EncodeDesc(coinjoin.P2PKHv0, int64(mixValue), txVersion, locktime, expiry)
ses, err := cspp.NewSession(rand.Reader, debugLog, pairing, count)
if err != nil {
return errors.E(op, err)
}
var conn net.Conn
if dialTLS != nil {
conn, err = dialTLS(ctx, "tcp", csppserver)
} else {
conn, err = tls.Dial("tcp", csppserver, nil)
}
if err != nil {
return errors.E(op, err)
}
defer conn.Close()
log.Infof("Dialed CSPPServer %v -> %v", conn.LocalAddr(), conn.RemoteAddr())
// Create change output from remaining value and contributed fee
const P2PKHv0Len = 25
feeRate := w.RelayFee()
inScriptSizes := []int{txsizes.RedeemP2PKHSigScriptSize}
outScriptSizes := make([]int, count)
for i := range outScriptSizes {
outScriptSizes[i] = P2PKHv0Len
}
size := txsizes.EstimateSerializeSizeFromScriptSizes(inScriptSizes, outScriptSizes, P2PKHv0Len)
changeValue := remValue - txrules.FeeForSerializeSize(feeRate, size)
var change *wire.TxOut
if !txrules.IsDustAmount(changeValue, P2PKHv0Len, feeRate) {
persist := w.deferPersistReturnedChild(ctx, &updates)
addr, err := w.nextAddress(ctx, op, persist, changeAccount, udb.InternalBranch, WithGapPolicyIgnore())
if err != nil {
return errors.E(op, err)
}
changeScript, version, err := addressScript(addr)
if err != nil {
return errors.E(op, err)
}
change = &wire.TxOut{
Value: int64(changeValue),
PkScript: changeScript,
Version: version,
}
}
log.Infof("Mixing output %v (%v)", output, amount)
cj := w.newCsppJoin(ctx, change, mixValue, mixAccount, mixBranch, int(count))
cj.addTxIn(prevScript, &wire.TxIn{
PreviousOutPoint: *output,
ValueIn: int64(amount),
})
err = ses.DiceMix(ctx, conn, cj)
if err != nil {
return errors.E(op, err)
}
cjHash := cj.tx.TxHash()
log.Infof("Completed CoinShuffle++ mix of output %v in transaction %v", output, &cjHash)
err = walletdb.Update(ctx, w.db, func(dbtx walletdb.ReadWriteTx) error {
for _, f := range updates {
if err := f(dbtx); err != nil {
return err
}
}
return nil
})
if err != nil {
return errors.E(op, err)
}
return nil
}
// MixAccount individually mixes outputs of an account into standard
// denominations, creating newly mixed outputs for a mixed account.
//
// Due to performance concerns of timing out in a CoinShuffle++ run, this
// function may throttle how many of the outputs are mixed each call.
func (w *Wallet) MixAccount(ctx context.Context, dialTLS DialFunc, csppserver string, changeAccount, mixAccount, mixBranch uint32) error {
const op errors.Op = "wallet.MixAccount"
hold, err := w.holdUnlock()
if err != nil {
return errors.E(op, err)
}
defer hold.release()
_, tipHeight := w.MainChainTip(ctx)
credits, err := w.FindEligibleOutputs(ctx, changeAccount, 1, tipHeight)
if err != nil {
return errors.E(op, err)
}
unlockedCredits := credits[:0]
for i := range credits {
if credits[i].Amount <= splitPoints[len(splitPoints)-1] {
continue
}
w.lockedOutpointMu.Lock()
_, locked := w.lockedOutpoints[credits[i].OutPoint]
w.lockedOutpointMu.Unlock()
if !locked {
unlockedCredits = append(unlockedCredits, credits[i])
}
}
credits = unlockedCredits
shuffle(len(credits), func(i, j int) {
credits[i], credits[j] = credits[j], credits[i]
})
if len(credits) > 32 { // simple throttle
credits = credits[:32]
}
var g errgroup.Group
for i := range credits {
op := &credits[i].OutPoint
g.Go(func() error {
err := w.MixOutput(ctx, dialTLS, csppserver, op, changeAccount, mixAccount, mixBranch)
if errors.Is(err, errNoSplitDenomination) {
return nil
}
if errors.Is(err, socks.ErrPoolMaxConnections) {
return nil
}
return err
})
}
err = g.Wait()
if err != nil {
return errors.E(op, err)
}
return nil
}
// randomInputSource wraps an InputSource to randomly pick UTXOs.
// This involves reading all UTXOs from the underlying source into memory.
func randomInputSource(source txauthor.InputSource) txauthor.InputSource {
all, err := source(dcrutil.MaxAmount)
if err == nil {
shuffleUTXOs(all)
}
var n int
var tot dcrutil.Amount
return func(target dcrutil.Amount) (*txauthor.InputDetail, error) {
if err != nil {
return nil, err
}
if all.Amount <= target {
return all, nil
}
for n < len(all.Inputs) {
tot += dcrutil.Amount(all.Inputs[n].ValueIn)
n++
if tot >= target {
break
}
}
selected := &txauthor.InputDetail{
Amount: tot,
Inputs: all.Inputs[:n],
Scripts: all.Scripts[:n],
RedeemScriptSizes: all.RedeemScriptSizes[:n],
}
return selected, nil
}
}