-
Notifications
You must be signed in to change notification settings - Fork 203
/
dip.go
307 lines (270 loc) · 7.64 KB
/
dip.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
// Copyright (C) 2018 go-nebulas authors
//
// This file is part of the go-nebulas library.
//
// the go-nebulas library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// the go-nebulas library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
//
package dip
import (
"time"
"github.com/hashicorp/golang-lru"
"github.com/nebulasio/go-nebulas/core"
"github.com/nebulasio/go-nebulas/util"
"github.com/nebulasio/go-nebulas/util/byteutils"
"github.com/nebulasio/go-nebulas/util/logging"
"github.com/sirupsen/logrus"
)
type Dip struct {
neb Neblet
cache *lru.Cache
// reward rewardAddress
rewardAddress *core.Address
rewardValue *util.Uint128
isLooping bool
quitCh chan int
}
// NewDIP create a dip
func NewDIP(neb Neblet) (*Dip, error) {
cache, err := lru.New(CacheSize)
if err != nil {
return nil, err
}
// dip reward address.
priv, err := byteutils.FromHex(DipRewardAddressPrivate)
if err != nil {
return nil, err
}
addr, err := neb.AccountManager().LoadPrivate(priv, []byte(DipRewardAddressPassphrase))
if err != nil {
return nil, err
}
dip := &Dip{
neb: neb,
cache: cache,
quitCh: make(chan int, 1),
isLooping: false,
rewardAddress: addr,
rewardValue: core.DIPReward,
}
return dip, nil
}
// RewardAddress return dip reward rewardAddress.
func (d *Dip) RewardAddress() *core.Address {
return d.rewardAddress
}
func (d *Dip) RewardValue() *util.Uint128 {
return d.rewardValue
}
// Start start dip.
func (d *Dip) Start() {
if !d.isLooping {
d.isLooping = true
logging.CLog().WithFields(logrus.Fields{}).Info("Starting Dip...")
go d.loop()
}
}
// Stop stop dip.
func (d *Dip) Stop() {
if d.isLooping {
d.isLooping = false
logging.CLog().WithFields(logrus.Fields{}).Info("Stopping Dip...")
d.quitCh <- 1
}
}
func (d *Dip) loop() {
logging.CLog().Info("Started Dip.")
timerChan := time.NewTicker(time.Second * 15).C
for {
select {
case <-d.quitCh:
logging.CLog().Info("Stopped Dip.")
return
case <-timerChan:
if d.isLooping {
d.submitReward()
}
}
}
}
func (d *Dip) DipDelayRewardHeight() uint64 {
chainID := d.neb.BlockChain().ChainID()
// for Mainnet and Testnet, delay 0.5 day to submit dip reward.
if chainID == core.MainNetID {
return 12 * 60 * 60 / 15
} else if chainID == core.TestNetID {
return 12 * 60 * 60 / 15
} else {
return 33
}
}
// submitReward generate dip transactions and push to tx pool
func (d *Dip) submitReward() {
height := d.neb.BlockChain().TailBlock().Height() - d.DipDelayRewardHeight()
if height < 1 {
return
}
logging.VLog().WithFields(logrus.Fields{
"height": height,
}).Debug("loop to query dip for submit.")
data, err := d.GetDipList(height, 0)
if err != nil {
logging.VLog().WithFields(logrus.Fields{
"err": err,
}).Warn("Failed to get dip reward list.")
return
}
dipData := data.(*DIPData)
endBlock := d.neb.BlockChain().GetBlockOnCanonicalChainByHeight(dipData.EndHeight)
endAccount, err := endBlock.GetAccount(d.RewardAddress().Bytes())
if err != nil {
logging.VLog().WithFields(logrus.Fields{
"err": err,
}).Error("Failed to load reward account in dip end account.")
return
}
tailAccount, err := d.neb.BlockChain().TailBlock().GetAccount(d.RewardAddress().Bytes())
if err != nil {
logging.VLog().WithFields(logrus.Fields{
"err": err,
}).Error("Failed to load reward account in tail block.")
return
}
for idx, v := range dipData.Dips {
nonce := endAccount.Nonce() + uint64(idx) + 1
// only not reward tx can be pushed to tx pool.
if nonce > tailAccount.Nonce() {
tx, err := d.generateRewardTx(dipData.StartHeight, dipData.EndHeight, dipData.Version, v, nonce, endBlock)
if err != nil {
logging.VLog().WithFields(logrus.Fields{
"err": err,
}).Error("Failed to generate reward transaction.")
return
}
logging.VLog().WithFields(logrus.Fields{
"height": d.neb.BlockChain().TailBlock().Height(),
"start": dipData.StartHeight,
"end": dipData.EndHeight,
"tx": tx,
}).Info("Success to push dip reward tx.")
d.neb.BlockChain().TransactionPool().Push(tx)
}
}
}
func (d *Dip) generateRewardTx(start uint64, end uint64, version uint64, item *DIPItem, nonce uint64, block *core.Block) (*core.Transaction, error) {
var (
to *core.Address
value *util.Uint128
payload *core.DipPayload
payloadBytes []byte
gasLimit *util.Uint128
err error
)
if to, err = core.AddressParse(item.Address); err != nil {
return nil, err
}
if value, err = util.NewUint128FromString(item.Reward); err != nil {
return nil, err
}
if payload, err = core.NewDipPayload(start, end, version, item.Contract); err != nil {
return nil, err
}
if payloadBytes, err = payload.ToBytes(); err != nil {
return nil, err
}
if gasLimit, err = core.MinGasCountPerTransaction.Mul(util.NewUint128FromUint(10)); err != nil {
return nil, err
}
tx, err := core.NewTransaction(
block.ChainID(),
d.RewardAddress(),
to,
value,
nonce,
core.TxPayloadDipType,
payloadBytes,
d.neb.BlockChain().TransactionPool().GetMinGasPrice(),
gasLimit)
if err != nil {
return nil, err
}
// update all reward timestamp to last calculated block timestamp, generate hash equal every loop.
tx.SetTimestamp(block.Timestamp())
if err = d.neb.AccountManager().SignTransactionWithPassphrase(d.RewardAddress(), tx, []byte(DipRewardAddressPassphrase)); err != nil {
return nil, err
}
return tx, nil
}
// GetDipList returns dip info list
func (d *Dip) GetDipList(height, version uint64) (core.Data, error) {
data, err := d.checkCache(height)
if err != nil {
return nil, err
}
return data, nil
}
func (d *Dip) checkCache(height uint64) (*DIPData, error) {
if d.cache.Len() == 0 {
d.loadCache()
}
key := (height-core.NrStartHeight)/core.NrIntervalHeight - 1
if data, ok := d.cache.Get(key); ok {
dipData := data.(*DIPData)
logging.VLog().WithFields(logrus.Fields{
"height": height,
"start": dipData.StartHeight,
"end": dipData.EndHeight,
"dataSize": len(dipData.Dips),
}).Debug("Success to find dip list in cache.")
return dipData, nil
}
return nil, ErrDipNotFound
}
func (d *Dip) CheckReward(tx *core.Transaction) error {
//if tx type is not dip, can't use the reward address send tx.
if tx.Type() != core.TxPayloadDipType && tx.From().Equals(d.rewardAddress) {
return ErrUnsupportedTransactionFromDipAddress
}
if tx.Type() == core.TxPayloadDipType {
if !tx.From().Equals(d.rewardAddress) {
return ErrInvalidDipAddress
}
if tx.To().Equals(core.DIPRewardAddress2) {
return nil
}
payload, err := tx.LoadPayload()
if err != nil {
return err
}
dipPayload := payload.(*core.DipPayload)
height := dipPayload.EndHeight + 1
data, err := d.GetDipList(height, dipPayload.Version)
if err != nil {
return err
}
dip := data.(*DIPData)
for _, v := range dip.Dips {
if tx.To().String() == v.Address && tx.Value().String() == v.Reward {
logging.VLog().WithFields(logrus.Fields{
"height": height,
"start": dip.StartHeight,
"end": dip.EndHeight,
"tx": tx,
}).Debug("Success to check dip reward tx.")
return nil
}
}
return ErrDipNotFound
}
return nil
}