This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
tbtc.go
507 lines (439 loc) · 12.7 KB
/
tbtc.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
497
498
499
500
501
502
503
504
505
506
507
//+build !celo
package ethereum
import (
"fmt"
"math/big"
"sort"
"github.com/ethereum/go-ethereum/common"
"github.com/keep-network/keep-common/pkg/chain/ethereum/ethutil"
"github.com/keep-network/keep-common/pkg/subscription"
"github.com/keep-network/keep-ecdsa/pkg/chain"
"github.com/keep-network/keep-ecdsa/pkg/chain/gen/ethereum/contract"
tbtccontract "github.com/keep-network/tbtc/pkg/chain/ethereum/gen/contract"
)
// tbtcApplication represents a tBTC application handle conforming to
// chain.TBTCHandle.
type tbtcApplication struct {
chainHandle *ethereumChain
bondedECDSAKeepFactoryContract *contract.BondedECDSAKeepFactory
tbtcSystemAddress common.Address
tbtcSystemContract *tbtccontract.TBTCSystem
}
func (ec *ethereumChain) TBTCApplicationHandle() (chain.TBTCHandle, error) {
var emptyAddress = common.Address{}
if ec.tbtcSystemAddress == emptyAddress {
return nil, fmt.Errorf("TBTCSystem address unset")
}
tbtcSystemContract, err := tbtccontract.NewTBTCSystem(
ec.tbtcSystemAddress,
ec.chainID,
ec.accountKey,
ec.client,
ec.nonceManager,
ec.miningWaiter,
ec.blockCounter,
ec.transactionMutex,
)
if err != nil {
return nil, err
}
return &tbtcApplication{
chainHandle: ec,
bondedECDSAKeepFactoryContract: ec.bondedECDSAKeepFactoryContract,
tbtcSystemAddress: ec.tbtcSystemAddress,
tbtcSystemContract: tbtcSystemContract,
}, nil
}
func (ta *tbtcApplication) ID() chain.ID {
return ethereumChainID(ta.tbtcSystemAddress)
}
func (ta *tbtcApplication) RegisterAsMemberCandidate() error {
gasEstimate, err :=
ta.bondedECDSAKeepFactoryContract.RegisterMemberCandidateGasEstimate(
ta.tbtcSystemAddress,
)
if err != nil {
return fmt.Errorf("failed to estimate gas [%v]", err)
}
// If we have multiple sortition pool join transactions queued - and that
// happens when multiple operators become eligible to join at the same time,
// e.g. after lowering the minimum bond requirement, transactions mined at
// the end may no longer have valid gas limits as they were estimated based
// on a different state of the pool. We add 20% safety margin to the original
// gas estimation to account for that.
gasEstimateWithMargin := float64(gasEstimate) * float64(1.2)
transaction, err := ta.bondedECDSAKeepFactoryContract.RegisterMemberCandidate(
ta.tbtcSystemAddress,
ethutil.TransactionOptions{
GasLimit: uint64(gasEstimateWithMargin),
},
)
if err != nil {
return err
}
logger.Debugf(
"submitted RegisterMemberCandidate transaction with hash: [%s]",
transaction.Hash(),
)
return nil
}
// IsRegisteredForApplication checks if the operator is registered
// as a signer candidate in the factory for the given application.
func (ta *tbtcApplication) IsRegisteredForApplication() (bool, error) {
return ta.bondedECDSAKeepFactoryContract.IsOperatorRegistered(
ta.chainHandle.operatorAddress(),
ta.tbtcSystemAddress,
)
}
// IsEligibleForApplication checks if the operator is eligible to register
// as a signer candidate for the given application.
func (ta *tbtcApplication) IsEligibleForApplication() (bool, error) {
return ta.bondedECDSAKeepFactoryContract.IsOperatorEligible(
ta.chainHandle.operatorAddress(),
ta.tbtcSystemAddress,
)
}
// IsStatusUpToDateForApplication checks if the operator's status
// is up to date in the signers' pool of the given application.
func (ta *tbtcApplication) IsStatusUpToDateForApplication() (bool, error) {
return ta.bondedECDSAKeepFactoryContract.IsOperatorUpToDate(
ta.chainHandle.operatorAddress(),
ta.tbtcSystemAddress,
)
}
// UpdateStatusForApplication updates the operator's status in the signers'
// pool for the given application.
func (ta *tbtcApplication) UpdateStatusForApplication() error {
transaction, err := ta.bondedECDSAKeepFactoryContract.UpdateOperatorStatus(
ta.chainHandle.operatorAddress(),
ta.tbtcSystemAddress,
)
if err != nil {
return err
}
logger.Debugf(
"submitted UpdateOperatorStatus transaction with hash: [%s]",
transaction.Hash(),
)
return nil
}
// OnDepositCreated installs a callback that is invoked when an
// on-chain notification of a new deposit creation is seen.
func (ta *tbtcApplication) OnDepositCreated(
handler func(depositAddress string),
) subscription.EventSubscription {
onEvent := func(
DepositContractAddress common.Address,
KeepAddress common.Address,
Timestamp *big.Int,
blockNumber uint64,
) {
handler(DepositContractAddress.Hex())
}
return ta.tbtcSystemContract.Created(
nil,
nil,
nil,
).OnEvent(onEvent)
}
// OnDepositRegisteredPubkey installs a callback that is invoked when an
// on-chain notification of a deposit's pubkey registration is seen.
func (ta *tbtcApplication) OnDepositRegisteredPubkey(
handler func(depositAddress string),
) subscription.EventSubscription {
onEvent := func(
DepositContractAddress common.Address,
SigningGroupPubkeyX [32]uint8,
SigningGroupPubkeyY [32]uint8,
Timestamp *big.Int,
blockNumber uint64,
) {
handler(DepositContractAddress.Hex())
}
return ta.tbtcSystemContract.RegisteredPubkey(nil, nil).OnEvent(onEvent)
}
// OnDepositRedemptionRequested installs a callback that is invoked when an
// on-chain notification of a deposit redemption request is seen.
func (ta *tbtcApplication) OnDepositRedemptionRequested(
handler func(depositAddress string),
) subscription.EventSubscription {
onEvent := func(
DepositContractAddress common.Address,
Requester common.Address,
Digest [32]uint8,
UtxoValue *big.Int,
RedeemerOutputScript []uint8,
RequestedFee *big.Int,
Outpoint []uint8,
blockNumber uint64,
) {
handler(DepositContractAddress.Hex())
}
return ta.tbtcSystemContract.RedemptionRequested(
nil,
nil,
nil,
nil,
).OnEvent(onEvent)
}
// OnDepositGotRedemptionSignature installs a callback that is invoked when an
// on-chain notification of a deposit receiving a redemption signature is seen.
func (ta *tbtcApplication) OnDepositGotRedemptionSignature(
handler func(depositAddress string),
) subscription.EventSubscription {
onEvent := func(
DepositContractAddress common.Address,
Digest [32]uint8,
R [32]uint8,
S [32]uint8,
Timestamp *big.Int,
blockNumber uint64,
) {
handler(DepositContractAddress.Hex())
}
return ta.tbtcSystemContract.GotRedemptionSignature(
nil,
nil,
nil,
).OnEvent(onEvent)
}
// OnDepositRedeemed installs a callback that is invoked when an
// on-chain notification of a deposit redemption is seen.
func (ta *tbtcApplication) OnDepositRedeemed(
handler func(depositAddress string),
) subscription.EventSubscription {
onEvent := func(
DepositContractAddress common.Address,
Txid [32]uint8,
Timestamp *big.Int,
blockNumber uint64,
) {
handler(DepositContractAddress.Hex())
}
return ta.tbtcSystemContract.Redeemed(
nil,
nil,
nil,
).OnEvent(onEvent)
}
// PastDepositRedemptionRequestedEvents returns all redemption requested
// events for the given deposit which occurred after the provided start block.
// Returned events are sorted by the block number in the ascending order.
func (ta *tbtcApplication) PastDepositRedemptionRequestedEvents(
startBlock uint64,
depositAddress string,
) ([]*chain.DepositRedemptionRequestedEvent, error) {
if !common.IsHexAddress(depositAddress) {
return nil, fmt.Errorf("incorrect deposit contract address")
}
events, err := ta.tbtcSystemContract.PastRedemptionRequestedEvents(
startBlock,
nil,
[]common.Address{
common.HexToAddress(depositAddress),
},
nil,
nil,
)
if err != nil {
return nil, err
}
result := make([]*chain.DepositRedemptionRequestedEvent, 0)
for _, event := range events {
result = append(result, &chain.DepositRedemptionRequestedEvent{
DepositAddress: event.DepositContractAddress.Hex(),
RequesterAddress: event.Requester.Hex(),
Digest: event.Digest,
UtxoValue: event.UtxoValue,
RedeemerOutputScript: event.RedeemerOutputScript,
RequestedFee: event.RequestedFee,
Outpoint: event.Outpoint,
BlockNumber: event.Raw.BlockNumber,
})
}
// Make sure events are sorted by block number in ascending order.
sort.SliceStable(result, func(i, j int) bool {
return result[i].BlockNumber < result[j].BlockNumber
})
return result, nil
}
func (ta *tbtcApplication) Keep(
depositAddress string,
) (chain.BondedECDSAKeepHandle, error) {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return nil, err
}
keepAddress, err := deposit.KeepAddress()
if err != nil {
return nil, err
}
return ta.chainHandle.GetKeepWithID(ethereumChainID(keepAddress))
}
// RetrieveSignerPubkey retrieves the signer public key for the
// provided deposit.
func (ta *tbtcApplication) RetrieveSignerPubkey(
depositAddress string,
) error {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return err
}
transaction, err := deposit.RetrieveSignerPubkey()
if err != nil {
return err
}
logger.Debugf(
"submitted RetrieveSignerPubkey transaction with hash: [%s]",
transaction.Hash(),
)
return nil
}
// ProvideRedemptionSignature provides the redemption signature for the
// provided deposit.
func (ta *tbtcApplication) ProvideRedemptionSignature(
depositAddress string,
v uint8,
r [32]uint8,
s [32]uint8,
) error {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return err
}
transaction, err := deposit.ProvideRedemptionSignature(v, r, s)
if err != nil {
return err
}
logger.Debugf(
"submitted ProvideRedemptionSignature transaction with hash: [%s]",
transaction.Hash(),
)
return nil
}
// IncreaseRedemptionFee increases the redemption fee for the provided deposit.
func (ta *tbtcApplication) IncreaseRedemptionFee(
depositAddress string,
previousOutputValueBytes [8]uint8,
newOutputValueBytes [8]uint8,
) error {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return err
}
transaction, err := deposit.IncreaseRedemptionFee(
previousOutputValueBytes,
newOutputValueBytes,
)
if err != nil {
return err
}
logger.Debugf(
"submitted IncreaseRedemptionFee transaction with hash: [%s]",
transaction.Hash(),
)
return nil
}
// ProvideRedemptionProof provides the redemption proof for the provided deposit.
func (ta *tbtcApplication) ProvideRedemptionProof(
depositAddress string,
txVersion [4]uint8,
txInputVector []uint8,
txOutputVector []uint8,
txLocktime [4]uint8,
merkleProof []uint8,
txIndexInBlock *big.Int,
bitcoinHeaders []uint8,
) error {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return err
}
transaction, err := deposit.ProvideRedemptionProof(
txVersion,
txInputVector,
txOutputVector,
txLocktime,
merkleProof,
txIndexInBlock,
bitcoinHeaders,
)
if err != nil {
return err
}
logger.Debugf(
"submitted ProvideRedemptionProof transaction with hash: [%s]",
transaction.Hash(),
)
return nil
}
// CurrentState returns the current state for the provided deposit.
func (ta *tbtcApplication) CurrentState(
depositAddress string,
) (chain.DepositState, error) {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return 0, err
}
state, err := deposit.CurrentState()
if err != nil {
return 0, err
}
return chain.DepositState(state.Uint64()), err
}
func (ta *tbtcApplication) getDepositContract(
address string,
) (*tbtccontract.Deposit, error) {
if !common.IsHexAddress(address) {
return nil, fmt.Errorf("incorrect deposit contract address")
}
depositContract, err := tbtccontract.NewDeposit(
common.HexToAddress(address),
ta.chainHandle.chainID,
ta.chainHandle.accountKey,
ta.chainHandle.client,
ta.chainHandle.nonceManager,
ta.chainHandle.miningWaiter,
ta.chainHandle.blockCounter,
ta.chainHandle.transactionMutex,
)
if err != nil {
return nil, err
}
return depositContract, nil
}
// FundingInfo retrieves the funding info for a particular deposit address
func (ta *tbtcApplication) FundingInfo(
depositAddress string,
) (*chain.FundingInfo, error) {
deposit, err := ta.getDepositContract(depositAddress)
if err != nil {
return nil, err
}
fundingInfo, err := deposit.FundingInfo()
if err != nil {
return nil, err
}
logger.Debugf(
"deposit [%s] funding info: %+v",
depositAddress,
fundingInfo,
)
if fundingInfo.FundedAt == nil || fundingInfo.FundedAt.Cmp(big.NewInt(0)) <= 0 {
return nil, chain.ErrDepositNotFunded
}
transactionHash, outputIndex, err := chain.ParseUtxoOutpoint(fundingInfo.UtxoOutpoint)
if err != nil {
return nil, fmt.Errorf(
"failed to parse utx outpoint [%v]: [%v]",
fundingInfo.UtxoOutpoint,
err,
)
}
return &chain.FundingInfo{
UtxoValueBytes: fundingInfo.UtxoValueBytes,
FundedAt: fundingInfo.FundedAt,
TransactionHash: transactionHash,
OutputIndex: outputIndex,
}, nil
}