forked from sonm-io/core
/
api.go
533 lines (450 loc) · 14.6 KB
/
api.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package blockchain
import (
"crypto/ecdsa"
"errors"
"math/big"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/sonm-io/core/blockchain/tsc"
token_api "github.com/sonm-io/core/blockchain/tsc/api"
pb "github.com/sonm-io/core/proto"
"github.com/sonm-io/core/util"
"golang.org/x/net/context"
)
const defaultEthEndpoint = "https://rinkeby.infura.io/00iTrs5PIy0uGODwcsrb"
const defaultGasPrice = 20 * 1000000000
// Dealer - interface above SONM deals
// client - who wanna buy
// hub - who wanna selling its resources
// WARN: this may change at future, by any proposal
type Dealer interface {
// OpenDeal is function to open new deal in blockchain from given address,
// it have effect to change blockchain state, key is mandatory param
// other params caused by SONM office's agreement
// It could be called by client
// return transaction, not deal id
OpenDeal(key *ecdsa.PrivateKey, deal *pb.Deal) (*types.Transaction, error)
// OpenDealPending creates deal and waits for transaction to be committed on blockchain.
// wait is duration to wait for transaction commit, recommended value is 180 seconds.
OpenDealPending(ctx context.Context, key *ecdsa.PrivateKey, deal *pb.Deal, wait time.Duration) (*big.Int, error)
// AcceptDeal accepting deal by hub, causes that hub accept to sell its resources
// It could be called by hub
AcceptDeal(key *ecdsa.PrivateKey, id *big.Int) (*types.Transaction, error)
// CloseDeal closing deal by given id
// It could be called by client
CloseDeal(key *ecdsa.PrivateKey, id *big.Int) (*types.Transaction, error)
// GetDeals is returns ids by given address
GetDeals(address string) ([]*big.Int, error)
// GetDealInfo is returns deal info by given id
GetDealInfo(id *big.Int) (*pb.Deal, error)
// GetDealAmount return global deal counter
GetDealAmount() (*big.Int, error)
// GetOpenedDeal returns only opened deals by given hub/client addresses
GetOpenedDeal(hubAddr string, clientAddr string) ([]*big.Int, error)
// GetAcceptedDeal returns only accepted deals by given hub/client addresses
GetAcceptedDeal(hubAddr string, clientAddr string) ([]*big.Int, error)
// GetClosedDeal returns only closed deals by given hub/client addresses
GetClosedDeal(hubAddr string, clientAddr string) ([]*big.Int, error)
}
// Tokener is go implementation of ERC20-compatibility token with full functionality high-level interface
// standart description with placed: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
type Tokener interface {
// Approve - add allowance from caller to other contract to spend tokens
Approve(key *ecdsa.PrivateKey, to string, amount *big.Int) (*types.Transaction, error)
// Transfer token from caller
Transfer(key *ecdsa.PrivateKey, to string, amount *big.Int) (*types.Transaction, error)
// TransferFrom fallback function for contracts to transfer you allowance
TransferFrom(key *ecdsa.PrivateKey, from string, to string, amount *big.Int) (*types.Transaction, error)
// BalanceOf returns balance of given address
BalanceOf(address string) (*big.Int, error)
// AllowanceOf returns allowance of given address to spender account
AllowanceOf(from string, to string) (*big.Int, error)
// TotalSupply - all amount of emitted token
TotalSupply() (*big.Int, error)
// GetTokens - send 100 SNMT token for message caller
// this function added for MVP purposes and has been deleted later
GetTokens(key *ecdsa.PrivateKey) (*types.Transaction, error)
}
// Blockchainer interface describes operations with deals and tokens
type Blockchainer interface {
Dealer
Tokener
}
func initEthClient(ethEndpoint *string) (*ethclient.Client, error) {
var endpoint string
if ethEndpoint == nil {
endpoint = defaultEthEndpoint
} else {
endpoint = *ethEndpoint
}
ethClient, err := ethclient.Dial(endpoint)
if err != nil {
return nil, err
}
return ethClient, nil
}
func (bch *api) getTxOpts(key *ecdsa.PrivateKey, gasLimit int64) *bind.TransactOpts {
opts := bind.NewKeyedTransactor(key)
opts.GasLimit = big.NewInt(gasLimit)
opts.GasPrice = big.NewInt(bch.gasPrice)
return opts
}
type api struct {
client *ethclient.Client
gasPrice int64
dealsContract *token_api.Deals
tokenContract *token_api.SNMTToken
}
// NewAPI builds new Blockchain instance with given endpoint and gas price
func NewAPI(ethEndpoint *string, gasPrice *int64) (Blockchainer, error) {
client, err := initEthClient(ethEndpoint)
if err != nil {
return nil, err
}
var gp int64
if gasPrice == nil {
gp = defaultGasPrice
} else {
gp = *gasPrice
}
dealsContract, err := token_api.NewDeals(common.HexToAddress(tsc.DealsAddress), client)
if err != nil {
return nil, err
}
tokenContract, err := token_api.NewSNMTToken(common.HexToAddress(tsc.SNMTAddress), client)
if err != nil {
return nil, err
}
bch := &api{
client: client,
gasPrice: gp,
dealsContract: dealsContract,
tokenContract: tokenContract,
}
return bch, nil
}
// ----------------
// Deals appearance
// ----------------
var DealOpenedTopic = common.HexToHash("0x873cb35202fef184c9f8ee23c04e36dc38f3e26fb285224ca574a837be976848")
var DealAcceptedTopic = common.HexToHash("0x3a38edea6028913403c74ce8433c90eca94f4ca074d318d8cb77be5290ba4f15")
var DealClosedTopic = common.HexToHash("0x72615f99a62a6cc2f8452d5c0c9cbc5683995297e1d988f09bb1471d4eefb890")
func (bch *api) OpenDeal(key *ecdsa.PrivateKey, deal *pb.Deal) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 360000)
bigSpec, err := util.ParseBigInt(deal.SpecificationHash)
if err != nil {
return nil, err
}
bigPrice, err := util.ParseBigInt(deal.Price)
if err != nil {
return nil, err
}
tx, err := bch.dealsContract.OpenDeal(
opts,
common.HexToAddress(deal.GetSupplierID()),
common.HexToAddress(deal.GetBuyerID()),
bigSpec,
bigPrice,
big.NewInt(int64(deal.GetWorkTime())),
)
if err != nil {
return nil, err
}
return tx, err
}
func (bch *api) checkTransactionResult(ctx context.Context, tx *types.Transaction) (*big.Int, error) {
txReceipt, err := bch.client.TransactionReceipt(ctx, tx.Hash())
if err != nil {
return nil, err
}
if txReceipt.Status != types.ReceiptStatusSuccessful {
return nil, errors.New("transaction failed")
}
for _, l := range txReceipt.Logs {
if len(l.Topics) < 1 {
return nil, errors.New("transaction topics is malformed")
}
if l.Topics[0] == DealOpenedTopic {
if len(l.Topics) < 4 {
return nil, errors.New("transaction topics content is malformed")
}
return l.Topics[3].Big(), nil
}
}
return nil, errors.New("cannot find the DealOpened topic in transaction")
}
func (bch *api) OpenDealPending(ctx context.Context, key *ecdsa.PrivateKey, deal *pb.Deal, wait time.Duration) (*big.Int, error) {
tx, err := bch.OpenDeal(key, deal)
if err != nil {
return nil, err
}
id, err := bch.checkTransactionResult(ctx, tx)
if err != nil {
// if transaction status is NOT FOUND, then just wait for next tick
// and try to find it again.
if err != ethereum.NotFound {
return nil, err
}
} else {
return id, err
}
ctx, cancel := context.WithTimeout(ctx, wait)
defer cancel()
tk := time.NewTicker(1 * time.Second)
defer tk.Stop()
for {
select {
case <-tk.C:
id, err := bch.checkTransactionResult(ctx, tx)
if err != nil {
if err == ethereum.NotFound {
break
}
return nil, err
}
return id, err
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (bch *api) AcceptDeal(key *ecdsa.PrivateKey, id *big.Int) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 90000)
tx, err := bch.dealsContract.AcceptDeal(opts, id)
if err != nil {
return nil, err
}
return tx, err
}
func (bch *api) CloseDeal(key *ecdsa.PrivateKey, id *big.Int) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 90000)
tx, err := bch.dealsContract.CloseDeal(opts, id)
if err != nil {
return nil, err
}
return tx, err
}
func (bch *api) GetOpenedDeal(hubAddr string, clientAddr string) ([]*big.Int, error) {
var topics [][]common.Hash
// precompile EventName topics
var eventTopic = []common.Hash{DealOpenedTopic, DealAcceptedTopic, DealClosedTopic}
topics = append(topics, eventTopic)
// add filter topic by hub address
// filtering by client address implemented below
if hubAddr != "" {
var addrTopic = []common.Hash{common.HexToHash(common.HexToAddress(hubAddr).String())}
topics = append(topics, addrTopic)
}
logs, err := bch.client.FilterLogs(context.Background(), ethereum.FilterQuery{
Addresses: []common.Address{common.HexToAddress(tsc.DealsAddress)},
Topics: topics,
})
if err != nil {
return nil, err
}
// shifts ids of `DealOpened` event to new slice
idsOpened := make([]common.Hash, 0)
// ids of `DealAccepted` & `DealClosed` to other map
mb := make(map[string]bool)
for _, l := range logs {
// filtering by client address
if clientAddr != "" {
if l.Topics[2] != common.HexToHash(clientAddr) {
continue
}
}
idTopic := l.Topics[3]
switch l.Topics[0] {
case DealOpenedTopic:
idsOpened = append(idsOpened, idTopic)
break
case DealAcceptedTopic, DealClosedTopic:
mb[idTopic.String()] = true
break
}
}
// shift ids of opened deals by accepted and closed deals
var out []*big.Int
for _, item := range idsOpened {
if _, ok := mb[item.String()]; !ok {
if err != nil {
continue
}
out = append(out, item.Big())
}
}
return out, nil
}
func (bch *api) GetAcceptedDeal(hubAddr string, clientAddr string) ([]*big.Int, error) {
var topics [][]common.Hash
// precompile EventName topics
var eventTopic = []common.Hash{DealAcceptedTopic, DealClosedTopic}
topics = append(topics, eventTopic)
// add filter topic by hub address
// filtering by client address implemented below
if hubAddr != "" {
var addrTopic = []common.Hash{common.HexToHash(common.HexToAddress(hubAddr).String())}
topics = append(topics, addrTopic)
}
logs, err := bch.client.FilterLogs(context.Background(), ethereum.FilterQuery{
Addresses: []common.Address{common.HexToAddress(tsc.DealsAddress)},
Topics: topics,
})
if err != nil {
return nil, err
}
// shifts ids of `DealAccepted` event to new slice
idsOpened := make([]common.Hash, 0)
// ids of `DealClosed` to other map
mb := make(map[string]bool)
for _, l := range logs {
// filtering by client address
if clientAddr != "" {
if l.Topics[2] != common.HexToHash(clientAddr) {
continue
}
}
idTopic := l.Topics[3]
switch l.Topics[0] {
case DealAcceptedTopic:
idsOpened = append(idsOpened, idTopic)
break
case DealClosedTopic:
mb[idTopic.String()] = true
break
}
}
// shift ids of opened deals by accepted and closed deals
var out []*big.Int
for _, item := range idsOpened {
if _, ok := mb[item.String()]; !ok {
if err != nil {
continue
}
out = append(out, item.Big())
}
}
return out, nil
}
func (bch *api) GetClosedDeal(hubAddr string, clientAddr string) ([]*big.Int, error) {
var topics [][]common.Hash
// precompile EventName topics
var eventTopic = []common.Hash{DealClosedTopic}
topics = append(topics, eventTopic)
// add filter topic by hub address
// filtering by client address implemented below
if hubAddr != "" {
var addrTopic = []common.Hash{common.HexToHash(common.HexToAddress(hubAddr).String())}
topics = append(topics, addrTopic)
}
logs, err := bch.client.FilterLogs(context.Background(), ethereum.FilterQuery{
Addresses: []common.Address{common.HexToAddress(tsc.DealsAddress)},
Topics: topics,
})
if err != nil {
return nil, err
}
var out []*big.Int
for _, l := range logs {
// filtering by client address
if clientAddr != "" {
if l.Topics[2] != common.HexToHash(clientAddr) {
continue
}
}
out = append(out, l.Topics[3].Big())
}
return out, nil
}
func (bch *api) GetDeals(address string) ([]*big.Int, error) {
clientDeals, err := bch.dealsContract.GetDeals(&bind.CallOpts{Pending: true}, common.HexToAddress(address))
if err != nil {
return nil, err
}
return clientDeals, nil
}
func (bch *api) GetDealInfo(id *big.Int) (*pb.Deal, error) {
deal, err := bch.dealsContract.GetDealInfo(&bind.CallOpts{Pending: true}, id)
if err != nil {
return nil, err
}
dealInfo := pb.Deal{
Id: id.String(),
BuyerID: deal.Client.String(),
SupplierID: deal.Hub.String(),
SpecificationHash: deal.SpecHach.String(),
Price: deal.Price.String(),
Status: pb.DealStatus(deal.Status.Int64()),
StartTime: &pb.Timestamp{Seconds: deal.StartTime.Int64()},
WorkTime: deal.WorkTime.Uint64(),
EndTime: &pb.Timestamp{Seconds: deal.EndTIme.Int64()},
}
return &dealInfo, nil
}
func (bch *api) GetDealAmount() (*big.Int, error) {
res, err := bch.dealsContract.GetDealsAmount(&bind.CallOpts{Pending: true})
if err != nil {
return nil, err
}
return res, nil
}
// ----------------
// Tokener appearance
// ----------------
func (bch *api) BalanceOf(address string) (*big.Int, error) {
balance, err := bch.tokenContract.BalanceOf(&bind.CallOpts{Pending: true}, common.HexToAddress(address))
if err != nil {
return nil, err
}
return balance, nil
}
func (bch *api) AllowanceOf(from string, to string) (*big.Int, error) {
allowance, err := bch.tokenContract.Allowance(&bind.CallOpts{Pending: true}, common.HexToAddress(from), common.HexToAddress(to))
if err != nil {
return nil, err
}
return allowance, nil
}
func (bch *api) Approve(key *ecdsa.PrivateKey, to string, amount *big.Int) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 50000)
tx, err := bch.tokenContract.Approve(opts, common.HexToAddress(to), amount)
if err != nil {
return nil, err
}
return tx, err
}
func (bch *api) Transfer(key *ecdsa.PrivateKey, to string, amount *big.Int) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 50000)
tx, err := bch.tokenContract.Transfer(opts, common.HexToAddress(to), amount)
if err != nil {
return nil, err
}
return tx, err
}
func (bch *api) TransferFrom(key *ecdsa.PrivateKey, from string, to string, amount *big.Int) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 50000)
tx, err := bch.tokenContract.TransferFrom(opts, common.HexToAddress(from), common.HexToAddress(to), amount)
if err != nil {
return nil, err
}
return tx, err
}
func (bch *api) TotalSupply() (*big.Int, error) {
supply, err := bch.tokenContract.TotalSupply(&bind.CallOpts{Pending: true})
if err != nil {
return nil, err
}
return supply, nil
}
func (bch *api) GetTokens(key *ecdsa.PrivateKey) (*types.Transaction, error) {
opts := bch.getTxOpts(key, 50000)
tx, err := bch.tokenContract.GetTokens(opts)
if err != nil {
return nil, err
}
return tx, err
}