/
message_handler.go
288 lines (239 loc) · 8.25 KB
/
message_handler.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
// Copyright 2023 The AthanorLabs/atomic-swap Authors
// SPDX-License-Identifier: LGPL-3.0-only
package xmrtaker
import (
"context"
"fmt"
"time"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/fatih/color"
"github.com/athanorlabs/atomic-swap/common"
"github.com/athanorlabs/atomic-swap/common/types"
mcrypto "github.com/athanorlabs/atomic-swap/crypto/monero"
"github.com/athanorlabs/atomic-swap/monero"
"github.com/athanorlabs/atomic-swap/net/message"
pcommon "github.com/athanorlabs/atomic-swap/protocol"
)
// HandleProtocolMessage is called by the network to handle an incoming message.
// If the message received is not the expected type for the point in the protocol we're at,
// this function will return an error.
func (s *swapState) HandleProtocolMessage(msg common.Message) error {
switch msg := msg.(type) {
case *message.SendKeysMessage:
event := newEventKeysReceived(msg)
s.eventCh <- event
err := <-event.errCh
if err != nil {
return err
}
default:
return errUnexpectedMessageType
}
return nil
}
func (s *swapState) clearNextExpectedEvent(status types.Status) {
s.nextExpectedEvent = EventNoneType
s.updateStatus(status)
}
func (s *swapState) setNextExpectedEvent(event EventType) error {
if s.nextExpectedEvent == EventNoneType {
// should have called clearNextExpectedEvent instead
panic("cannot set next expected event to EventNoneType")
}
if event == s.nextExpectedEvent {
panic("cannot set next expected event to same as current")
}
s.nextExpectedEvent = event
status := event.getStatus()
if status == types.UnknownStatus {
panic("status corresponding to event cannot be UnknownStatus")
}
log.Debugf("setting status to %s", status)
s.updateStatus(status)
return s.Backend.SwapManager().WriteSwapToDB(s.info)
}
func (s *swapState) handleSendKeysMessage(msg *message.SendKeysMessage) (common.Message, error) {
if msg.ProvidedAmount == nil {
return nil, errMissingProvidedAmount
}
if msg.ProvidedAmount.Cmp(s.info.ExpectedAmount) < 0 {
return nil, fmt.Errorf("provided amount is not the same as expected: got %s, expected %s",
msg.ProvidedAmount.Text('f'),
s.info.ExpectedAmount.Text('f'),
)
}
if msg.PublicSpendKey == nil || msg.PrivateViewKey == nil {
return nil, errMissingKeys
}
if msg.EthAddress == (ethcommon.Address{}) {
return nil, errMissingAddress
}
vk := msg.PrivateViewKey
// verify counterparty's DLEq proof and ensure the resulting secp256k1 key is correct
verificationRes, err := pcommon.VerifyKeysAndProof(msg.DLEqProof, msg.Secp256k1PublicKey, msg.PublicSpendKey)
if err != nil {
return nil, err
}
s.xmrmakerAddress = msg.EthAddress
log.Debugf("got XMRMaker's keys and address: address=%s", s.xmrmakerAddress)
symbol, err := pcommon.AssetSymbol(s.Backend, s.info.EthAsset)
if err != nil {
return nil, err
}
log.Infof(color.New(color.Bold).Sprintf("receiving %v XMR for %v %s",
msg.ProvidedAmount,
s.info.ProvidedAmount,
symbol,
))
err = s.setXMRMakerKeys(verificationRes.Ed25519PublicKey, vk, verificationRes.Secp256k1PublicKey)
if err != nil {
return nil, fmt.Errorf("failed to set xmrmaker keys: %w", err)
}
log.Debugf("stored XMR maker's keys, going to lock ETH")
receipt, err := s.lockAsset()
if err != nil {
return nil, fmt.Errorf("failed to lock ethereum asset in contract: %w", err)
}
// start goroutine to check that XMRMaker locks before t_0
go s.runT1ExpirationHandler()
// start goroutine to check for xmr being locked
go s.checkForXMRLock()
out := &message.NotifyETHLocked{
Address: s.SwapCreatorAddr(),
TxHash: receipt.TxHash,
ContractSwapID: s.contractSwapID,
ContractSwap: s.contractSwap,
}
return out, nil
}
func (s *swapState) checkForXMRLock() {
var checkForXMRLockInterval time.Duration
if s.Env() == common.Development {
checkForXMRLockInterval = time.Second
} else {
// monero block time is >1 minute, so this should be fine
checkForXMRLockInterval = time.Minute
}
// check that XMR was locked in expected account, and confirm amount
lockedAddr, vk := s.expectedXMRLockAccount()
conf := s.XMRClient().CreateWalletConf("xmrtaker-swap-wallet-verify-funds")
abViewCli, err := monero.CreateViewOnlyWalletFromKeys(conf, vk, lockedAddr, s.walletScanHeight)
if err != nil {
log.Errorf("failed to generate view-only wallet to verify locked XMR: %s", err)
return
}
defer abViewCli.CloseAndRemoveWallet()
log.Debugf("generated view-only wallet to check funds: %s", abViewCli.WalletName())
timer := time.NewTicker(checkForXMRLockInterval)
for {
select {
case <-s.ctx.Done():
return
case <-timer.C:
balance, err := abViewCli.GetBalance(0)
if err != nil {
log.Errorf("failed to get balance: %s", err)
continue
}
log.Debugf("checking locked wallet, address=%s balance=%d blocks-to-unlock=%d",
lockedAddr, balance.Balance, balance.BlocksToUnlock)
if s.expectedPiconeroAmount().CmpU64(balance.UnlockedBalance) <= 0 {
event := newEventXMRLocked()
s.eventCh <- event
err := <-event.errCh
if err != nil {
log.Errorf("eventXMRLocked errored: %s", err)
}
return
}
}
}
}
func (s *swapState) runT1ExpirationHandler() {
defer log.Debugf("returning from runT1ExpirationHandler")
if time.Until(s.t1) <= 0 {
log.Debugf("T1 already passed, not starting T1 expiration handler")
return
}
// TODO: this variable is so that we definitely refund before t1.
// Current algorithm is to trigger the timeout when only 15% of the allotted
// time is remaining. If the block interval is 1 second on a test network and
// and T1 is 7 seconds after swap creation, we need the refund to trigger more
// than one second before the block with a timestamp exactly equal to T1 to
// satisfy the strictly less than requirement. 7s * 15% = 1.05s. 15% remaining
// may be reasonable even with large timeouts on production networks, but more
// research is needed.
t1Delta := s.t2.Sub(s.t1) // time between swap start and T1 is equal to T2-T1
deltaBeforeT1ToGiveUp := time.Duration(float64(t1Delta) * 0.15)
deltaUntilGiveUp := time.Until(s.t1) - deltaBeforeT1ToGiveUp
giveUpAndRefundTimer := time.NewTimer(deltaUntilGiveUp)
defer giveUpAndRefundTimer.Stop() // don't wait for the timeout to garbage collect
log.Debugf("time until refund: %vs", deltaUntilGiveUp.Seconds())
select {
case <-s.ctx.Done():
return
case <-s.xmrLockedCh:
return
case <-giveUpAndRefundTimer.C:
log.Infof("approaching T1, attempting to refund ETH")
event := newEventShouldRefund()
s.eventCh <- event
err := <-event.errCh
if err != nil {
// TODO: what should we do here? this would be bad. (#162)
log.Errorf("failed to refund: %s", err)
}
}
}
func (s *swapState) expectedXMRLockAccount() (*mcrypto.Address, *mcrypto.PrivateViewKey) {
vk := mcrypto.SumPrivateViewKeys(s.xmrmakerPrivateViewKey, s.privkeys.ViewKey())
sk := mcrypto.SumPublicKeys(s.xmrmakerPublicSpendKey, s.pubkeys.SpendKey())
return mcrypto.NewPublicKeyPair(sk, vk.Public()).Address(s.Env()), vk
}
func (s *swapState) handleNotifyXMRLock() error {
close(s.xmrLockedCh)
log.Info("XMR was locked successfully, setting contract to ready...")
if err := s.setReady(); err != nil {
return fmt.Errorf("failed to call Ready: %w", err)
}
go s.runT2ExpirationHandler()
return nil
}
func (s *swapState) runT2ExpirationHandler() {
log.Debugf("time until t2 (%s): %vs",
s.t2.Format(common.TimeFmtSecs),
time.Until(s.t2).Seconds(),
)
defer log.Debugf("returning from runT2ExpirationHandler")
waitCtx, waitCtxCancel := context.WithCancel(context.Background())
defer waitCtxCancel() // Unblock WaitForTimestamp if still running when we exit
waitCh := make(chan error)
go func() {
waitCh <- s.ETHClient().WaitForTimestamp(waitCtx, s.t2)
close(waitCh)
}()
select {
case <-s.ctx.Done():
return
case <-s.claimedCh:
return
case err := <-waitCh:
if err != nil {
// TODO: Do we propagate this error? If we retry, the logic should probably be inside
// WaitForTimestamp. (#162)
log.Errorf("failure waiting for T2 timeout: %s", err)
return
}
s.handleT2Expired()
}
}
func (s *swapState) handleT2Expired() {
log.Debugf("handling T2")
event := newEventShouldRefund()
s.eventCh <- event
err := <-event.errCh
if err != nil {
// TODO: what should we do here? this would be bad. (#162)
log.Errorf("failed to refund: %s", err)
}
}