-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.go
More file actions
240 lines (224 loc) · 6.09 KB
/
service.go
File metadata and controls
240 lines (224 loc) · 6.09 KB
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
package goeth
import (
"fmt"
"math/big"
"strings"
"time"
"github.com/cheggaaa/pb"
"github.com/dneprix/goeth/model"
"github.com/dneprix/goeth/tx"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
ethereum "github.com/ethereum/go-ethereum/core/types"
"github.com/jinzhu/gorm"
"github.com/shopspring/decimal"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh/terminal"
)
type Service interface {
SendWei(from common.Address, to common.Address, amount *model.Wei) (*model.Transaction, error)
GetLast() (txs []*model.Transaction)
LoadAccounts() error
LoadBalances()
LoadHistoryBlocks(num int)
LoadNewBlocks()
LoadLast()
}
func NewService(db *gorm.DB, client Client) (Service, error) {
svc := &service{
db: db,
client: client,
accounts: make(map[common.Address]string),
nblocksC: make(chan *types.Header),
txLast: tx.NewLast(db),
}
return svc, nil
}
type service struct {
db *gorm.DB
client Client
accounts map[common.Address]string
nblocksC chan *types.Header
txLast tx.Last
}
func (s *service) SendWei(from common.Address, to common.Address, amount *model.Wei) (*model.Transaction, error) {
pass, ok := s.accounts[from]
if !ok {
return nil, fmt.Errorf("account is not added to service: %v", from.String())
}
txHash, err := s.client.SendTransaction(from, to, amount, pass)
if err != nil {
return nil, fmt.Errorf("send tx fail: %v", err)
}
tx := &model.Transaction{
AccountFrom: from,
AccountTo: to,
Amount: amount,
Hash: *txHash,
}
s.db.Create(tx)
return tx, nil
}
func (s *service) GetLast() (txs []*model.Transaction) {
return s.txLast.View()
}
func (s *service) LoadAccounts() error {
addrList, err := s.client.AccountsList()
if err != nil {
return fmt.Errorf("get accounts: %v", err)
}
for _, addr := range addrList {
err := s.processAccount(addr)
if err != nil {
log.Warnf("add account %v error: %v", addr.String(), err)
continue
}
}
if len(s.accounts) == 0 {
return fmt.Errorf("no accounts for service")
}
return nil
}
func (s *service) processAccount(addr common.Address) error {
var answer string
fmt.Printf("\nDo you want to add %v account? (y/N): ", addr.String())
if _, err := fmt.Scan(&answer); err != nil {
return err
}
if strings.ToLower(answer) != "y" {
return nil
}
var bytePass []byte
var okPass bool
for i := 0; i < 3; i++ {
fmt.Print("Enter passphrase: ")
bytePass, _ = terminal.ReadPassword(0)
fmt.Print("\n")
if okPass = s.client.CheckPassphrase(addr, string(bytePass)); okPass {
break
}
}
if !okPass {
log.Fatalf("Wrong passphase")
}
s.db.Save(&model.Account{
Address: addr,
})
s.accounts[addr] = string(bytePass)
return nil
}
func (s *service) LoadBalances() {
for addr, _ := range s.accounts {
balance, err := s.client.BalanceAt(addr)
if err != nil {
log.Errorf("%v balance fail: %s", addr.String(), err)
continue
}
s.db.Model(&model.Account{Address: addr}).
Updates(&model.Account{Balance: balance})
}
}
func (s *service) LoadNewBlocks() {
subs, err := s.client.SubscribeNewHead(s.nblocksC)
if err != nil {
log.Fatal(err)
}
log.Infoln("Subscription started, listening for new blocks")
for {
select {
case h := <-s.nblocksC:
block, err := s.client.BlockByHash(h.Hash())
if err != nil {
log.Warnf("error get block %v: %v", h.Hash().String(), err)
continue
}
s.processBlock(block, nil)
go s.processConfirmations(block.Number())
go s.LoadBalances()
case err := <-subs.Err():
log.Warnln("error from subscription: ", err)
log.Warnln("waiting 10 seconds and retrying")
time.Sleep(time.Second * 10)
nsubs, err := s.client.SubscribeNewHead(s.nblocksC)
if err != nil {
log.Fatal("error trying to resubscribe:", err)
}
subs = nsubs
}
}
}
func (s *service) LoadHistoryBlocks(num int) {
lastBlock, err := s.client.BlockByNumber(nil)
if err != nil {
log.Warnf("load history error: get last block: %v", err)
return
}
bar := pb.StartNew(num)
for i := 0; i < num; i++ {
blockNum := big.NewInt(0).Sub(lastBlock.Number(), big.NewInt(int64(i)))
block, err := s.client.BlockByNumber(blockNum)
if err != nil {
log.Warnf("error get block %v: %v", blockNum.String(), err)
continue
}
s.processBlock(block, lastBlock)
bar.Increment()
}
bar.Finish()
}
func (s *service) processBlock(block *ethereum.Block, lastBlock *ethereum.Block) {
for index, tx := range block.Transactions() {
txTo := tx.To()
if txTo == nil {
continue
}
if _, ok := s.accounts[*txTo]; ok {
confirmations := decimal.New(0, 0)
blockNum := decimal.NewFromBigInt(block.Number(), 0)
if lastBlock != nil {
confirmations = decimal.NewFromBigInt(lastBlock.Number(), 0).Sub(blockNum)
}
txFrom, _ := s.client.TransactionSender(tx, block.Hash(), uint(index))
s.db.Save(&model.Transaction{
Hash: tx.Hash(),
AccountFrom: txFrom,
AccountTo: *txTo,
Amount: model.WeiFromString(tx.Value().String()),
BlockNum: blockNum,
Confirmations: confirmations,
ChainId: decimal.NewFromBigInt(tx.ChainId(), 0),
Gas: tx.Gas(),
GasPrice: decimal.NewFromBigInt(tx.GasPrice(), 0),
Nonce: tx.Nonce(),
Protected: tx.Protected(),
CreatedAt: time.Now(),
})
}
}
}
func (s *service) processConfirmations(lastBlockNum *big.Int) {
var txs []model.Transaction
s.db.Where("block_num > 0 AND confirmations < ?", model.TX_CONFIRM_MAX).Find(&txs)
for _, tx := range txs {
txBlockNum, err := s.client.BlockNumByTxHash(tx.Hash)
if err != nil {
log.Warnf("confirmation get tx %v: %v", tx.Hash.String(), err)
return
}
confirmations := decimal.NewFromBigInt(lastBlockNum, 0).Sub(*txBlockNum)
if txBlockNum.IsPositive() && tx.Confirmations.LessThan(confirmations) {
s.db.Model(&model.Transaction{Hash: tx.Hash}).
Updates(&model.Transaction{
Confirmations: confirmations,
BlockNum: *txBlockNum,
})
}
}
}
func (s *service) LoadLast() {
accounts := make([]common.Address, 0, len(s.accounts))
for addr := range s.accounts {
accounts = append(accounts, addr)
}
s.txLast.Load(accounts)
}