/
coinjoin.go
246 lines (228 loc) · 6.32 KB
/
coinjoin.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
package wallet
import (
"bytes"
"context"
"crypto/subtle"
"decred.org/dcrwallet/v2/errors"
"decred.org/dcrwallet/v2/wallet/walletdb"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/txscript/v4/sign"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
)
type missingGenError struct{}
var errMissingGen missingGenError
func (missingGenError) Error() string { return "coinjoin is missing gen output" }
func (missingGenError) MissingMessage() {}
type csppJoin struct {
tx *wire.MsgTx
txInputs map[wire.OutPoint]int
myPrevScripts [][]byte
myIns []*wire.TxIn
change *wire.TxOut
mcount int
genScripts [][]byte
genIndex []int
amount int64
wallet *Wallet
mixAccount uint32
mixBranch uint32
ctx context.Context
}
func (w *Wallet) newCsppJoin(ctx context.Context, change *wire.TxOut, amount dcrutil.Amount, mixAccount, mixBranch uint32, mcount int) *csppJoin {
cj := &csppJoin{
tx: &wire.MsgTx{Version: 1},
change: change,
mcount: mcount,
amount: int64(amount),
wallet: w,
mixAccount: mixAccount,
mixBranch: mixBranch,
ctx: ctx,
}
if change != nil {
cj.tx.TxOut = append(cj.tx.TxOut, change)
}
return cj
}
func (c *csppJoin) addTxIn(prevScript []byte, in *wire.TxIn) {
c.tx.TxIn = append(c.tx.TxIn, in)
c.myPrevScripts = append(c.myPrevScripts, prevScript)
c.myIns = append(c.myIns, in)
}
func (c *csppJoin) Gen() ([][]byte, error) {
const op errors.Op = "cspp.Gen"
gen := make([][]byte, c.mcount)
c.genScripts = make([][]byte, c.mcount)
var updates []func(walletdb.ReadWriteTx) error
for i := 0; i < c.mcount; i++ {
persist := c.wallet.deferPersistReturnedChild(c.ctx, &updates)
const accountName = "" // not used, so can be faked.
mixAddr, err := c.wallet.nextAddress(c.ctx, op, persist,
accountName, c.mixAccount, c.mixBranch, WithGapPolicyIgnore())
if err != nil {
return nil, err
}
version, script := mixAddr.PaymentScript()
if version != 0 {
return nil, errors.E("expected script version 0")
}
hash160er, ok := mixAddr.(stdaddr.Hash160er)
if !ok {
return nil, errors.E("address does not have Hash160 method")
}
c.genScripts[i] = script
gen[i] = hash160er.Hash160()[:]
}
err := walletdb.Update(c.ctx, c.wallet.db, func(dbtx walletdb.ReadWriteTx) error {
for _, f := range updates {
if err := f(dbtx); err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, errors.E(op, err)
}
return gen, nil
}
func (c *csppJoin) Confirm() error {
const op errors.Op = "cspp.Confirm"
err := walletdb.View(c.ctx, c.wallet.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
for outx, in := range c.myIns {
outScript := c.myPrevScripts[outx]
index, ok := c.txInputs[in.PreviousOutPoint]
if !ok {
return errors.E("coinjoin is missing inputs")
}
in = c.tx.TxIn[index]
const scriptVersion = 0
_, addrs := stdscript.ExtractAddrs(scriptVersion, outScript, c.wallet.chainParams)
if len(addrs) != 1 {
continue
}
apkh, ok := addrs[0].(*stdaddr.AddressPubKeyHashEcdsaSecp256k1V0)
if !ok {
return errors.E(errors.Bug, "previous output is not P2PKH")
}
privKey, done, err := c.wallet.manager.PrivateKey(addrmgrNs, apkh)
if err != nil {
return err
}
defer done()
sigscript, err := sign.SignatureScript(c.tx, index, outScript,
txscript.SigHashAll, privKey.Serialize(), dcrec.STEcdsaSecp256k1, true)
if err != nil {
return errors.E(errors.Op("txscript.SignatureScript"), err)
}
in.SignatureScript = sigscript
}
return nil
})
if err != nil {
return errors.E(op, err)
}
return nil
}
func (c *csppJoin) mixOutputIndexes() []int {
return c.genIndex
}
func (c *csppJoin) MarshalBinary() ([]byte, error) {
buf := new(bytes.Buffer)
buf.Grow(c.tx.SerializeSize())
err := c.tx.Serialize(buf)
return buf.Bytes(), err
}
func (c *csppJoin) UnmarshalBinary(b []byte) error {
tx := new(wire.MsgTx)
err := tx.Deserialize(bytes.NewReader(b))
if err != nil {
return err
}
// Ensure all unmixed inputs, unmixed outputs, and mixed outputs exist.
// Mixed outputs must be searched in constant time to avoid sidechannel leakage.
txInputs := make(map[wire.OutPoint]int, len(tx.TxIn))
for i, in := range tx.TxIn {
txInputs[in.PreviousOutPoint] = i
}
var n int
for _, in := range c.myIns {
if index, ok := txInputs[in.PreviousOutPoint]; ok {
other := tx.TxIn[index]
if in.Sequence != other.Sequence || in.ValueIn != other.ValueIn {
break
}
n++
}
}
if n != len(c.myIns) {
return errors.E("coinjoin is missing inputs")
}
if c.change != nil {
var hasChange bool
for _, out := range tx.TxOut {
if out.Value != c.change.Value {
continue
}
if out.Version != c.change.Version {
continue
}
if !bytes.Equal(out.PkScript, c.change.PkScript) {
continue
}
hasChange = true
break
}
if !hasChange {
return errors.E("coinjoin is missing change")
}
}
indexes, err := constantTimeOutputSearch(tx, c.amount, 0, c.genScripts)
if err != nil {
return err
}
c.tx = tx
c.txInputs = txInputs
c.genIndex = indexes
return nil
}
// constantTimeOutputSearch searches for the output indexes of mixed outputs to
// verify inclusion in a coinjoin. It is constant time such that, for each
// searched script, all outputs with equal value, script versions, and script
// lengths matching the searched output are checked in constant time.
func constantTimeOutputSearch(tx *wire.MsgTx, value int64, scriptVer uint16, scripts [][]byte) ([]int, error) {
var scan []int
for i, out := range tx.TxOut {
if out.Value != value {
continue
}
if out.Version != scriptVer {
continue
}
if len(out.PkScript) != len(scripts[0]) {
continue
}
scan = append(scan, i)
}
indexes := make([]int, 0, len(scan))
var missing int
for _, s := range scripts {
idx := -1
for _, i := range scan {
eq := subtle.ConstantTimeCompare(tx.TxOut[i].PkScript, s)
idx = subtle.ConstantTimeSelect(eq, i, idx)
}
indexes = append(indexes, idx)
eq := subtle.ConstantTimeEq(int32(idx), -1)
missing = subtle.ConstantTimeSelect(eq, 1, missing)
}
if missing == 1 {
return nil, errMissingGen
}
return indexes, nil
}