/
deposit_sweep.go
496 lines (438 loc) · 14.8 KB
/
deposit_sweep.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package tbtc
import (
"crypto/ecdsa"
"fmt"
"math/big"
"time"
"github.com/ipfs/go-log/v2"
"go.uber.org/zap"
"github.com/keep-network/keep-core/pkg/bitcoin"
)
const (
// depositSweepProposalValidityBlocks determines the deposit sweep proposal
// validity time expressed in blocks. In other words, this is the worst-case
// time for a deposit sweep during which the wallet is busy and cannot take
// another actions. The value of 1200 blocks is roughly 4 hours, assuming
// 12 seconds per block.
depositSweepProposalValidityBlocks = 1200
// DepositSweepRequiredFundingTxConfirmations determines the minimum
// number of confirmations that are needed for a deposit funding Bitcoin
// transaction in order to consider it a valid part of the deposit sweep
// proposal.
DepositSweepRequiredFundingTxConfirmations = 6
// depositSweepSigningTimeoutSafetyMarginBlocks determines the duration of
// the safety margin that must be preserved between the signing timeout
// and the timeout of the entire deposit sweep action. This safety
// margin prevents against the case where signing completes late and there
// is not enough time to broadcast the sweep transaction properly.
// In such a case, wallet signatures may leak and make the wallet subject
// of fraud accusations. Usage of the safety margin ensures there is enough
// time to perform post-signing steps of the deposit sweep action.
// The value of 300 blocks is roughly 1 hour, assuming 12 seconds per block.
depositSweepSigningTimeoutSafetyMarginBlocks = 300
// depositSweepBroadcastTimeout determines the time window for deposit
// sweep transaction broadcast. It is guaranteed that at least
// depositSweepSigningTimeoutSafetyMarginBlocks is preserved for the broadcast
// step. However, the happy path for the broadcast step is usually quick
// and few retries are needed to recover from temporary problems. That
// said, if the broadcast step does not succeed in a tight timeframe,
// there is no point to retry for the entire possible time window.
// Hence, the timeout for broadcast step is set as 25% of the entire
// time widow determined by depositSweepSigningTimeoutSafetyMarginBlocks.
depositSweepBroadcastTimeout = 15 * time.Minute
// depositSweepBroadcastCheckDelay determines the delay that must
// be preserved between transaction broadcast and the check that ensures
// the transaction is known on the Bitcoin chain. This delay is needed
// as spreading the transaction over the Bitcoin network takes time.
depositSweepBroadcastCheckDelay = 1 * time.Minute
)
// DepositSweepProposal represents a deposit sweep proposal issued by a
// wallet's coordination leader.
type DepositSweepProposal struct {
DepositsKeys []struct {
FundingTxHash bitcoin.Hash
FundingOutputIndex uint32
}
SweepTxFee *big.Int
DepositsRevealBlocks []*big.Int
}
func (dsp *DepositSweepProposal) ActionType() WalletActionType {
return ActionDepositSweep
}
func (dsp *DepositSweepProposal) ValidityBlocks() uint64 {
return depositSweepProposalValidityBlocks
}
// depositSweepAction is a deposit sweep walletAction.
type depositSweepAction struct {
logger *zap.SugaredLogger
chain Chain
btcChain bitcoin.Chain
sweepingWallet wallet
transactionExecutor *walletTransactionExecutor
proposal *DepositSweepProposal
proposalProcessingStartBlock uint64
proposalExpiryBlock uint64
requiredFundingTxConfirmations uint
signingTimeoutSafetyMarginBlocks uint64
broadcastTimeout time.Duration
broadcastCheckDelay time.Duration
}
func newDepositSweepAction(
logger *zap.SugaredLogger,
chain Chain,
btcChain bitcoin.Chain,
sweepingWallet wallet,
signingExecutor walletSigningExecutor,
proposal *DepositSweepProposal,
proposalProcessingStartBlock uint64,
proposalExpiryBlock uint64,
waitForBlockFn waitForBlockFn,
) *depositSweepAction {
transactionExecutor := newWalletTransactionExecutor(
btcChain,
sweepingWallet,
signingExecutor,
waitForBlockFn,
)
return &depositSweepAction{
logger: logger,
chain: chain,
btcChain: btcChain,
sweepingWallet: sweepingWallet,
transactionExecutor: transactionExecutor,
proposal: proposal,
proposalProcessingStartBlock: proposalProcessingStartBlock,
proposalExpiryBlock: proposalExpiryBlock,
requiredFundingTxConfirmations: DepositSweepRequiredFundingTxConfirmations,
signingTimeoutSafetyMarginBlocks: depositSweepSigningTimeoutSafetyMarginBlocks,
broadcastTimeout: depositSweepBroadcastTimeout,
broadcastCheckDelay: depositSweepBroadcastCheckDelay,
}
}
func (dsa *depositSweepAction) execute() error {
validateProposalLogger := dsa.logger.With(
zap.String("step", "validateProposal"),
)
walletPublicKeyHash := bitcoin.PublicKeyHash(dsa.wallet().publicKey)
validatedDeposits, err := ValidateDepositSweepProposal(
validateProposalLogger,
walletPublicKeyHash,
dsa.proposal,
dsa.requiredFundingTxConfirmations,
dsa.chain,
dsa.btcChain,
)
if err != nil {
return fmt.Errorf("validate proposal step failed: [%v]", err)
}
walletMainUtxo, err := DetermineWalletMainUtxo(
walletPublicKeyHash,
dsa.chain,
dsa.btcChain,
)
if err != nil {
return fmt.Errorf(
"error while determining wallet's main UTXO: [%v]",
err,
)
}
err = EnsureWalletSyncedBetweenChains(
walletPublicKeyHash,
walletMainUtxo,
dsa.chain,
dsa.btcChain,
)
if err != nil {
return fmt.Errorf(
"error while ensuring wallet state is synced between "+
"BTC and host chain: [%v]",
err,
)
}
unsignedSweepTx, err := assembleDepositSweepTransaction(
dsa.btcChain,
dsa.wallet().publicKey,
walletMainUtxo,
validatedDeposits,
dsa.proposal.SweepTxFee.Int64(),
)
if err != nil {
return fmt.Errorf(
"error while assembling deposit sweep transaction: [%v]",
err,
)
}
signTxLogger := dsa.logger.With(
zap.String("step", "signTransaction"),
)
// Just in case. This should never happen.
if dsa.proposalExpiryBlock < dsa.signingTimeoutSafetyMarginBlocks {
return fmt.Errorf("invalid proposal expiry block")
}
sweepTx, err := dsa.transactionExecutor.signTransaction(
signTxLogger,
unsignedSweepTx,
dsa.proposalProcessingStartBlock,
dsa.proposalExpiryBlock-dsa.signingTimeoutSafetyMarginBlocks,
)
if err != nil {
return fmt.Errorf("sign transaction step failed: [%v]", err)
}
broadcastTxLogger := dsa.logger.With(
zap.String("step", "broadcastTransaction"),
zap.String("sweepTxHash", sweepTx.Hash().Hex(bitcoin.ReversedByteOrder)),
)
err = dsa.transactionExecutor.broadcastTransaction(
broadcastTxLogger,
sweepTx,
dsa.broadcastTimeout,
dsa.broadcastCheckDelay,
)
if err != nil {
return fmt.Errorf("broadcast transaction step failed: [%v]", err)
}
return nil
}
// ValidateDepositSweepProposal checks the deposit sweep proposal with on-chain
// validation rules and verifies transactions on the Bitcoin chain.
func ValidateDepositSweepProposal(
validateProposalLogger log.StandardLogger,
walletPublicKeyHash [20]byte,
proposal *DepositSweepProposal,
requiredFundingTxConfirmations uint,
chain interface {
// PastDepositRevealedEvents fetches past deposit reveal events according
// to the provided filter or unfiltered if the filter is nil. Returned
// events are sorted by the block number in the ascending order, i.e. the
// latest event is at the end of the slice.
PastDepositRevealedEvents(
filter *DepositRevealedEventFilter,
) ([]*DepositRevealedEvent, error)
// ValidateDepositSweepProposal validates the given deposit sweep proposal
// against the chain. It requires some additional data about the deposits
// that must be fetched externally. Returns an error if the proposal is
// not valid or nil otherwise.
ValidateDepositSweepProposal(
walletPublicKeyHash [20]byte,
proposal *DepositSweepProposal,
depositsExtraInfo []struct {
*Deposit
FundingTx *bitcoin.Transaction
},
) error
// GetDepositRequest gets the on-chain deposit request for the given
// funding transaction hash and output index.The returned values represent:
// - deposit request which is non-nil only when the deposit request was
// found,
// - boolean value which is true if the deposit request was found, false
// otherwise,
// - error which is non-nil only when the function execution failed. It will
// be nil if the deposit request was not found, but the function execution
// succeeded.
GetDepositRequest(
fundingTxHash bitcoin.Hash,
fundingOutputIndex uint32,
) (*DepositChainRequest, bool, error)
},
btcChain bitcoin.Chain,
) ([]*Deposit, error) {
depositExtraInfo := make(
[]struct {
*Deposit
FundingTx *bitcoin.Transaction
},
len(proposal.DepositsKeys),
)
validateProposalLogger.Infof("gathering prerequisites for proposal validation")
if len(proposal.DepositsKeys) != len(proposal.DepositsRevealBlocks) {
return nil, fmt.Errorf("proposal's reveal blocks list has a wrong length")
}
for i, depositKey := range proposal.DepositsKeys {
depositDisplayIndex := fmt.Sprintf("%v/%v", i+1, len(proposal.DepositsKeys))
validateProposalLogger.Infof(
"deposit [%v] - checking confirmations count for funding tx",
depositDisplayIndex,
)
confirmations, err := btcChain.GetTransactionConfirmations(
depositKey.FundingTxHash,
)
if err != nil {
return nil, fmt.Errorf(
"cannot get funding tx confirmations count "+
"for deposit [%v]: [%v]",
depositDisplayIndex,
err,
)
}
if confirmations < requiredFundingTxConfirmations {
return nil, fmt.Errorf(
"funding tx of deposit [%v] has only [%v/%v] of "+
"required confirmations",
depositDisplayIndex,
confirmations,
requiredFundingTxConfirmations,
)
}
validateProposalLogger.Infof(
"deposit [%v] - fetching deposit's extra data",
depositDisplayIndex,
)
fundingTx, err := btcChain.GetTransaction(depositKey.FundingTxHash)
if err != nil {
return nil, fmt.Errorf(
"cannot get funding tx data for deposit [%v]: [%v]",
depositDisplayIndex,
err,
)
}
revealBlock := proposal.DepositsRevealBlocks[i].Uint64()
// We need to fetch the past DepositRevealed event for the given deposit.
// It may be tempting to fetch such events for all deposit keys
// in the proposal using a single call, however, this solution has
// serious downsides. Popular chain clients have limitations
// for fetching past chain events regarding the requested block
// range and/or returned data size. In this context, it is better to
// do several well-tailored calls than a single general one.
// We have the revealBlock passed by the coordinator within the proposal
// so, we can use it to make a narrow call. Moreover, we use the
// wallet PKH as additional filter to limit the size of returned data.
events, err := chain.PastDepositRevealedEvents(&DepositRevealedEventFilter{
StartBlock: revealBlock,
EndBlock: &revealBlock,
WalletPublicKeyHash: [][20]byte{walletPublicKeyHash},
})
if err != nil {
return nil, fmt.Errorf(
"cannot get on-chain DepositRevealed events for deposit [%v]: [%v]",
depositDisplayIndex,
err,
)
}
// There may be multiple events returned for the provided filter.
// Find the one matching our depositKey.
var matchingEvent *DepositRevealedEvent
for _, event := range events {
if event.FundingTxHash == depositKey.FundingTxHash &&
event.FundingOutputIndex == depositKey.FundingOutputIndex {
matchingEvent = event
break
}
}
if matchingEvent == nil {
return nil, fmt.Errorf(
"no matching DepositRevealed event for deposit [%v]: [%v]",
depositDisplayIndex,
err,
)
}
depositRequest, found, err := chain.GetDepositRequest(
depositKey.FundingTxHash,
depositKey.FundingOutputIndex,
)
if err != nil {
return nil, fmt.Errorf(
"cannot get request data for deposit [%v]: [%v]",
depositDisplayIndex,
err,
)
}
if !found {
return nil, fmt.Errorf(
"request data not found for deposit [%v]",
depositDisplayIndex,
)
}
depositExtraInfo[i] = struct {
*Deposit
FundingTx *bitcoin.Transaction
}{
Deposit: matchingEvent.unpack(depositRequest.ExtraData),
FundingTx: fundingTx,
}
}
validateProposalLogger.Infof("calling chain for proposal validation")
err := chain.ValidateDepositSweepProposal(
walletPublicKeyHash,
proposal,
depositExtraInfo,
)
if err != nil {
return nil, fmt.Errorf("deposit sweep proposal is invalid: [%v]", err)
}
validateProposalLogger.Infof(
"deposit sweep proposal is valid",
)
deposits := make([]*Deposit, len(depositExtraInfo))
for i, dei := range depositExtraInfo {
deposits[i] = dei.Deposit
}
return deposits, nil
}
func (dsa *depositSweepAction) wallet() wallet {
return dsa.sweepingWallet
}
func (dsa *depositSweepAction) actionType() WalletActionType {
return ActionDepositSweep
}
// assembleDepositSweepTransaction constructs an unsigned deposit sweep Bitcoin
// transaction.
//
// Regarding input arguments, the walletMainUtxo parameter is optional and
// can be set as nil if the wallet does not have a main UTXO at the moment.
// The deposits slice must contain at least one element. The fee argument
// is not validated in any way so must be chosen with respect to the system
// limitations.
//
// The resulting bitcoin.TransactionBuilder instance holds all the data
// necessary to sign the transaction and obtain a bitcoin.Transaction instance
// ready to be spread across the Bitcoin network.
func assembleDepositSweepTransaction(
bitcoinChain bitcoin.Chain,
walletPublicKey *ecdsa.PublicKey,
walletMainUtxo *bitcoin.UnspentTransactionOutput,
deposits []*Deposit,
fee int64,
) (*bitcoin.TransactionBuilder, error) {
if len(deposits) < 1 {
return nil, fmt.Errorf("at least one deposit is required")
}
builder := bitcoin.NewTransactionBuilder(bitcoinChain)
if walletMainUtxo != nil {
err := builder.AddPublicKeyHashInput(walletMainUtxo)
if err != nil {
return nil, fmt.Errorf(
"cannot add input pointing to wallet main UTXO: [%v]",
err,
)
}
}
for i, deposit := range deposits {
depositScript, err := deposit.Script()
if err != nil {
return nil, fmt.Errorf(
"cannot get script for deposit [%v]: [%v]",
i,
err,
)
}
err = builder.AddScriptHashInput(deposit.Utxo, depositScript)
if err != nil {
return nil, fmt.Errorf(
"cannot add input pointing to deposit [%v] UTXO: [%v]",
i,
err,
)
}
}
walletPublicKeyHash := bitcoin.PublicKeyHash(walletPublicKey)
outputScript, err := bitcoin.PayToWitnessPublicKeyHash(walletPublicKeyHash)
if err != nil {
return nil, fmt.Errorf("cannot compute output script: [%v]", err)
}
outputValue := builder.TotalInputsValue() - fee
builder.AddOutput(&bitcoin.TransactionOutput{
Value: outputValue,
PublicKeyScript: outputScript,
})
return builder, nil
}