diff --git a/XDCxlending/XDCxlending.go b/XDCxlending/XDCxlending.go index d0093dc151..5922bddda1 100644 --- a/XDCxlending/XDCxlending.go +++ b/XDCxlending/XDCxlending.go @@ -280,7 +280,7 @@ func (l *Lending) SyncDataToSDKNode(chain consensus.ChainContext, statedb *state updatedTakerLendingItem.AutoTopUp = false case lendingstate.Repay: updatedTakerLendingItem.Status = lendingstate.Repay - paymentBalance := lendingstate.CalculateTotalRepayValue(block.Time().Uint64(), tradeRecord.LiquidationTime, tradeRecord.Term, tradeRecord.Interest, tradeRecord.Amount) + paymentBalance := lendingstate.CalculateTotalRepayValue(block.Time(), tradeRecord.LiquidationTime, tradeRecord.Term, tradeRecord.Interest, tradeRecord.Amount) updatedTakerLendingItem.Quantity = paymentBalance updatedTakerLendingItem.FilledAmount = paymentBalance // manual repay item @@ -811,7 +811,7 @@ func (l *Lending) RollbackLendingData(txhash common.Hash) error { } 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) { - time := header.Time + time := new(big.Int).SetUint64(header.Time) updatedTrades = map[common.Hash]*lendingstate.LendingTrade{} // sum of liquidatedTrades, autoRepayTrades, autoTopUpTrades, autoRecallTrades liquidatedTrades = []*lendingstate.LendingTrade{} autoRepayTrades = []*lendingstate.LendingTrade{} diff --git a/XDCxlending/order_processor.go b/XDCxlending/order_processor.go index a46b9dafed..3914d5e9d2 100644 --- a/XDCxlending/order_processor.go +++ b/XDCxlending/order_processor.go @@ -347,7 +347,7 @@ func (l *Lending) processOrderList(header *types.Header, coinbase common.Address log.Debug("Update quantity for orderId", "orderId", orderId.Hex()) log.Debug("LEND", "lendingOrderBook", lendingOrderBook.Hex(), "Taker Interest", Interest, "maker Interest", order.Interest, "Amount", tradedQuantity, "orderId", orderId, "side", side) tradingId := lendingStateDB.GetTradeNonce(lendingOrderBook) + 1 - liquidationTime := header.Time.Uint64() + order.Term + liquidationTime := header.Time + order.Term liquidationPrice := new(big.Int).Mul(collateralPrice, liquidationRate) liquidationPrice = new(big.Int).Div(liquidationPrice, depositRate) lendingTrade := lendingstate.LendingTrade{ @@ -841,7 +841,7 @@ func (l *Lending) LiquidationExpiredTrade(header *types.Header, chain consensus. _, liquidationRate, _ := lendingstate.GetCollateralDetail(statedb, lendingTrade.CollateralToken) collateralAmount := new(big.Int).Mul(repayAmount, big.NewInt(100)) collateralAmount = new(big.Int).Div(collateralAmount, liquidationRate) - totalCollateralAmount := lendingstate.CalculateTotalRepayValue(header.Time.Uint64(), lendingTrade.LiquidationTime, lendingTrade.Term, lendingTrade.Interest, collateralAmount) + totalCollateralAmount := lendingstate.CalculateTotalRepayValue(header.Time, lendingTrade.LiquidationTime, lendingTrade.Term, lendingTrade.Interest, collateralAmount) interestAmount := new(big.Int).Sub(totalCollateralAmount, collateralAmount) repayAmount = new(big.Int).Add(repayAmount, interestAmount) } @@ -1159,7 +1159,7 @@ func (l *Lending) ProcessRepayLendingTrade(header *types.Header, chain consensus if lendingTrade == lendingstate.EmptyLendingTrade { return nil, fmt.Errorf("ProcessRepayLendingTrade for emptyLendingTrade is not allowed. lendingTradeId: %v", lendingTradeId) } - time := header.Time.Uint64() + time := header.Time tokenBalance := lendingstate.GetTokenBalance(lendingTrade.Borrower, lendingTrade.LendingToken, statedb) paymentBalance := lendingstate.CalculateTotalRepayValue(time, lendingTrade.LiquidationTime, lendingTrade.Term, lendingTrade.Interest, lendingTrade.Amount) log.Debug("ProcessRepay", "totalInterest", new(big.Int).Sub(paymentBalance, lendingTrade.Amount), "totalRepayValue", paymentBalance, "token", lendingTrade.LendingToken.Hex()) diff --git a/accounts/abi/bind/backends/simulated_test.go b/accounts/abi/bind/backends/simulated_test.go index 62b72cbccc..ccdbc582a7 100644 --- a/accounts/abi/bind/backends/simulated_test.go +++ b/accounts/abi/bind/backends/simulated_test.go @@ -149,11 +149,11 @@ func TestAdjustTime(t *testing.T) { ) defer sim.Close() - prevTime := sim.pendingBlock.Time().Uint64() + prevTime := sim.pendingBlock.Time() if err := sim.AdjustTime(time.Second); err != nil { t.Error(err) } - newTime := sim.pendingBlock.Time().Uint64() + newTime := sim.pendingBlock.Time() if newTime-prevTime != uint64(time.Second.Seconds()) { t.Errorf("adjusted time not equal to a second. prev: %v, new: %v", prevTime, newTime) @@ -182,11 +182,11 @@ func TestNewAdjustTimeFail(t *testing.T) { } sim.Commit() - prevTime := sim.pendingBlock.Time().Uint64() + prevTime := sim.pendingBlock.Time() if err := sim.AdjustTime(time.Minute); err != nil { t.Error(err) } - newTime := sim.pendingBlock.Time().Uint64() + newTime := sim.pendingBlock.Time() if newTime-prevTime != uint64(time.Minute.Seconds()) { t.Errorf("adjusted time not equal to a minute. prev: %v, new: %v", prevTime, newTime) } @@ -198,7 +198,7 @@ func TestNewAdjustTimeFail(t *testing.T) { } sim.SendTransaction(context.Background(), signedTx2) sim.Commit() - newTime = sim.pendingBlock.Time().Uint64() + newTime = sim.pendingBlock.Time() if newTime-prevTime >= uint64(time.Minute.Seconds()) { t.Errorf("time adjusted, but shouldn't be: prev: %v, new: %v", prevTime, newTime) } @@ -1385,7 +1385,7 @@ func TestForkResendTx(t *testing.T) { if err != nil { t.Fatalf("could not sign transaction: %v", err) } - if err = sim.SendTransaction(context.Background(), tx); err != nil { + if err = sim.SendTransaction(context.Background(), tx); err != nil { t.Fatalf("sending transaction: %v", err) } sim.Commit() diff --git a/consensus/XDPoS/api.go b/consensus/XDPoS/api.go index 9f3dedf108..10f9e949eb 100644 --- a/consensus/XDPoS/api.go +++ b/consensus/XDPoS/api.go @@ -297,7 +297,7 @@ func (api *API) GetV2BlockByHeader(header *types.Header, uncle bool) *V2BlockInf Round: round, Committed: committed, Miner: header.Coinbase.Hash(), - Timestamp: header.Time, + Timestamp: new(big.Int).SetUint64(header.Time), EncodedRLP: base64.StdEncoding.EncodeToString(encodeBytes), } return block diff --git a/consensus/XDPoS/engines/engine_v1/engine.go b/consensus/XDPoS/engines/engine_v1/engine.go index da8188e377..ee0b0b44e7 100644 --- a/consensus/XDPoS/engines/engine_v1/engine.go +++ b/consensus/XDPoS/engines/engine_v1/engine.go @@ -166,7 +166,7 @@ func (x *XDPoS_v1) verifyHeader(chain consensus.ChainReader, header *types.Heade return consensus.ErrNoValidatorSignature } // Don't waste time checking blocks from the future - if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 { + if header.Time > uint64(time.Now().Unix()) { return consensus.ErrFutureBlock } } @@ -230,7 +230,7 @@ func (x *XDPoS_v1) verifyCascadingFields(chain consensus.ChainReader, header *ty if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { return consensus.ErrUnknownAncestor } - if parent.Time.Uint64()+x.config.Period > header.Time.Uint64() { + if parent.Time+x.config.Period > header.Time { return utils.ErrInvalidTimestamp } // Verify the header's EIP-1559 attributes. @@ -423,7 +423,7 @@ func (x *XDPoS_v1) YourTurn(chain consensus.ChainReader, parent *types.Header, s gap = minePeriodCheckpoint * int64(h) } log.Info("Distance from the parent block", "seconds", gap, "hops", h) - waitedTime := time.Now().Unix() - parent.Time.Int64() + waitedTime := time.Now().Unix() - int64(parent.Time) if gap > waitedTime { return false, nil } @@ -775,9 +775,9 @@ func (x *XDPoS_v1) Prepare(chain consensus.ChainReader, header *types.Header) er // Ensure the timestamp has the correct delay - header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(x.config.Period)) - if header.Time.Int64() < time.Now().Unix() { - header.Time = big.NewInt(time.Now().Unix()) + header.Time = parent.Time + x.config.Period + if timeNow := uint64(time.Now().Unix()); header.Time < timeNow { + header.Time = timeNow } return nil } diff --git a/consensus/XDPoS/engines/engine_v2/engine.go b/consensus/XDPoS/engines/engine_v2/engine.go index 98c29d92f4..9de918d1dc 100644 --- a/consensus/XDPoS/engines/engine_v2/engine.go +++ b/consensus/XDPoS/engines/engine_v2/engine.go @@ -283,7 +283,7 @@ func (x *XDPoS_v2) YourTurn(chain consensus.ChainReader, parent *types.Header, s } } - waitedTime := time.Now().Unix() - parent.Time.Int64() + waitedTime := time.Now().Unix() - int64(parent.Time) minePeriod := x.config.V2.Config(uint64(x.currentRound)).MinePeriod if waitedTime < int64(minePeriod) { 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 // Ensure the timestamp has the correct delay // TODO: Proper deal with time // TODO: if timestamp > current time, how to deal with future timestamp - header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(x.config.Period)) - if header.Time.Int64() < time.Now().Unix() { - header.Time = big.NewInt(time.Now().Unix()) + header.Time = parent.Time + x.config.Period + if timeNow := uint64(time.Now().Unix()); header.Time < timeNow { + header.Time = timeNow } if header.Coinbase != signer { diff --git a/consensus/XDPoS/engines/engine_v2/verifyHeader.go b/consensus/XDPoS/engines/engine_v2/verifyHeader.go index cef1331f67..41ebf4f56f 100644 --- a/consensus/XDPoS/engines/engine_v2/verifyHeader.go +++ b/consensus/XDPoS/engines/engine_v2/verifyHeader.go @@ -43,7 +43,7 @@ func (x *XDPoS_v2) verifyHeader(chain consensus.ChainReader, header *types.Heade if fullVerify { // Don't waste time checking blocks from the future - if header.Time.Int64() > time.Now().Unix() { + if header.Time > uint64(time.Now().Unix()) { return consensus.ErrFutureBlock } } @@ -69,8 +69,8 @@ func (x *XDPoS_v2) verifyHeader(chain consensus.ChainReader, header *types.Heade } minePeriod := uint64(x.config.V2.Config(uint64(round)).MinePeriod) - if parent.Number.Uint64() > x.config.V2.SwitchBlock.Uint64() && parent.Time.Uint64()+minePeriod > header.Time.Uint64() { - 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()) + if parent.Number.Uint64() > x.config.V2.SwitchBlock.Uint64() && parent.Time+minePeriod > header.Time { + log.Warn("[verifyHeader] Fail to verify header due to invalid timestamp", "ParentTime", parent.Time, "MinePeriod", minePeriod, "HeaderTime", header.Time, "Hash", header.Hash().Hex()) return utils.ErrInvalidTimestamp } diff --git a/consensus/clique/clique.go b/consensus/clique/clique.go index 6187028711..df2b724293 100644 --- a/consensus/clique/clique.go +++ b/consensus/clique/clique.go @@ -275,7 +275,7 @@ func (c *Clique) verifyHeader(chain consensus.ChainReader, header *types.Header, number := header.Number.Uint64() // Don't waste time checking blocks from the future - if header.Time.Cmp(big.NewInt(time.Now().Unix())) > 0 { + if header.Time > uint64(time.Now().Unix()) { return consensus.ErrFutureBlock } // Checkpoint blocks need to enforce zero beneficiary @@ -353,7 +353,7 @@ func (c *Clique) verifyCascadingFields(chain consensus.ChainReader, header *type if parent == nil || parent.Number.Uint64() != number-1 || parent.Hash() != header.ParentHash { return consensus.ErrUnknownAncestor } - if parent.Time.Uint64()+c.config.Period > header.Time.Uint64() { + if parent.Time+c.config.Period > header.Time { return ErrInvalidTimestamp } // Verify that the gas limit remains within allowed bounds @@ -574,9 +574,9 @@ func (c *Clique) Prepare(chain consensus.ChainReader, header *types.Header) erro if parent == nil { return consensus.ErrUnknownAncestor } - header.Time = new(big.Int).Add(parent.Time, new(big.Int).SetUint64(c.config.Period)) - if header.Time.Int64() < time.Now().Unix() { - header.Time = big.NewInt(time.Now().Unix()) + header.Time = parent.Time + c.config.Period + if header.Time < uint64(time.Now().Unix()) { + header.Time = uint64(time.Now().Unix()) } return nil } @@ -642,7 +642,7 @@ func (c *Clique) Seal(chain consensus.ChainReader, block *types.Block, stop <-ch } } // Sweet, the protocol permits us to sign the block, wait for our time - delay := time.Until(time.Unix(header.Time.Int64(), 0)) + delay := time.Until(time.Unix(int64(header.Time), 0)) if header.Difficulty.Cmp(diffNoTurn) == 0 { // It's not our turn explicitly to sign, delay it a bit wiggle := time.Duration(len(snap.Signers)/2+1) * wiggleTime diff --git a/consensus/ethash/algorithm_test.go b/consensus/ethash/algorithm_test.go index 40524a81e4..ec8405fa35 100644 --- a/consensus/ethash/algorithm_test.go +++ b/consensus/ethash/algorithm_test.go @@ -707,7 +707,7 @@ func TestConcurrentDiskCacheGeneration(t *testing.T) { Difficulty: big.NewInt(167925187834220), GasLimit: 4015682, GasUsed: 0, - Time: big.NewInt(1488928920), + Time: 1488928920, Extra: []byte("www.bw.com"), MixDigest: common.HexToHash("0x3e140b0784516af5e5ec6730f2fb20cca22f32be399b9e4ad77d32541f798cd0"), Nonce: types.EncodeNonce(0xf400cd0006070c49), diff --git a/consensus/ethash/consensus.go b/consensus/ethash/consensus.go index 2bcfd6e0b6..0008100503 100644 --- a/consensus/ethash/consensus.go +++ b/consensus/ethash/consensus.go @@ -25,7 +25,6 @@ import ( "time" "github.com/XinFinOrg/XDPoSChain/common" - "github.com/XinFinOrg/XDPoSChain/common/math" "github.com/XinFinOrg/XDPoSChain/consensus" "github.com/XinFinOrg/XDPoSChain/consensus/misc" "github.com/XinFinOrg/XDPoSChain/consensus/misc/eip1559" @@ -38,10 +37,10 @@ import ( // Ethash proof-of-work protocol constants. var ( - FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block - ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium - maxUncles = 2 // Maximum number of uncles allowed in a single block - allowedFutureBlockTime = 15 * time.Second // Max time from current time allowed for blocks, before they're considered future blocks + FrontierBlockReward *big.Int = big.NewInt(5e+18) // Block reward in wei for successfully mining a block + ByzantiumBlockReward *big.Int = big.NewInt(3e+18) // Block reward in wei for successfully mining a block upward from Byzantium + maxUncles = 2 // Maximum number of uncles allowed in a single block + allowedFutureBlockTimeSeconds = int64(15) // Max seconds from current time allowed for blocks, before they're considered future blocks ) // Various error messages to mark blocks invalid. These should be private to @@ -49,7 +48,6 @@ var ( // codebase, inherently breaking if the engine is swapped out. Please put common // error types into the consensus package. var ( - errLargeBlockTime = errors.New("timestamp too big") errZeroBlockTime = errors.New("timestamp equals parent's") errTooManyUncles = errors.New("too many uncles") errDuplicateUncle = errors.New("duplicate uncle") @@ -228,20 +226,16 @@ func (ethash *Ethash) verifyHeader(chain consensus.ChainReader, header, parent * return fmt.Errorf("extra-data too long: %d > %d", len(header.Extra), params.MaximumExtraDataSize) } // Verify the header's timestamp - if uncle { - if header.Time.Cmp(math.MaxBig256) > 0 { - return errLargeBlockTime - } - } else { - if header.Time.Cmp(big.NewInt(time.Now().Add(allowedFutureBlockTime).Unix())) > 0 { + if !uncle { + if header.Time > uint64(time.Now().Unix()+allowedFutureBlockTimeSeconds) { return consensus.ErrFutureBlock } } - if header.Time.Cmp(parent.Time) <= 0 { + if header.Time <= parent.Time { return errZeroBlockTime } // Verify the block's difficulty based in it's timestamp and parent's difficulty - expected := ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) + expected := ethash.CalcDifficulty(chain, header.Time, parent) if expected.Cmp(header.Difficulty) != 0 { 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 { // ) + 2^(periodCount - 2) bigTime := new(big.Int).SetUint64(time) - bigParentTime := new(big.Int).Set(parent.Time) + bigParentTime := new(big.Int).SetUint64(parent.Time) // holds intermediate values to make the algo easier to read & audit x := new(big.Int) @@ -390,7 +384,7 @@ func calcDifficultyHomestead(time uint64, parent *types.Header) *big.Int { // ) + 2^(periodCount - 2) bigTime := new(big.Int).SetUint64(time) - bigParentTime := new(big.Int).Set(parent.Time) + bigParentTime := new(big.Int).SetUint64(parent.Time) // holds intermediate values to make the algo easier to read & audit x := new(big.Int) @@ -438,7 +432,7 @@ func calcDifficultyFrontier(time uint64, parent *types.Header) *big.Int { bigParentTime := new(big.Int) bigTime.SetUint64(time) - bigParentTime.Set(parent.Time) + bigParentTime.SetUint64(parent.Time) if bigTime.Sub(bigTime, bigParentTime).Cmp(params.DurationLimit) < 0 { diff.Add(parent.Difficulty, adjust) @@ -512,7 +506,7 @@ func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) if parent == nil { return consensus.ErrUnknownAncestor } - header.Difficulty = ethash.CalcDifficulty(chain, header.Time.Uint64(), parent) + header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent) return nil } diff --git a/consensus/ethash/consensus_test.go b/consensus/ethash/consensus_test.go index 3d56792cdd..fe0647e521 100644 --- a/consensus/ethash/consensus_test.go +++ b/consensus/ethash/consensus_test.go @@ -76,7 +76,7 @@ func TestCalcDifficulty(t *testing.T) { number := new(big.Int).Sub(test.CurrentBlocknumber, big.NewInt(1)) diff := CalcDifficulty(config, test.CurrentTimestamp, &types.Header{ Number: number, - Time: new(big.Int).SetUint64(test.ParentTimestamp), + Time: test.ParentTimestamp, Difficulty: test.ParentDifficulty, }) if diff.Cmp(test.CurrentDifficulty) != 0 { diff --git a/consensus/tests/engine_v1_tests/helper.go b/consensus/tests/engine_v1_tests/helper.go index cbebfd1bbf..7da93279e2 100644 --- a/consensus/tests/engine_v1_tests/helper.go +++ b/consensus/tests/engine_v1_tests/helper.go @@ -354,7 +354,7 @@ func createBlockFromHeader(bc *core.BlockChain, customHeader *types.Header, txs Difficulty: difficulty, Number: customHeader.Number, GasLimit: 1200000000, - Time: big.NewInt(time.Now().Unix()), + Time: uint64(time.Now().Unix()), Extra: customHeader.Extra, Validator: customHeader.Validator, Validators: customHeader.Validators, diff --git a/consensus/tests/engine_v2_tests/authorised_masternode_test.go b/consensus/tests/engine_v2_tests/authorised_masternode_test.go index 8f39886ec6..e67651515f 100644 --- a/consensus/tests/engine_v2_tests/authorised_masternode_test.go +++ b/consensus/tests/engine_v2_tests/authorised_masternode_test.go @@ -1,7 +1,6 @@ package engine_v2_tests import ( - "math/big" "testing" "time" @@ -41,7 +40,7 @@ func TestIsYourTurnConsensusV2(t *testing.T) { blockCoinBase := "0x111000000000000000000000000000000123" currentBlock = CreateBlock(blockchain, params.TestXDPoSMockChainConfig, currentBlock, blockNum, 1, blockCoinBase, signer, signFn, nil, nil, "") currentBlockHeader := currentBlock.Header() - currentBlockHeader.Time = big.NewInt(time.Now().Unix()) + currentBlockHeader.Time = uint64(time.Now().Unix()) err := blockchain.InsertBlock(currentBlock) assert.Nil(t, err) adaptor.Initial(blockchain, currentBlockHeader) @@ -94,7 +93,7 @@ func TestIsYourTurnConsensusV2CrossConfig(t *testing.T) { blockCoinBase := "0x111000000000000000000000000000000123" currentBlock = CreateBlock(blockchain, params.TestXDPoSMockChainConfig, currentBlock, blockNum, 10, blockCoinBase, signer, signFn, nil, nil, "") currentBlockHeader := currentBlock.Header() - currentBlockHeader.Time = big.NewInt(time.Now().Unix()) + currentBlockHeader.Time = uint64(time.Now().Unix()) err := blockchain.InsertBlock(currentBlock) adaptor.EngineV2.SetNewRoundFaker(blockchain, types.Round(10), false) assert.Nil(t, err) diff --git a/consensus/tests/engine_v2_tests/helper.go b/consensus/tests/engine_v2_tests/helper.go index 4586502ceb..ccecf8e997 100644 --- a/consensus/tests/engine_v2_tests/helper.go +++ b/consensus/tests/engine_v2_tests/helper.go @@ -877,7 +877,7 @@ func createBlockFromHeader(bc *core.BlockChain, customHeader *types.Header, txs Difficulty: difficulty, Number: customHeader.Number, GasLimit: 1200000000, - Time: big.NewInt(time.Now().Unix() - 1000000 + int64(customHeader.Number.Uint64()*10)), + Time: uint64(time.Now().Unix() - 1000000 + int64(customHeader.Number.Uint64()*10)), Extra: customHeader.Extra, Validator: customHeader.Validator, Validators: customHeader.Validators, diff --git a/consensus/tests/engine_v2_tests/mine_test.go b/consensus/tests/engine_v2_tests/mine_test.go index 7a66536eaf..6ae82986e2 100644 --- a/consensus/tests/engine_v2_tests/mine_test.go +++ b/consensus/tests/engine_v2_tests/mine_test.go @@ -145,13 +145,13 @@ func TestPrepareFail(t *testing.T) { blockchain, _, currentBlock, signer, _, _ := PrepareXDCTestBlockChainForV2Engine(t, int(config.XDPoS.Epoch), config, nil) adaptor := blockchain.Engine().(*XDPoS.XDPoS) - tstamp := time.Now().Unix() + tstamp := uint64(time.Now().Unix()) notReadyToProposeHeader := &types.Header{ ParentHash: currentBlock.Hash(), Number: big.NewInt(int64(901)), GasLimit: params.TargetGasLimit, - Time: big.NewInt(tstamp), + Time: tstamp, Coinbase: signer, } @@ -162,7 +162,7 @@ func TestPrepareFail(t *testing.T) { ParentHash: currentBlock.Hash(), Number: big.NewInt(int64(901)), GasLimit: params.TargetGasLimit, - Time: big.NewInt(tstamp), + Time: tstamp, Coinbase: signer, } // trigger initial which will set the highestQC @@ -176,7 +176,7 @@ func TestPrepareFail(t *testing.T) { ParentHash: currentBlock.Hash(), Number: big.NewInt(int64(901)), GasLimit: params.TargetGasLimit, - Time: big.NewInt(tstamp), + Time: tstamp, } err = adaptor.Prepare(blockchain, header901WithoutCoinbase) @@ -191,13 +191,13 @@ func TestPrepareHappyPath(t *testing.T) { _, err := adaptor.YourTurn(blockchain, currentBlock.Header(), signer) assert.Nil(t, err) - tstamp := time.Now().Unix() + tstamp := uint64(time.Now().Unix()) header901 := &types.Header{ ParentHash: currentBlock.Hash(), Number: big.NewInt(int64(901)), GasLimit: params.TargetGasLimit, - Time: big.NewInt(tstamp), + Time: tstamp, Coinbase: signer, } @@ -271,13 +271,13 @@ func TestUpdateMultipleMasterNodes(t *testing.T) { } } - tstamp := time.Now().Unix() + tstamp := uint64(time.Now().Unix()) header1800 := &types.Header{ ParentHash: parentBlock.Hash(), Number: big.NewInt(int64(1800)), GasLimit: params.TargetGasLimit, - Time: big.NewInt(tstamp), + Time: tstamp, Coinbase: voterAddr, } diff --git a/consensus/tests/engine_v2_tests/timeout_test.go b/consensus/tests/engine_v2_tests/timeout_test.go index 8ce3edbc91..a990e77df5 100644 --- a/consensus/tests/engine_v2_tests/timeout_test.go +++ b/consensus/tests/engine_v2_tests/timeout_test.go @@ -1,7 +1,6 @@ package engine_v2_tests import ( - "math/big" "strconv" "strings" "testing" @@ -111,7 +110,7 @@ func TestTimeoutPeriodAndThreadholdConfigChange(t *testing.T) { blockCoinBase := "0x111000000000000000000000000000000123" currentBlock = CreateBlock(blockchain, params.TestXDPoSMockChainConfig, currentBlock, blockNum, 900, blockCoinBase, signer, signFn, nil, nil, "") currentBlockHeader := currentBlock.Header() - currentBlockHeader.Time = big.NewInt(time.Now().Unix()) + currentBlockHeader.Time = uint64(time.Now().Unix()) err := blockchain.InsertBlock(currentBlock) assert.Nil(t, err) diff --git a/consensus/tests/engine_v2_tests/verify_header_test.go b/consensus/tests/engine_v2_tests/verify_header_test.go index 1237c49914..844a0ec645 100644 --- a/consensus/tests/engine_v2_tests/verify_header_test.go +++ b/consensus/tests/engine_v2_tests/verify_header_test.go @@ -53,7 +53,7 @@ func TestShouldVerifyBlock(t *testing.T) { assert.Equal(t, consensus.ErrNoValidatorSignatureV2, err) blockFromFuture := blockchain.GetBlockByNumber(902).Header() - blockFromFuture.Time = big.NewInt(time.Now().Unix() + 10000) + blockFromFuture.Time = uint64(time.Now().Unix() + 10000) err = adaptor.VerifyHeader(blockchain, blockFromFuture, true) assert.Equal(t, consensus.ErrFutureBlock, err) @@ -97,7 +97,7 @@ func TestShouldVerifyBlock(t *testing.T) { block901 := blockchain.GetBlockByNumber(901).Header() tooFastMinedBlock := blockchain.GetBlockByNumber(902).Header() - tooFastMinedBlock.Time = big.NewInt(block901.Time.Int64() - 10) + tooFastMinedBlock.Time = block901.Time - 10 err = adaptor.VerifyHeader(blockchain, tooFastMinedBlock, true) assert.Equal(t, utils.ErrInvalidTimestamp, err) @@ -351,7 +351,7 @@ func TestConfigSwitchOnDifferentMindPeriod(t *testing.T) { // after 910 require 5 signs, but we only give 3 signs block911 := blockchain.GetBlockByNumber(911).Header() block911.Extra = extraInBytes - block911.Time = big.NewInt(blockchain.GetBlockByNumber(910).Time().Int64() + 2) //2 is previous config, should get the right config from round + block911.Time = blockchain.GetBlockByNumber(910).Time() + 2 // 2 is previous config, should get the right config from round err = adaptor.VerifyHeader(blockchain, block911, true) assert.Equal(t, utils.ErrInvalidTimestamp, err) diff --git a/core/blockchain.go b/core/blockchain.go index 675278d05a..50d82d02da 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -429,9 +429,9 @@ func (bc *BlockChain) loadLastState() error { blockTd := bc.GetTd(currentBlock.Hash(), currentBlock.NumberU64()) fastTd := bc.GetTd(currentFastBlock.Hash(), currentFastBlock.NumberU64()) - log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(currentHeader.Time.Int64(), 0))) - log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(currentBlock.Time().Int64(), 0))) - log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(currentFastBlock.Time().Int64(), 0))) + log.Info("Loaded most recent local header", "number", currentHeader.Number, "hash", currentHeader.Hash(), "td", headerTd, "age", common.PrettyAge(time.Unix(int64(currentHeader.Time), 0))) + log.Info("Loaded most recent local full block", "number", currentBlock.Number(), "hash", currentBlock.Hash(), "td", blockTd, "age", common.PrettyAge(time.Unix(int64(currentBlock.Time()), 0))) + log.Info("Loaded most recent local fast block", "number", currentFastBlock.Number(), "hash", currentFastBlock.Hash(), "td", fastTd, "age", common.PrettyAge(time.Unix(int64(currentFastBlock.Time()), 0))) return nil } @@ -1309,7 +1309,7 @@ func (bc *BlockChain) InsertReceiptChain(blockChain types.Blocks, receiptChain [ context := []interface{}{ "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), - "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(head.Time().Int64(), 0)), + "number", head.Number(), "hash", head.Hash(), "age", common.PrettyAge(time.Unix(int64(head.Time()), 0)), "size", common.StorageSize(bytes), } if stats.ignored > 0 { @@ -1570,8 +1570,8 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. // accepted for future processing, and returns an error if the block is too far // ahead and was not added. func (bc *BlockChain) addFutureBlock(block *types.Block) error { - max := big.NewInt(time.Now().Unix() + maxTimeFutureBlocks) - if block.Time().Cmp(max) > 0 { + max := uint64(time.Now().Unix()) + maxTimeFutureBlocks + if block.Time() > max { return fmt.Errorf("future block timestamp %v > allowed %v", block.Time(), max) } bc.futureBlocks.Add(block.Hash(), block) @@ -2792,7 +2792,7 @@ func (bc *BlockChain) logExchangeData(block *types.Block) { rejectedOrders = rejected.([]*tradingstate.OrderItem) } - txMatchTime := time.Unix(block.Header().Time.Int64(), 0).UTC() + txMatchTime := time.Unix(int64(block.Header().Time), 0).UTC() if err := XDCXService.SyncDataToSDKNode(takerOrderInTx, txMatchBatch.TxHash, txMatchTime, currentState, trades, rejectedOrders, &dirtyOrderCount); err != nil { log.Crit("failed to SyncDataToSDKNode ", "blockNumber", block.Number(), "err", err) return @@ -2846,7 +2846,7 @@ func (bc *BlockChain) logLendingData(block *types.Block) { rejectedOrders = rejected.([]*lendingstate.LendingItem) } - txMatchTime := time.Unix(block.Header().Time.Int64(), 0).UTC() + txMatchTime := time.Unix(int64(block.Header().Time), 0).UTC() statedb, _ := bc.State() if err := lendingService.SyncDataToSDKNode(bc, statedb.Copy(), block, item, batch.TxHash, txMatchTime, trades, rejectedOrders, &dirtyOrderCount); err != nil { @@ -2867,7 +2867,7 @@ func (bc *BlockChain) logLendingData(block *types.Block) { finalizedTrades = finalizedData.(map[common.Hash]*lendingstate.LendingTrade) } if len(finalizedTrades) > 0 { - if err := lendingService.UpdateLiquidatedTrade(block.Time().Uint64(), finalizedTx, finalizedTrades); err != nil { + if err := lendingService.UpdateLiquidatedTrade(block.Time(), finalizedTx, finalizedTrades); err != nil { log.Crit("lending: failed to UpdateLiquidatedTrade ", "blockNumber", block.Number(), "err", err) } } diff --git a/core/blockchain_insert.go b/core/blockchain_insert.go index a80925ab73..b376b98363 100644 --- a/core/blockchain_insert.go +++ b/core/blockchain_insert.go @@ -60,7 +60,7 @@ func (st *insertStats) report(chain []*types.Block, index int, cache common.Stor "elapsed", common.PrettyDuration(elapsed), "mgasps", float64(st.usedGas) * 1000 / float64(elapsed), "number", end.Number(), "hash", end.Hash(), } - if timestamp := time.Unix(end.Time().Int64(), 0); time.Since(timestamp) > time.Minute { + if timestamp := time.Unix(int64(end.Time()), 0); time.Since(timestamp) > time.Minute { context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) } context = append(context, []interface{}{"dirty", cache}...) diff --git a/core/chain_makers.go b/core/chain_makers.go index 5e2fcfcfea..39979664cb 100644 --- a/core/chain_makers.go +++ b/core/chain_makers.go @@ -189,12 +189,12 @@ func (b *BlockGen) PrevBlock(index int) *types.Block { // associated difficulty. It's useful to test scenarios where forking is not // tied to chain length directly. func (b *BlockGen) OffsetTime(seconds int64) { - b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds)) - if b.header.Time.Cmp(b.parent.Header().Time) <= 0 { + b.header.Time += uint64(seconds) + if b.header.Time <= b.parent.Header().Time { panic("block time out of range") } chainReader := &fakeChainReader{config: b.config} - b.header.Difficulty = b.engine.CalcDifficulty(chainReader, b.header.Time.Uint64(), b.parent.Header()) + b.header.Difficulty = b.engine.CalcDifficulty(chainReader, b.header.Time, b.parent.Header()) } // GenerateChain creates a chain of n blocks. The first block's @@ -277,20 +277,19 @@ func GenerateChainWithGenesis(genesis *Genesis, engine consensus.Engine, n int, } func makeHeader(chain consensus.ChainReader, parent *types.Block, state *state.StateDB, engine consensus.Engine) *types.Header { - var time *big.Int - if parent.Time() == nil { - time = big.NewInt(10) + var time uint64 + if parent.Time() == 0 { + time = 10 } else { - time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds + time = parent.Time() + 10 // block time is fixed at 10 seconds } - header := &types.Header{ Root: state.IntermediateRoot(chain.Config().IsEIP158(parent.Number())), ParentHash: parent.Hash(), Coinbase: parent.Coinbase(), - Difficulty: engine.CalcDifficulty(chain, time.Uint64(), &types.Header{ + Difficulty: engine.CalcDifficulty(chain, time, &types.Header{ Number: parent.Number(), - Time: new(big.Int).Sub(time, big.NewInt(10)), + Time: time - 10, Difficulty: parent.Difficulty(), UncleHash: parent.UncleHash(), }), diff --git a/core/evm.go b/core/evm.go index 4f42850fee..bbf6249cd5 100644 --- a/core/evm.go +++ b/core/evm.go @@ -60,7 +60,7 @@ func NewEVMBlockContext(header *types.Header, chain ChainContext, author *common GetHash: GetHashFn(header, chain), Coinbase: beneficiary, BlockNumber: new(big.Int).Set(header.Number), - Time: new(big.Int).Set(header.Time), + Time: new(big.Int).SetUint64(header.Time), Difficulty: new(big.Int).Set(header.Difficulty), BaseFee: baseFee, GasLimit: header.GasLimit, diff --git a/core/genesis.go b/core/genesis.go index 75e019bfd6..77cb447180 100644 --- a/core/genesis.go +++ b/core/genesis.go @@ -197,7 +197,7 @@ func (g *Genesis) ToBlock(db ethdb.Database) *types.Block { head := &types.Header{ Number: new(big.Int).SetUint64(g.Number), Nonce: types.EncodeNonce(g.Nonce), - Time: new(big.Int).SetUint64(g.Timestamp), + Time: g.Timestamp, ParentHash: g.ParentHash, Extra: g.ExtraData, GasLimit: g.GasLimit, diff --git a/core/headerchain.go b/core/headerchain.go index 28b7ec5358..ea1123e59d 100644 --- a/core/headerchain.go +++ b/core/headerchain.go @@ -304,7 +304,7 @@ func (hc *HeaderChain) InsertHeaderChain(chain []*types.Header, writeHeader WhCa "count", stats.processed, "elapsed", common.PrettyDuration(time.Since(start)), "number", last.Number, "hash", last.Hash(), } - if timestamp := time.Unix(last.Time.Int64(), 0); time.Since(timestamp) > time.Minute { + if timestamp := time.Unix(int64(last.Time), 0); time.Since(timestamp) > time.Minute { context = append(context, []interface{}{"age", common.PrettyAge(timestamp)}...) } if stats.ignored > 0 { diff --git a/core/state_processor_test.go b/core/state_processor_test.go index 830e2badc6..999ab04d9c 100644 --- a/core/state_processor_test.go +++ b/core/state_processor_test.go @@ -256,7 +256,7 @@ func GenerateBadBlock(t *testing.T, parent *types.Block, engine consensus.Engine header := &types.Header{ ParentHash: parent.Hash(), Coinbase: parent.Coinbase(), - Difficulty: engine.CalcDifficulty(&fakeChainReader{config}, parent.Time().Uint64()+10, &types.Header{ + Difficulty: engine.CalcDifficulty(&fakeChainReader{config}, parent.Time()+10, &types.Header{ Number: parent.Number(), Time: parent.Time(), Difficulty: parent.Difficulty(), @@ -264,7 +264,7 @@ func GenerateBadBlock(t *testing.T, parent *types.Block, engine consensus.Engine }), GasLimit: parent.GasLimit(), Number: new(big.Int).Add(parent.Number(), common.Big1), - Time: new(big.Int).SetUint64(parent.Time().Uint64() + 10), + Time: parent.Time() + 10, UncleHash: types.EmptyUncleHash, } if config.IsEIP1559(header.Number) { diff --git a/core/types/block.go b/core/types/block.go index 93d71d3974..bd07d5e7c8 100644 --- a/core/types/block.go +++ b/core/types/block.go @@ -22,10 +22,10 @@ import ( "fmt" "io" "math/big" + "reflect" "sort" "sync/atomic" "time" - "unsafe" "github.com/XinFinOrg/XDPoSChain/common" "github.com/XinFinOrg/XDPoSChain/common/hexutil" @@ -74,7 +74,7 @@ type Header struct { Number *big.Int `json:"number" gencodec:"required"` GasLimit uint64 `json:"gasLimit" gencodec:"required"` GasUsed uint64 `json:"gasUsed" gencodec:"required"` - Time *big.Int `json:"timestamp" gencodec:"required"` + Time uint64 `json:"timestamp" gencodec:"required"` Extra []byte `json:"extraData" gencodec:"required"` MixDigest common.Hash `json:"mixHash" gencodec:"required"` Nonce BlockNonce `json:"nonce" gencodec:"required"` @@ -92,7 +92,7 @@ type headerMarshaling struct { Number *hexutil.Big GasLimit hexutil.Uint64 GasUsed hexutil.Uint64 - Time *hexutil.Big + Time hexutil.Uint64 Extra hexutil.Bytes BaseFee *hexutil.Big Hash common.Hash `json:"hash"` // adds call to Hash() in MarshalJSON @@ -147,10 +147,16 @@ func (h *Header) HashNoValidator() common.Hash { }) } +var headerSize = common.StorageSize(reflect.TypeOf(Header{}).Size()) + // Size returns the approximate memory used by all internal contents. It is used // to approximate and limit the memory consumption of various caches. func (h *Header) Size() common.StorageSize { - return common.StorageSize(unsafe.Sizeof(*h)) + common.StorageSize(len(h.Extra)+(h.Difficulty.BitLen()+h.Number.BitLen()+h.Time.BitLen())/8) + var baseFeeBits int + if h.BaseFee != nil { + baseFeeBits = h.BaseFee.BitLen() + } + return headerSize + common.StorageSize(len(h.Extra)+len(h.Validators)+len(h.Validator)+len(h.Penalties)+(h.Difficulty.BitLen()+h.Number.BitLen()+baseFeeBits)/8) } // EmptyBody returns true if there is no additional 'body' to complete the header @@ -270,9 +276,6 @@ func NewBlockWithHeader(header *Header) *Block { // modifying a header variable. func CopyHeader(h *Header) *Header { cpy := *h - if cpy.Time = new(big.Int); h.Time != nil { - cpy.Time.Set(h.Time) - } if cpy.Difficulty = new(big.Int); h.Difficulty != nil { cpy.Difficulty.Set(h.Difficulty) } @@ -286,10 +289,18 @@ func CopyHeader(h *Header) *Header { cpy.Extra = make([]byte, len(h.Extra)) copy(cpy.Extra, h.Extra) } + if len(h.Validators) > 0 { + cpy.Validators = make([]byte, len(h.Validators)) + copy(cpy.Validators, h.Validators) + } if len(h.Validator) > 0 { cpy.Validator = make([]byte, len(h.Validator)) copy(cpy.Validator, h.Validator) } + if len(h.Penalties) > 0 { + cpy.Penalties = make([]byte, len(h.Penalties)) + copy(cpy.Penalties, h.Penalties) + } return &cpy } @@ -342,7 +353,7 @@ func (b *Block) Number() *big.Int { return new(big.Int).Set(b.header.Number) func (b *Block) GasLimit() uint64 { return b.header.GasLimit } func (b *Block) GasUsed() uint64 { return b.header.GasUsed } func (b *Block) Difficulty() *big.Int { return new(big.Int).Set(b.header.Difficulty) } -func (b *Block) Time() *big.Int { return new(big.Int).Set(b.header.Time) } +func (b *Block) Time() uint64 { return b.header.Time } func (b *Block) NumberU64() uint64 { return b.header.Number.Uint64() } func (b *Block) MixDigest() common.Hash { return b.header.MixDigest } diff --git a/core/types/block_test.go b/core/types/block_test.go index 4c496b2901..91eabbadba 100644 --- a/core/types/block_test.go +++ b/core/types/block_test.go @@ -52,7 +52,7 @@ func TestBlockEncoding(t *testing.T) { check("Root", block.Root().String(), common.HexToHash("ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017").String()) check("Hash", block.Hash().String(), common.HexToHash("e8d9d473fdeddd3079988fa7be58f582b7b2800e90917d4bb6f11155ce4dba30").String()) check("Nonce", block.Nonce(), uint64(0xa13a5a8c8f2bb1c4)) - check("Time", block.Time(), big.NewInt(1426516743)) + check("Time", block.Time(), uint64(1426516743)) check("Size", block.Size(), common.StorageSize(len(blockEnc))) ourBlockEnc, err := rlp.EncodeToBytes(&block) @@ -84,7 +84,7 @@ func TestEIP2718BlockEncoding(t *testing.T) { check("MixDigest", block.MixDigest(), common.HexToHash("bd4472abb6659ebe3ee06ee4d7b72a00a9f4d001caca51342001075469aff498")) check("Root", block.Root(), common.HexToHash("ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017")) check("Nonce", block.Nonce(), uint64(0xa13a5a8c8f2bb1c4)) - check("Time", block.Time().Uint64(), uint64(1426516743)) + check("Time", block.Time(), uint64(1426516743)) check("Size", block.Size(), common.StorageSize(len(blockEnc))) // Create legacy tx. @@ -186,7 +186,7 @@ func makeBenchBlock() *Block { Number: math.BigPow(2, 9), GasLimit: 12345678, GasUsed: 1476322, - Time: big.NewInt(9876543), + Time: 9876543, Extra: []byte("coolest block on chain"), } for i := range txs { @@ -207,7 +207,7 @@ func makeBenchBlock() *Block { Number: math.BigPow(2, 9), GasLimit: 12345678, GasUsed: 1476322, - Time: big.NewInt(9876543), + Time: 9876543, Extra: []byte("benchmark uncle"), } } diff --git a/core/types/gen_header_json.go b/core/types/gen_header_json.go index 4f8b851b36..05889cdc30 100644 --- a/core/types/gen_header_json.go +++ b/core/types/gen_header_json.go @@ -27,7 +27,7 @@ func (h Header) MarshalJSON() ([]byte, error) { Number *hexutil.Big `json:"number" gencodec:"required"` GasLimit hexutil.Uint64 `json:"gasLimit" gencodec:"required"` GasUsed hexutil.Uint64 `json:"gasUsed" gencodec:"required"` - Time *hexutil.Big `json:"timestamp" gencodec:"required"` + Time hexutil.Uint64 `json:"timestamp" gencodec:"required"` Extra hexutil.Bytes `json:"extraData" gencodec:"required"` MixDigest common.Hash `json:"mixHash" gencodec:"required"` Nonce BlockNonce `json:"nonce" gencodec:"required"` @@ -49,7 +49,7 @@ func (h Header) MarshalJSON() ([]byte, error) { enc.Number = (*hexutil.Big)(h.Number) enc.GasLimit = hexutil.Uint64(h.GasLimit) enc.GasUsed = hexutil.Uint64(h.GasUsed) - enc.Time = (*hexutil.Big)(h.Time) + enc.Time = hexutil.Uint64(h.Time) enc.Extra = h.Extra enc.MixDigest = h.MixDigest enc.Nonce = h.Nonce @@ -75,7 +75,7 @@ func (h *Header) UnmarshalJSON(input []byte) error { Number *hexutil.Big `json:"number" gencodec:"required"` GasLimit *hexutil.Uint64 `json:"gasLimit" gencodec:"required"` GasUsed *hexutil.Uint64 `json:"gasUsed" gencodec:"required"` - Time *hexutil.Big `json:"timestamp" gencodec:"required"` + Time *hexutil.Uint64 `json:"timestamp" gencodec:"required"` Extra *hexutil.Bytes `json:"extraData" gencodec:"required"` MixDigest *common.Hash `json:"mixHash" gencodec:"required"` Nonce *BlockNonce `json:"nonce" gencodec:"required"` @@ -135,7 +135,7 @@ func (h *Header) UnmarshalJSON(input []byte) error { if dec.Time == nil { return errors.New("missing required field 'timestamp' for Header") } - h.Time = (*big.Int)(dec.Time) + h.Time = uint64(*dec.Time) if dec.Extra == nil { return errors.New("missing required field 'extraData' for Header") } diff --git a/core/vm/runtime/runtime_test.go b/core/vm/runtime/runtime_test.go index 87e1bac529..386b42b5bc 100644 --- a/core/vm/runtime/runtime_test.go +++ b/core/vm/runtime/runtime_test.go @@ -217,7 +217,7 @@ func fakeHeader(n uint64, parentHash common.Hash) *types.Header { Coinbase: common.HexToAddress("0x00000000000000000000000000000000deadbeef"), Number: big.NewInt(int64(n)), ParentHash: parentHash, - Time: big.NewInt(1000), + Time: 1000, Nonce: types.BlockNonce{0x1}, Extra: []byte{}, Difficulty: big.NewInt(0), diff --git a/eth/api_backend.go b/eth/api_backend.go index df10cb6c2a..3569012186 100644 --- a/eth/api_backend.go +++ b/eth/api_backend.go @@ -577,7 +577,7 @@ func (b *EthAPIBackend) GetEpochDuration() *big.Int { secondToLastCheckpointNumber := lastCheckpointNumber - b.ChainConfig().XDPoS.Epoch secondToLastCheckpointBlockTime := chain.GetBlockByNumber(secondToLastCheckpointNumber).Time() - return secondToLastCheckpointBlockTime.Add(secondToLastCheckpointBlockTime, lastCheckpointBlockTime.Mul(lastCheckpointBlockTime, new(big.Int).SetInt64(-1))) + return new(big.Int).SetInt64(int64(secondToLastCheckpointBlockTime) - int64(lastCheckpointBlockTime)) } // GetMasternodesCap return a cap of all masternode at a checkpoint diff --git a/eth/fetcher/fetcher.go b/eth/fetcher/fetcher.go index c4aa795532..04e9f9861d 100644 --- a/eth/fetcher/fetcher.go +++ b/eth/fetcher/fetcher.go @@ -689,7 +689,7 @@ func (f *Fetcher) insert(peer string, block *types.Block) { go f.broadcastBlock(block, true) } case consensus.ErrFutureBlock: - delay := time.Until(time.Unix(block.Time().Int64(), 0)) + delay := time.Until(time.Unix(int64(block.Time()), 0)) log.Info("Receive future block", "number", block.NumberU64(), "hash", block.Hash().Hex(), "delay", delay) time.Sleep(delay) goto again diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go index 4f3af91e1d..0e69a00251 100644 --- a/ethstats/ethstats.go +++ b/ethstats/ethstats.go @@ -672,7 +672,7 @@ func (s *Service) assembleBlockStats(block *types.Block) *blockStats { Number: header.Number, Hash: header.Hash(), ParentHash: header.ParentHash, - Timestamp: header.Time, + Timestamp: new(big.Int).SetUint64(header.Time), Miner: author, GasUsed: header.GasUsed, GasLimit: header.GasLimit, diff --git a/internal/ethapi/api.go b/internal/ethapi/api.go index c79e6749c2..acac735cbf 100644 --- a/internal/ethapi/api.go +++ b/internal/ethapi/api.go @@ -1379,7 +1379,7 @@ func RPCMarshalHeader(head *types.Header) map[string]interface{} { "size": hexutil.Uint64(head.Size()), "gasLimit": hexutil.Uint64(head.GasLimit), "gasUsed": hexutil.Uint64(head.GasUsed), - "timestamp": (*hexutil.Big)(head.Time), + "timestamp": hexutil.Uint64(head.Time), "transactionsRoot": head.TxHash, "receiptsRoot": head.ReceiptHash, "validators": hexutil.Bytes(head.Validators), diff --git a/internal/ethapi/transaction_args_test.go b/internal/ethapi/transaction_args_test.go index 16de689df1..e34d3a2934 100644 --- a/internal/ethapi/transaction_args_test.go +++ b/internal/ethapi/transaction_args_test.go @@ -261,7 +261,7 @@ func newBackendMock() *backendMock { Number: big.NewInt(1100), GasLimit: 8_000_000, GasUsed: 8_000_000, - Time: big.NewInt(555), + Time: 555, Extra: make([]byte, 32), BaseFee: big.NewInt(10), }, diff --git a/miner/worker.go b/miner/worker.go index 1d6ef32784..8b6ca93d4d 100644 --- a/miner/worker.go +++ b/miner/worker.go @@ -383,7 +383,7 @@ func (w *worker) update() { func getResetTime(chain *core.BlockChain, minePeriod int) time.Duration { minePeriodDuration := time.Duration(minePeriod) * time.Second - currentBlockTime := chain.CurrentBlock().Time().Int64() + currentBlockTime := int64(chain.CurrentBlock().Time()) nowTime := time.Now().UnixMilli() resetTime := time.Duration(currentBlockTime)*time.Second + minePeriodDuration - time.Duration(nowTime)*time.Millisecond // in case the current block time is not very accurate @@ -639,8 +639,8 @@ func (w *worker) commitNewWork() { } } tstamp := tstart.Unix() - if parent.Time().Cmp(new(big.Int).SetInt64(tstamp)) >= 0 { - tstamp = parent.Time().Int64() + 1 + if parent.Time() >= uint64(tstamp) { + tstamp = int64(parent.Time() + 1) } // this will ensure we're not going off too far in the future if now := time.Now().Unix(); tstamp > now { @@ -655,7 +655,7 @@ func (w *worker) commitNewWork() { Number: num.Add(num, common.Big1), GasLimit: params.TargetGasLimit, Extra: w.extra, - Time: big.NewInt(tstamp), + Time: uint64(tstamp), } // Set baseFee if we are on an EIP-1559 chain header.BaseFee = eip1559.CalcBaseFee(w.config, header) diff --git a/tests/block_test_util.go b/tests/block_test_util.go index 75a43d0921..f0155d2d48 100644 --- a/tests/block_test_util.go +++ b/tests/block_test_util.go @@ -81,7 +81,7 @@ type btHeader struct { Difficulty *big.Int GasLimit uint64 GasUsed uint64 - Timestamp *big.Int + Timestamp uint64 BaseFee *big.Int } @@ -91,7 +91,7 @@ type btHeaderMarshaling struct { Difficulty *math.HexOrDecimal256 GasLimit math.HexOrDecimal64 GasUsed math.HexOrDecimal64 - Timestamp *math.HexOrDecimal256 + Timestamp math.HexOrDecimal64 BaseFee *math.HexOrDecimal256 } @@ -142,7 +142,7 @@ func (t *BlockTest) genesis(config *params.ChainConfig) *core.Genesis { return &core.Genesis{ Config: config, Nonce: t.json.Genesis.Nonce.Uint64(), - Timestamp: t.json.Genesis.Timestamp.Uint64(), + Timestamp: t.json.Genesis.Timestamp, ParentHash: t.json.Genesis.ParentHash, ExtraData: t.json.Genesis.ExtraData, GasLimit: t.json.Genesis.GasLimit, @@ -251,7 +251,7 @@ func validateHeader(h *btHeader, h2 *types.Header) error { if h.GasUsed != h2.GasUsed { return fmt.Errorf("mismatch GasUsed: want: %d have: %d", h.GasUsed, h2.GasUsed) } - if h.Timestamp.Cmp(h2.Time) != 0 { + if h.Timestamp != h2.Time { return fmt.Errorf("mismatch Timestamp: want: %v have: %v", h.Timestamp, h2.Time) } return nil diff --git a/tests/difficulty_test_util.go b/tests/difficulty_test_util.go index 9b628fa2d6..4af91a2206 100644 --- a/tests/difficulty_test_util.go +++ b/tests/difficulty_test_util.go @@ -30,18 +30,18 @@ import ( //go:generate go run github.com/fjl/gencodec -type DifficultyTest -field-override difficultyTestMarshaling -out gen_difficultytest.go type DifficultyTest struct { - ParentTimestamp *big.Int `json:"parentTimestamp"` + ParentTimestamp uint64 `json:"parentTimestamp"` ParentDifficulty *big.Int `json:"parentDifficulty"` UncleHash common.Hash `json:"parentUncles"` - CurrentTimestamp *big.Int `json:"currentTimestamp"` + CurrentTimestamp uint64 `json:"currentTimestamp"` CurrentBlockNumber uint64 `json:"currentBlockNumber"` CurrentDifficulty *big.Int `json:"currentDifficulty"` } type difficultyTestMarshaling struct { - ParentTimestamp *math.HexOrDecimal256 + ParentTimestamp math.HexOrDecimal64 ParentDifficulty *math.HexOrDecimal256 - CurrentTimestamp *math.HexOrDecimal256 + CurrentTimestamp math.HexOrDecimal64 CurrentDifficulty *math.HexOrDecimal256 UncleHash common.Hash CurrentBlockNumber math.HexOrDecimal64 @@ -56,7 +56,7 @@ func (test *DifficultyTest) Run(config *params.ChainConfig) error { UncleHash: test.UncleHash, } - actual := ethash.CalcDifficulty(config, test.CurrentTimestamp.Uint64(), parent) + actual := ethash.CalcDifficulty(config, test.CurrentTimestamp, parent) exp := test.CurrentDifficulty if actual.Cmp(exp) != 0 { diff --git a/tests/gen_btheader.go b/tests/gen_btheader.go index abe99159cc..642d2dde75 100644 --- a/tests/gen_btheader.go +++ b/tests/gen_btheader.go @@ -32,7 +32,7 @@ func (b btHeader) MarshalJSON() ([]byte, error) { Difficulty *math.HexOrDecimal256 GasLimit math.HexOrDecimal64 GasUsed math.HexOrDecimal64 - Timestamp *math.HexOrDecimal256 + Timestamp math.HexOrDecimal64 BaseFee *math.HexOrDecimal256 } var enc btHeader @@ -51,7 +51,7 @@ func (b btHeader) MarshalJSON() ([]byte, error) { enc.Difficulty = (*math.HexOrDecimal256)(b.Difficulty) enc.GasLimit = math.HexOrDecimal64(b.GasLimit) enc.GasUsed = math.HexOrDecimal64(b.GasUsed) - enc.Timestamp = (*math.HexOrDecimal256)(b.Timestamp) + enc.Timestamp = math.HexOrDecimal64(b.Timestamp) enc.BaseFee = (*math.HexOrDecimal256)(b.BaseFee) return json.Marshal(&enc) } @@ -74,7 +74,7 @@ func (b *btHeader) UnmarshalJSON(input []byte) error { Difficulty *math.HexOrDecimal256 GasLimit *math.HexOrDecimal64 GasUsed *math.HexOrDecimal64 - Timestamp *math.HexOrDecimal256 + Timestamp *math.HexOrDecimal64 BaseFee *math.HexOrDecimal256 } var dec btHeader @@ -127,7 +127,7 @@ func (b *btHeader) UnmarshalJSON(input []byte) error { b.GasUsed = uint64(*dec.GasUsed) } if dec.Timestamp != nil { - b.Timestamp = (*big.Int)(dec.Timestamp) + b.Timestamp = uint64(*dec.Timestamp) } if dec.BaseFee != nil { b.BaseFee = (*big.Int)(dec.BaseFee) diff --git a/tests/gen_difficultytest.go b/tests/gen_difficultytest.go index 67ce089e3c..83e6b8a1cb 100644 --- a/tests/gen_difficultytest.go +++ b/tests/gen_difficultytest.go @@ -15,18 +15,18 @@ var _ = (*difficultyTestMarshaling)(nil) // MarshalJSON marshals as JSON. func (d DifficultyTest) MarshalJSON() ([]byte, error) { type DifficultyTest struct { - ParentTimestamp *math.HexOrDecimal256 `json:"parentTimestamp"` + ParentTimestamp math.HexOrDecimal64 `json:"parentTimestamp"` ParentDifficulty *math.HexOrDecimal256 `json:"parentDifficulty"` UncleHash common.Hash `json:"parentUncles"` - CurrentTimestamp *math.HexOrDecimal256 `json:"currentTimestamp"` + CurrentTimestamp math.HexOrDecimal64 `json:"currentTimestamp"` CurrentBlockNumber math.HexOrDecimal64 `json:"currentBlockNumber"` CurrentDifficulty *math.HexOrDecimal256 `json:"currentDifficulty"` } var enc DifficultyTest - enc.ParentTimestamp = (*math.HexOrDecimal256)(d.ParentTimestamp) + enc.ParentTimestamp = math.HexOrDecimal64(d.ParentTimestamp) enc.ParentDifficulty = (*math.HexOrDecimal256)(d.ParentDifficulty) enc.UncleHash = d.UncleHash - enc.CurrentTimestamp = (*math.HexOrDecimal256)(d.CurrentTimestamp) + enc.CurrentTimestamp = math.HexOrDecimal64(d.CurrentTimestamp) enc.CurrentBlockNumber = math.HexOrDecimal64(d.CurrentBlockNumber) enc.CurrentDifficulty = (*math.HexOrDecimal256)(d.CurrentDifficulty) return json.Marshal(&enc) @@ -35,10 +35,10 @@ func (d DifficultyTest) MarshalJSON() ([]byte, error) { // UnmarshalJSON unmarshals from JSON. func (d *DifficultyTest) UnmarshalJSON(input []byte) error { type DifficultyTest struct { - ParentTimestamp *math.HexOrDecimal256 `json:"parentTimestamp"` + ParentTimestamp *math.HexOrDecimal64 `json:"parentTimestamp"` ParentDifficulty *math.HexOrDecimal256 `json:"parentDifficulty"` UncleHash *common.Hash `json:"parentUncles"` - CurrentTimestamp *math.HexOrDecimal256 `json:"currentTimestamp"` + CurrentTimestamp *math.HexOrDecimal64 `json:"currentTimestamp"` CurrentBlockNumber *math.HexOrDecimal64 `json:"currentBlockNumber"` CurrentDifficulty *math.HexOrDecimal256 `json:"currentDifficulty"` } @@ -47,7 +47,7 @@ func (d *DifficultyTest) UnmarshalJSON(input []byte) error { return err } if dec.ParentTimestamp != nil { - d.ParentTimestamp = (*big.Int)(dec.ParentTimestamp) + d.ParentTimestamp = uint64(*dec.ParentTimestamp) } if dec.ParentDifficulty != nil { d.ParentDifficulty = (*big.Int)(dec.ParentDifficulty) @@ -56,7 +56,7 @@ func (d *DifficultyTest) UnmarshalJSON(input []byte) error { d.UncleHash = *dec.UncleHash } if dec.CurrentTimestamp != nil { - d.CurrentTimestamp = (*big.Int)(dec.CurrentTimestamp) + d.CurrentTimestamp = uint64(*dec.CurrentTimestamp) } if dec.CurrentBlockNumber != nil { d.CurrentBlockNumber = uint64(*dec.CurrentBlockNumber)