-
Notifications
You must be signed in to change notification settings - Fork 75
/
swap.go
309 lines (275 loc) · 7.86 KB
/
swap.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
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
package swap
import (
"context"
"crypto/ecdsa"
"errors"
"fmt"
"math/big"
"os"
"path/filepath"
"sync"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/contracts/chequebook"
"github.com/ethereum/go-ethereum/contracts/chequebook/contract"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/swarm/log"
"github.com/ethereum/go-ethereum/swarm/services/swap/swap"
)
//
//
//
//
//
var (
autoCashInterval = 300 * time.Second //
autoCashThreshold = big.NewInt(50000000000000) //
autoDepositInterval = 300 * time.Second //
autoDepositThreshold = big.NewInt(50000000000000) //
autoDepositBuffer = big.NewInt(100000000000000) //
buyAt = big.NewInt(20000000000) //
sellAt = big.NewInt(20000000000) //
payAt = 100 //
dropAt = 10000 //
)
const (
chequebookDeployRetries = 5
chequebookDeployDelay = 1 * time.Second //
)
//
type LocalProfile struct {
*swap.Params
*PayProfile
}
//
type RemoteProfile struct {
*swap.Profile
*PayProfile
}
//
type PayProfile struct {
PublicKey string //
Contract common.Address //
Beneficiary common.Address //
privateKey *ecdsa.PrivateKey
publicKey *ecdsa.PublicKey
owner common.Address
chbook *chequebook.Chequebook
lock sync.RWMutex
}
//
func NewDefaultSwapParams() *LocalProfile {
return &LocalProfile{
PayProfile: &PayProfile{},
Params: &swap.Params{
Profile: &swap.Profile{
BuyAt: buyAt,
SellAt: sellAt,
PayAt: uint(payAt),
DropAt: uint(dropAt),
},
Strategy: &swap.Strategy{
AutoCashInterval: autoCashInterval,
AutoCashThreshold: autoCashThreshold,
AutoDepositInterval: autoDepositInterval,
AutoDepositThreshold: autoDepositThreshold,
AutoDepositBuffer: autoDepositBuffer,
},
},
}
}
//
//
func (lp *LocalProfile) Init(contract common.Address, prvkey *ecdsa.PrivateKey) {
pubkey := &prvkey.PublicKey
lp.PayProfile = &PayProfile{
PublicKey: common.ToHex(crypto.FromECDSAPub(pubkey)),
Contract: contract,
Beneficiary: crypto.PubkeyToAddress(*pubkey),
privateKey: prvkey,
publicKey: pubkey,
owner: crypto.PubkeyToAddress(*pubkey),
}
}
//
//
//
//
//
//
//
//
func NewSwap(localProfile *LocalProfile, remoteProfile *RemoteProfile, backend chequebook.Backend, proto swap.Protocol) (swapInstance *swap.Swap, err error) {
var (
ctx = context.TODO()
ok bool
in *chequebook.Inbox
out *chequebook.Outbox
)
remotekey, err := crypto.UnmarshalPubkey(common.FromHex(remoteProfile.PublicKey))
if err != nil {
return nil, errors.New("invalid remote public key")
}
//
//
//
ok, err = chequebook.ValidateCode(ctx, backend, remoteProfile.Contract)
if !ok {
log.Info(fmt.Sprintf("invalid contract %v for peer %v: %v)", remoteProfile.Contract.Hex()[:8], proto, err))
} else {
//
in, err = chequebook.NewInbox(localProfile.privateKey, remoteProfile.Contract, localProfile.Beneficiary, remotekey, backend)
if err != nil {
log.Warn(fmt.Sprintf("unable to set up inbox for chequebook contract %v for peer %v: %v)", remoteProfile.Contract.Hex()[:8], proto, err))
}
}
//
ok, err = chequebook.ValidateCode(ctx, backend, localProfile.Contract)
if !ok {
log.Warn(fmt.Sprintf("unable to set up outbox for peer %v: chequebook contract (owner: %v): %v)", proto, localProfile.owner.Hex(), err))
} else {
out = chequebook.NewOutbox(localProfile.Chequebook(), remoteProfile.Beneficiary)
}
pm := swap.Payment{
In: in,
Out: out,
Buys: out != nil,
Sells: in != nil,
}
swapInstance, err = swap.New(localProfile.Params, pm, proto)
if err != nil {
return
}
//
swapInstance.SetRemote(remoteProfile.Profile)
var buy, sell string
if swapInstance.Buys {
buy = "purchase from peer enabled at " + remoteProfile.SellAt.String() + " wei/chunk"
} else {
buy = "purchase from peer disabled"
}
if swapInstance.Sells {
sell = "selling to peer enabled at " + localProfile.SellAt.String() + " wei/chunk"
} else {
sell = "selling to peer disabled"
}
log.Warn(fmt.Sprintf("SWAP arrangement with <%v>: %v; %v)", proto, buy, sell))
return
}
//
func (lp *LocalProfile) Chequebook() *chequebook.Chequebook {
defer lp.lock.Unlock()
lp.lock.Lock()
return lp.chbook
}
//
func (lp *LocalProfile) PrivateKey() *ecdsa.PrivateKey {
return lp.privateKey
}
//
//
//
//
func (lp *LocalProfile) SetKey(prvkey *ecdsa.PrivateKey) {
lp.privateKey = prvkey
lp.publicKey = &prvkey.PublicKey
}
//
func (lp *LocalProfile) SetChequebook(ctx context.Context, backend chequebook.Backend, path string) error {
lp.lock.Lock()
swapContract := lp.Contract
lp.lock.Unlock()
valid, err := chequebook.ValidateCode(ctx, backend, swapContract)
if err != nil {
return err
} else if valid {
return lp.newChequebookFromContract(path, backend)
}
return lp.deployChequebook(ctx, backend, path)
}
//
func (lp *LocalProfile) deployChequebook(ctx context.Context, backend chequebook.Backend, path string) error {
opts := bind.NewKeyedTransactor(lp.privateKey)
opts.Value = lp.AutoDepositBuffer
opts.Context = ctx
log.Info(fmt.Sprintf("Deploying new chequebook (owner: %v)", opts.From.Hex()))
address, err := deployChequebookLoop(opts, backend)
if err != nil {
log.Error(fmt.Sprintf("unable to deploy new chequebook: %v", err))
return err
}
log.Info(fmt.Sprintf("new chequebook deployed at %v (owner: %v)", address.Hex(), opts.From.Hex()))
//
lp.lock.Lock()
lp.Contract = address
err = lp.newChequebookFromContract(path, backend)
lp.lock.Unlock()
if err != nil {
log.Warn(fmt.Sprintf("error initialising cheque book (owner: %v): %v", opts.From.Hex(), err))
}
return err
}
//
func deployChequebookLoop(opts *bind.TransactOpts, backend chequebook.Backend) (addr common.Address, err error) {
var tx *types.Transaction
for try := 0; try < chequebookDeployRetries; try++ {
if try > 0 {
time.Sleep(chequebookDeployDelay)
}
if _, tx, _, err = contract.DeployChequebook(opts, backend); err != nil {
log.Warn(fmt.Sprintf("can't send chequebook deploy tx (try %d): %v", try, err))
continue
}
if addr, err = bind.WaitDeployed(opts.Context, backend, tx); err != nil {
log.Warn(fmt.Sprintf("chequebook deploy error (try %d): %v", try, err))
continue
}
return addr, nil
}
return addr, err
}
//
//
func (lp *LocalProfile) newChequebookFromContract(path string, backend chequebook.Backend) error {
hexkey := common.Bytes2Hex(lp.Contract.Bytes())
err := os.MkdirAll(filepath.Join(path, "chequebooks"), os.ModePerm)
if err != nil {
return fmt.Errorf("unable to create directory for chequebooks: %v", err)
}
chbookpath := filepath.Join(path, "chequebooks", hexkey+".json")
lp.chbook, err = chequebook.LoadChequebook(chbookpath, lp.privateKey, backend, true)
if err != nil {
lp.chbook, err = chequebook.NewChequebook(chbookpath, lp.Contract, lp.privateKey, backend)
if err != nil {
log.Warn(fmt.Sprintf("unable to initialise chequebook (owner: %v): %v", lp.owner.Hex(), err))
return fmt.Errorf("unable to initialise chequebook (owner: %v): %v", lp.owner.Hex(), err)
}
}
lp.chbook.AutoDeposit(lp.AutoDepositInterval, lp.AutoDepositThreshold, lp.AutoDepositBuffer)
log.Info(fmt.Sprintf("auto deposit ON for %v -> %v: interval = %v, threshold = %v, buffer = %v)", crypto.PubkeyToAddress(*(lp.publicKey)).Hex()[:8], lp.Contract.Hex()[:8], lp.AutoDepositInterval, lp.AutoDepositThreshold, lp.AutoDepositBuffer))
return nil
}