Skip to content

Commit 3402096

Browse files
authored
all: simplify timestamps to uint64 ethereum#19372 (#1318)
1 parent 36374be commit 3402096

38 files changed

+143
-141
lines changed

XDCxlending/XDCxlending.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ func (l *Lending) SyncDataToSDKNode(chain consensus.ChainContext, statedb *state
280280
updatedTakerLendingItem.AutoTopUp = false
281281
case lendingstate.Repay:
282282
updatedTakerLendingItem.Status = lendingstate.Repay
283-
paymentBalance := lendingstate.CalculateTotalRepayValue(block.Time().Uint64(), tradeRecord.LiquidationTime, tradeRecord.Term, tradeRecord.Interest, tradeRecord.Amount)
283+
paymentBalance := lendingstate.CalculateTotalRepayValue(block.Time(), tradeRecord.LiquidationTime, tradeRecord.Term, tradeRecord.Interest, tradeRecord.Amount)
284284
updatedTakerLendingItem.Quantity = paymentBalance
285285
updatedTakerLendingItem.FilledAmount = paymentBalance
286286
// manual repay item
@@ -811,7 +811,7 @@ func (l *Lending) RollbackLendingData(txhash common.Hash) error {
811811
}
812812

813813
func (l *Lending) ProcessLiquidationData(header *types.Header, chain consensus.ChainContext, statedb *state.StateDB, tradingState *tradingstate.TradingStateDB, lendingState *lendingstate.LendingStateDB) (updatedTrades map[common.Hash]*lendingstate.LendingTrade, liquidatedTrades, autoRepayTrades, autoTopUpTrades, autoRecallTrades []*lendingstate.LendingTrade, err error) {
814-
time := header.Time
814+
time := new(big.Int).SetUint64(header.Time)
815815
updatedTrades = map[common.Hash]*lendingstate.LendingTrade{} // sum of liquidatedTrades, autoRepayTrades, autoTopUpTrades, autoRecallTrades
816816
liquidatedTrades = []*lendingstate.LendingTrade{}
817817
autoRepayTrades = []*lendingstate.LendingTrade{}

XDCxlending/order_processor.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ func (l *Lending) processOrderList(header *types.Header, coinbase common.Address
347347
log.Debug("Update quantity for orderId", "orderId", orderId.Hex())
348348
log.Debug("LEND", "lendingOrderBook", lendingOrderBook.Hex(), "Taker Interest", Interest, "maker Interest", order.Interest, "Amount", tradedQuantity, "orderId", orderId, "side", side)
349349
tradingId := lendingStateDB.GetTradeNonce(lendingOrderBook) + 1
350-
liquidationTime := header.Time.Uint64() + order.Term
350+
liquidationTime := header.Time + order.Term
351351
liquidationPrice := new(big.Int).Mul(collateralPrice, liquidationRate)
352352
liquidationPrice = new(big.Int).Div(liquidationPrice, depositRate)
353353
lendingTrade := lendingstate.LendingTrade{
@@ -841,7 +841,7 @@ func (l *Lending) LiquidationExpiredTrade(header *types.Header, chain consensus.
841841
_, liquidationRate, _ := lendingstate.GetCollateralDetail(statedb, lendingTrade.CollateralToken)
842842
collateralAmount := new(big.Int).Mul(repayAmount, big.NewInt(100))
843843
collateralAmount = new(big.Int).Div(collateralAmount, liquidationRate)
844-
totalCollateralAmount := lendingstate.CalculateTotalRepayValue(header.Time.Uint64(), lendingTrade.LiquidationTime, lendingTrade.Term, lendingTrade.Interest, collateralAmount)
844+
totalCollateralAmount := lendingstate.CalculateTotalRepayValue(header.Time, lendingTrade.LiquidationTime, lendingTrade.Term, lendingTrade.Interest, collateralAmount)
845845
interestAmount := new(big.Int).Sub(totalCollateralAmount, collateralAmount)
846846
repayAmount = new(big.Int).Add(repayAmount, interestAmount)
847847
}
@@ -1159,7 +1159,7 @@ func (l *Lending) ProcessRepayLendingTrade(header *types.Header, chain consensus
11591159
if lendingTrade == lendingstate.EmptyLendingTrade {
11601160
return nil, fmt.Errorf("ProcessRepayLendingTrade for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId)
11611161
}
1162-
time := header.Time.Uint64()
1162+
time := header.Time
11631163
tokenBalance := lendingstate.GetTokenBalance(lendingTrade.Borrower, lendingTrade.LendingToken, statedb)
11641164
paymentBalance := lendingstate.CalculateTotalRepayValue(time, lendingTrade.LiquidationTime, lendingTrade.Term, lendingTrade.Interest, lendingTrade.Amount)
11651165
log.Debug("ProcessRepay", "totalInterest", new(big.Int).Sub(paymentBalance, lendingTrade.Amount), "totalRepayValue", paymentBalance, "token", lendingTrade.LendingToken.Hex())

accounts/abi/bind/backends/simulated_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,11 @@ func TestAdjustTime(t *testing.T) {
149149
)
150150
defer sim.Close()
151151

152-
prevTime := sim.pendingBlock.Time().Uint64()
152+
prevTime := sim.pendingBlock.Time()
153153
if err := sim.AdjustTime(time.Second); err != nil {
154154
t.Error(err)
155155
}
156-
newTime := sim.pendingBlock.Time().Uint64()
156+
newTime := sim.pendingBlock.Time()
157157

158158
if newTime-prevTime != uint64(time.Second.Seconds()) {
159159
t.Errorf("adjusted time not equal to a second. prev: %v, new: %v", prevTime, newTime)
@@ -182,11 +182,11 @@ func TestNewAdjustTimeFail(t *testing.T) {
182182
}
183183
sim.Commit()
184184

185-
prevTime := sim.pendingBlock.Time().Uint64()
185+
prevTime := sim.pendingBlock.Time()
186186
if err := sim.AdjustTime(time.Minute); err != nil {
187187
t.Error(err)
188188
}
189-
newTime := sim.pendingBlock.Time().Uint64()
189+
newTime := sim.pendingBlock.Time()
190190
if newTime-prevTime != uint64(time.Minute.Seconds()) {
191191
t.Errorf("adjusted time not equal to a minute. prev: %v, new: %v", prevTime, newTime)
192192
}
@@ -198,7 +198,7 @@ func TestNewAdjustTimeFail(t *testing.T) {
198198
}
199199
sim.SendTransaction(context.Background(), signedTx2)
200200
sim.Commit()
201-
newTime = sim.pendingBlock.Time().Uint64()
201+
newTime = sim.pendingBlock.Time()
202202
if newTime-prevTime >= uint64(time.Minute.Seconds()) {
203203
t.Errorf("time adjusted, but shouldn't be: prev: %v, new: %v", prevTime, newTime)
204204
}
@@ -1385,7 +1385,7 @@ func TestForkResendTx(t *testing.T) {
13851385
if err != nil {
13861386
t.Fatalf("could not sign transaction: %v", err)
13871387
}
1388-
if err = sim.SendTransaction(context.Background(), tx); err != nil {
1388+
if err = sim.SendTransaction(context.Background(), tx); err != nil {
13891389
t.Fatalf("sending transaction: %v", err)
13901390
}
13911391
sim.Commit()

consensus/XDPoS/api.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,7 +297,7 @@ func (api *API) GetV2BlockByHeader(header *types.Header, uncle bool) *V2BlockInf
297297
Round: round,
298298
Committed: committed,
299299
Miner: header.Coinbase.Hash(),
300-
Timestamp: header.Time,
300+
Timestamp: new(big.Int).SetUint64(header.Time),
301301
EncodedRLP: base64.StdEncoding.EncodeToString(encodeBytes),
302302
}
303303
return block

consensus/XDPoS/engines/engine_v1/engine.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ func (x *XDPoS_v1) verifyHeader(chain consensus.ChainReader, header *types.Heade
166166
return consensus.ErrNoValidatorSignature
167167
}
168168
// Don't waste time checking blocks from the future
169-
if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
169+
if header.Time > uint64(time.Now().Unix()) {
170170
return consensus.ErrFutureBlock
171171
}
172172
}
@@ -230,7 +230,7 @@ func (x *XDPoS_v1) verifyCascadingFields(chain consensus.ChainReader, header *ty
230230
if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
231231
return consensus.ErrUnknownAncestor
232232
}
233-
if parent.Time.Uint64()+x.config.Period > header.Time.Uint64() {
233+
if parent.Time+x.config.Period > header.Time {
234234
return utils.ErrInvalidTimestamp
235235
}
236236
// Verify the header's EIP-1559 attributes.
@@ -423,7 +423,7 @@ func (x *XDPoS_v1) YourTurn(chain consensus.ChainReader, parent *types.Header, s
423423
gap = minePeriodCheckpoint * int64(h)
424424
}
425425
log.Info("Distance from the parent block", "seconds", gap, "hops", h)
426-
waitedTime := time.Now().Unix() - parent.Time.Int64()
426+
waitedTime := time.Now().Unix() - int64(parent.Time)
427427
if gap > waitedTime {
428428
return false, nil
429429
}
@@ -775,9 +775,9 @@ func (x *XDPoS_v1) Prepare(chain consensus.ChainReader, header *types.Header) er
775775

776776
// Ensure the timestamp has the correct delay
777777

778-
header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(x.config.Period))
779-
if header.Time.Int64() < time.Now().Unix() {
780-
header.Time = big.NewInt(time.Now().Unix())
778+
header.Time = parent.Time + x.config.Period
779+
if timeNow := uint64(time.Now().Unix()); header.Time < timeNow {
780+
header.Time = timeNow
781781
}
782782
return nil
783783
}

consensus/XDPoS/engines/engine_v2/engine.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ func (x *XDPoS_v2) YourTurn(chain consensus.ChainReader, parent *types.Header, s
283283
}
284284
}
285285

286-
waitedTime := time.Now().Unix() - parent.Time.Int64()
286+
waitedTime := time.Now().Unix() - int64(parent.Time)
287287
minePeriod := x.config.V2.Config(uint64(x.currentRound)).MinePeriod
288288
if waitedTime < int64(minePeriod) {
289289
log.Trace("[YourTurn] wait after mine period", "minePeriod", minePeriod, "waitedTime", waitedTime)
@@ -374,9 +374,9 @@ func (x *XDPoS_v2) Prepare(chain consensus.ChainReader, header *types.Header) er
374374
// Ensure the timestamp has the correct delay
375375
// TODO: Proper deal with time
376376
// TODO: if timestamp > current time, how to deal with future timestamp
377-
header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(x.config.Period))
378-
if header.Time.Int64() < time.Now().Unix() {
379-
header.Time = big.NewInt(time.Now().Unix())
377+
header.Time = parent.Time + x.config.Period
378+
if timeNow := uint64(time.Now().Unix()); header.Time < timeNow {
379+
header.Time = timeNow
380380
}
381381

382382
if header.Coinbase != signer {

consensus/XDPoS/engines/engine_v2/verifyHeader.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (x *XDPoS_v2) verifyHeader(chain consensus.ChainReader, header *types.Heade
4343

4444
if fullVerify {
4545
// Don't waste time checking blocks from the future
46-
if header.Time.Int64() > time.Now().Unix() {
46+
if header.Time > uint64(time.Now().Unix()) {
4747
return consensus.ErrFutureBlock
4848
}
4949
}
@@ -69,8 +69,8 @@ func (x *XDPoS_v2) verifyHeader(chain consensus.ChainReader, header *types.Heade
6969
}
7070

7171
minePeriod := uint64(x.config.V2.Config(uint64(round)).MinePeriod)
72-
if parent.Number.Uint64() > x.config.V2.SwitchBlock.Uint64() && parent.Time.Uint64()+minePeriod > header.Time.Uint64() {
73-
log.Warn("[verifyHeader] Fail to verify header due to invalid timestamp", "ParentTime", parent.Time.Uint64(), "MinePeriod", minePeriod, "HeaderTime", header.Time.Uint64(), "Hash", header.Hash().Hex())
72+
if parent.Number.Uint64() > x.config.V2.SwitchBlock.Uint64() && parent.Time+minePeriod > header.Time {
73+
log.Warn("[verifyHeader] Fail to verify header due to invalid timestamp", "ParentTime", parent.Time, "MinePeriod", minePeriod, "HeaderTime", header.Time, "Hash", header.Hash().Hex())
7474
return utils.ErrInvalidTimestamp
7575
}
7676

consensus/clique/clique.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ func (c *Clique) verifyHeader(chain consensus.ChainReader, header *types.Header,
275275
number := header.Number.Uint64()
276276

277277
// Don't waste time checking blocks from the future
278-
if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 {
278+
if header.Time > uint64(time.Now().Unix()) {
279279
return consensus.ErrFutureBlock
280280
}
281281
// Checkpoint blocks need to enforce zero beneficiary
@@ -353,7 +353,7 @@ func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *type
353353
if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash {
354354
return consensus.ErrUnknownAncestor
355355
}
356-
if parent.Time.Uint64()+c.config.Period > header.Time.Uint64() {
356+
if parent.Time+c.config.Period > header.Time {
357357
return ErrInvalidTimestamp
358358
}
359359
// Verify that the gas limit remains within allowed bounds
@@ -574,9 +574,9 @@ func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) erro
574574
if parent == nil {
575575
return consensus.ErrUnknownAncestor
576576
}
577-
header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period))
578-
if header.Time.Int64() < time.Now().Unix() {
579-
header.Time = big.NewInt(time.Now().Unix())
577+
header.Time = parent.Time + c.config.Period
578+
if header.Time < uint64(time.Now().Unix()) {
579+
header.Time = uint64(time.Now().Unix())
580580
}
581581
return nil
582582
}
@@ -642,7 +642,7 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-ch
642642
}
643643
}
644644
// Sweet, the protocol permits us to sign the block, wait for our time
645-
delay := time.Until(time.Unix(header.Time.Int64(), 0))
645+
delay := time.Until(time.Unix(int64(header.Time), 0))
646646
if header.Difficulty.Cmp(diffNoTurn) == 0 {
647647
// It's not our turn explicitly to sign, delay it a bit
648648
wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime

consensus/ethash/algorithm_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -707,7 +707,7 @@ func TestConcurrentDiskCacheGeneration(t *testing.T) {
707707
Difficulty: big.NewInt(167925187834220),
708708
GasLimit: 4015682,
709709
GasUsed: 0,
710-
Time: big.NewInt(1488928920),
710+
Time: 1488928920,
711711
Extra: []byte("www.bw.com"),
712712
MixDigest: common.HexToHash("0x3e140b0784516af5e5ec6730f2fb20cca22f32be399b9e4ad77d32541f798cd0"),
713713
Nonce: types.EncodeNonce(0xf400cd0006070c49),

consensus/ethash/consensus.go

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
"time"
2626

2727
"github.com/XinFinOrg/XDPoSChain/common"
28-
"github.com/XinFinOrg/XDPoSChain/common/math"
2928
"github.com/XinFinOrg/XDPoSChain/consensus"
3029
"github.com/XinFinOrg/XDPoSChain/consensus/misc"
3130
"github.com/XinFinOrg/XDPoSChain/consensus/misc/eip1559"
@@ -38,18 +37,17 @@ import (
3837

3938
// Ethash proof-of-work protocol constants.
4039
var (
41-
FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
42-
ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
43-
maxUncles = 2 // Maximum number of uncles allowed in a single block
44-
allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks
40+
FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block
41+
ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium
42+
maxUncles = 2 // Maximum number of uncles allowed in a single block
43+
allowedFutureBlockTimeSeconds = int64(15) // Max seconds from current time allowed for blocks, before they're considered future blocks
4544
)
4645

4746
// Various error messages to mark blocks invalid. These should be private to
4847
// prevent engine specific errors from being referenced in the remainder of the
4948
// codebase, inherently breaking if the engine is swapped out. Please put common
5049
// error types into the consensus package.
5150
var (
52-
errLargeBlockTime = errors.New("timestamp too big")
5351
errZeroBlockTime = errors.New("timestamp equals parent's")
5452
errTooManyUncles = errors.New("too many uncles")
5553
errDuplicateUncle = errors.New("duplicate uncle")
@@ -228,20 +226,16 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent *
228226
return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize)
229227
}
230228
// Verify the header's timestamp
231-
if uncle {
232-
if header.Time.Cmp(math.MaxBig256) > 0 {
233-
return errLargeBlockTime
234-
}
235-
} else {
236-
if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 {
229+
if !uncle {
230+
if header.Time > uint64(time.Now().Unix()+allowedFutureBlockTimeSeconds) {
237231
return consensus.ErrFutureBlock
238232
}
239233
}
240-
if header.Time.Cmp(parent.Time) <= 0 {
234+
if header.Time <= parent.Time {
241235
return errZeroBlockTime
242236
}
243237
// Verify the block's difficulty based in it's timestamp and parent's difficulty
244-
expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent)
238+
expected := ethash.CalcDifficulty(chain, header.Time, parent)
245239

246240
if expected.Cmp(header.Difficulty) != 0 {
247241
return fmt.Errorf("invalid difficulty: have %v, want %v", header.Difficulty, expected)
@@ -331,7 +325,7 @@ func calcDifficultyByzantium(time uint64, parent *types.Header) *big.Int {
331325
// ) + 2^(periodCount - 2)
332326

333327
bigTime := new(big.Int).SetUint64(time)
334-
bigParentTime := new(big.Int).Set(parent.Time)
328+
bigParentTime := new(big.Int).SetUint64(parent.Time)
335329

336330
// holds intermediate values to make the algo easier to read & audit
337331
x := new(big.Int)
@@ -390,7 +384,7 @@ func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int {
390384
// ) + 2^(periodCount - 2)
391385

392386
bigTime := new(big.Int).SetUint64(time)
393-
bigParentTime := new(big.Int).Set(parent.Time)
387+
bigParentTime := new(big.Int).SetUint64(parent.Time)
394388

395389
// holds intermediate values to make the algo easier to read & audit
396390
x := new(big.Int)
@@ -438,7 +432,7 @@ func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int {
438432
bigParentTime := new(big.Int)
439433

440434
bigTime.SetUint64(time)
441-
bigParentTime.Set(parent.Time)
435+
bigParentTime.SetUint64(parent.Time)
442436

443437
if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 {
444438
diff.Add(parent.Difficulty, adjust)
@@ -512,7 +506,7 @@ func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header)
512506
if parent == nil {
513507
return consensus.ErrUnknownAncestor
514508
}
515-
header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent)
509+
header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
516510
return nil
517511
}
518512

0 commit comments

Comments
 (0)