Skip to content

Commit

Permalink
EVM-440-Using-UTC-time (#1304)
Browse files Browse the repository at this point in the history
* Add new lint rule

* Custom time package

* Use timeutils package

* Expand rule

* Fix rule

* Remove the timeutils package
  • Loading branch information
goran-ethernal committed Mar 21, 2023
1 parent f427c11 commit c615d0c
Show file tree
Hide file tree
Showing 20 changed files with 112 additions and 38 deletions.
2 changes: 1 addition & 1 deletion command/regenesis/test_on_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func HistoryTestCmd() *cobra.Command {
}

tmpStorage := itrie.NewKV(tmpDB)
tt := time.Now()
tt := time.Now().UTC()

err = itrie.CopyTrie(header.StateRoot.Bytes(), itrie.NewKV(trieDB), tmpStorage, []byte{}, false)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion consensus/dev/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ func (d *Dev) writeNewBlock(parent *types.Header) error {
ParentHash: parent.Hash,
Number: num + 1,
GasLimit: parent.GasLimit, // Inherit from parent for now, will need to adjust dynamically later.
Timestamp: uint64(time.Now().Unix()),
Timestamp: uint64(time.Now().UTC().Unix()),
}

// calculate gas limit based on parent header
Expand Down
2 changes: 1 addition & 1 deletion consensus/ibft/consensus_backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func (i *backendIBFT) buildBlock(parent *types.Header) (*types.Block, error) {
}

// Set the header timestamp
potentialTimestamp := i.calcHeaderTimestamp(parent.Timestamp, time.Now())
potentialTimestamp := i.calcHeaderTimestamp(parent.Timestamp, time.Now().UTC())
header.Timestamp = uint64(potentialTimestamp.Unix())

parentCommittedSeals, err := i.extractParentCommittedSeals(parent)
Expand Down
4 changes: 2 additions & 2 deletions consensus/ibft/consensus_backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func TestIBFTBackend_CalculateHeaderTimestamp(t *testing.T) {
t.Parallel()

// Reference time
now := time.Unix(time.Now().Unix(), 0) // Round down
now := time.Unix(time.Now().UTC().Unix(), 0) // Round down

testTable := []struct {
name string
Expand Down Expand Up @@ -66,7 +66,7 @@ func TestIBFTBackend_RoundUpTime(t *testing.T) {
t.Parallel()

// Reference time
now := time.Now()
now := time.Now().UTC()

calcExpected := func(time int64, multiple int64) int64 {
if time%multiple == 0 {
Expand Down
4 changes: 2 additions & 2 deletions consensus/polybft/block_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ func (b *BlockBuilder) Reset() error {
parentTime := time.Unix(int64(b.params.Parent.Timestamp), 0)
headerTime := parentTime.Add(b.params.BlockTime)

if headerTime.Before(time.Now()) {
headerTime = time.Now()
if headerTime.Before(time.Now().UTC()) {
headerTime = time.Now().UTC()
}

b.header = &types.Header{
Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/consensus_runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1126,7 +1126,7 @@ func createTestBitmaps(t *testing.T, validators AccountSet, numberOfBlocks uint6

bitmaps := make(map[uint64]bitmap.Bitmap, numberOfBlocks)

rand.Seed(time.Now().Unix())
rand.Seed(time.Now().UTC().Unix())

for i := numberOfBlocks; i > 1; i-- {
bitmap := bitmap.Bitmap{}
Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/fsm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,7 @@ func TestFSM_Validate_TimestampOlder(t *testing.T) {
parent := &types.Header{
Number: parentBlockNumber,
ExtraData: createTestExtra(validators.getPublicIdentities(), AccountSet{}, 4, 3, 3),
Timestamp: uint64(time.Now().Unix()),
Timestamp: uint64(time.Now().UTC().Unix()),
}
parent.ComputeHash()

Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func getEpochNumber(t *testing.T, blockNumber, epochSize uint64) uint64 {
func newTestState(t *testing.T) *State {
t.Helper()

dir := fmt.Sprintf("/tmp/consensus-temp_%v", time.Now().Format(time.RFC3339Nano))
dir := fmt.Sprintf("/tmp/consensus-temp_%v", time.Now().UTC().Format(time.RFC3339Nano))
err := os.Mkdir(dir, 0775)

if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/polybft.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ func (p *Polybft) startConsensusProtocol() {
sequenceCh, stopSequence = p.ibft.runSequence(latestHeader.Number + 1)
}

now := time.Now()
now := time.Now().UTC()

select {
case <-syncerBlockCh:
Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/polybft_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func TestPolybft_VerifyHeader(t *testing.T) {

parentHeader := &types.Header{
Number: polyBftConfig.EpochSize,
Timestamp: uint64(time.Now().UnixMilli()),
Timestamp: uint64(time.Now().UTC().UnixMilli()),
}
parentCommitment := updateHeaderExtra(parentHeader, parentDelta, nil, &CheckpointData{EpochNumber: 1}, accountSetParent)

Expand Down
2 changes: 1 addition & 1 deletion consensus/polybft/signer/signature_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func Test_VerifySignature_NegativeCases(t *testing.T) {
t.Parallel()

// Get a random integer between 1 and 1000
mRand.Seed(time.Now().UnixNano())
mRand.Seed(time.Now().UTC().UnixNano())
messageSize := mRand.Intn(1000) + 1

validTestMsg := testGenRandomBytes(t, messageSize)
Expand Down
2 changes: 1 addition & 1 deletion crypto/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ func TestPrivateKeyRead(t *testing.T) {
}

func TestPrivateKeyGeneration(t *testing.T) {
tempFile := "./privateKeyTesting-" + strconv.FormatInt(time.Now().Unix(), 10) + ".key"
tempFile := "./privateKeyTesting-" + strconv.FormatInt(time.Now().UTC().Unix(), 10) + ".key"

t.Cleanup(func() {
_ = os.Remove(tempFile)
Expand Down
2 changes: 1 addition & 1 deletion e2e-polybft/framework/test-cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ const (
var startTime int64

func init() {
startTime = time.Now().UnixMilli()
startTime = time.Now().UTC().UnixMilli()
}

func resolveBinary() string {
Expand Down
2 changes: 1 addition & 1 deletion e2e/framework/ibft.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ type IBFTServerConfigCallback func(index int, config *TestServerConfig)
var startTime int64

func init() {
startTime = time.Now().UnixMilli()
startTime = time.Now().UTC().UnixMilli()
}

func NewIBFTServersManager(
Expand Down
30 changes: 23 additions & 7 deletions gorules/rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,31 @@ import (
)

func OsFilePermissionRule(m dsl.Matcher) {
m.Match(`os.$name($file, $number, 0777)`).Report("os.$name called with file mode 0777")
m.Match(`os.$name($file, 0777)`).Report("os.$name called with file mode 0777")
m.Match(`os.$name(0777)`).Report("os.$name called with file mode 0777")

m.Match(`os.$name($file, $number, os.ModePerm)`).Report("os.$name called with file mode os.ModePerm (0777)")
m.Match(`os.$name($file, os.ModePerm)`).Report("os.$name called with file mode os.ModePerm (0777)")
m.Match(`os.$name(os.ModePerm)`).Report("os.$name called with file mode os.ModePerm (0777)")
m.Match(`os.$name($file, $number, 0777)`,
`os.$name($file, 0777)`,
`os.$name(0777)`,
`os.$name($file, $number, os.ModePerm)`,
`os.$name($file, os.ModePerm)`,
`os.$name(os.ModePerm)`,
).Report("os.$name called with file mode 0777 (ModePerm)")
}

func ForbidPanicsRule(m dsl.Matcher) {
m.Match(`panic($_)`).Report("panics should not be manually used")
}

func NoUseOfTimeNowWithoutUTCRule(m dsl.Matcher) {
m.Match(`$_ = time.Now()`,
`$_ := time.Now()`,
`$_.$_ = time.Now()`).
Suggest("time.Now().UTC()").
Report(`use UTC time when calling time.Now`)

m.Match(`time.Now().$f()`,
`time.Now().$f($_)`,
`time.Now().$f($_, $_)`,
`time.Now().$f($_, $_, $_)`).
Where(!m["f"].Text.Matches("UTC")).
Suggest("time.Now().UTC()").
Report(`use UTC time when calling time.Now`)
}
80 changes: 69 additions & 11 deletions gorules/testdata/rules_test_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,59 @@ import (
"errors"
"fmt"
"os"
"time"
)

type testLintStruct struct {
testTime time.Time
}

func testLintError() {
err := errors.New("test")
testStruct := &testLintStruct{}
var timeNow time.Time

os.Mkdir("test", 0777) // want `OsFilePermissionRule: os.Mkdir called with file mode 0777`
os.Mkdir("test", os.ModePerm) // want `OsFilePermissionRule: os.Mkdir called with file mode 0777`
os.MkdirAll("test", 0777) // want `OsFilePermissionRule: os.MkdirAll called with file mode 0777`
os.MkdirAll("test", os.ModePerm) // want `OsFilePermissionRule: os.MkdirAll called with file mode 0777`
os.Chmod("test", 0777) // want `OsFilePermissionRule: os.Chmod called with file mode 0777`
os.Chmod("test", os.ModePerm) // want `OsFilePermissionRule: os.Chmod called with file mode 0777`
os.OpenFile("test", 0, 0777) // want `OsFilePermissionRule: os.OpenFile called with file mode 0777`
os.OpenFile("test", 0, os.ModePerm) // want `OsFilePermissionRule: os.OpenFile called with file mode 0777`
panic("test") // want `ForbidPanicsRule: panics should not be manually used`
panic(fmt.Sprintf("test error")) // want `ForbidPanicsRule: panics should not be manually used`
panic(err) // want `ForbidPanicsRule: panics should not be manually used`
testStruct.testTime = time.Now() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
timeNow = time.Now() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
v := time.Now() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Unix() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().UnixMicro() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().UnixMilli() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().UnixNano() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Add(time.Hour) // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().AddDate(1, 1, 1) // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().After(time.Date(1, 1, 1, 1, 1, 1, 1, time.Local)) // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().AppendFormat([]byte{0, 1}, "dd.mm.yyyy") // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Before(time.Date(1, 1, 1, 1, 1, 1, 1, time.Local)) // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Clock() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Date() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Day() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Equal(time.Date(1, 1, 1, 1, 1, 1, 1, time.Local)) // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Hour() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Minute() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Hour() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Year() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`
time.Now().Add(time.Hour).Unix() // want `NoUseOfTimeNowWithoutUTCRule: use UTC time when calling time.Now`

os.Mkdir("test", 0777) // want `OsFilePermissionRule: os.Mkdir called with file mode`
os.Mkdir("test", os.ModePerm) // want `OsFilePermissionRule: os.Mkdir called with file mode`
os.MkdirAll("test", 0777) // want `OsFilePermissionRule: os.MkdirAll called with file mode`
os.MkdirAll("test", os.ModePerm) // want `OsFilePermissionRule: os.MkdirAll called with file mode`
os.Chmod("test", 0777) // want `OsFilePermissionRule: os.Chmod called with file mode`
os.Chmod("test", os.ModePerm) // want `OsFilePermissionRule: os.Chmod called with file mode`
os.OpenFile("test", 0, 0777) // want `OsFilePermissionRule: os.OpenFile called with file mode`
os.OpenFile("test", 0, os.ModePerm) // want `OsFilePermissionRule: os.OpenFile called with file mode`
panic("test") // want `ForbidPanicsRule: panics should not be manually used`
panic(fmt.Sprintf("test error")) // want `ForbidPanicsRule: panics should not be manually used`
panic(err) // want `ForbidPanicsRule: panics should not be manually used`
v.Day()
timeNow.Day()
}

func testNoLintError() {
testStruct := &testLintStruct{}
var timeNow time.Time

os.Mkdir("test", 67108864)
os.Mkdir("test", os.ModeDevice)
os.MkdirAll("test", 67108864)
Expand All @@ -31,4 +65,28 @@ func testNoLintError() {
os.Chmod("test", os.ModeDevice)
os.OpenFile("test", 0, 67108864)
os.OpenFile("test", 0, os.ModeDevice)
testStruct.testTime = time.Now().UTC()
timeNow = time.Now().UTC()
v := time.Now().UTC()
time.Now().UTC().Unix()
time.Now().UTC().UnixMicro()
time.Now().UTC().UnixMilli()
time.Now().UTC().UnixNano()
time.Now().UTC().Add(time.Hour)
time.Now().UTC().AddDate(1, 1, 1)
time.Now().UTC().After(time.Date(1, 1, 1, 1, 1, 1, 1, time.Local))
time.Now().UTC().AppendFormat([]byte{0, 1}, "dd.mm.yyyy")
time.Now().UTC().Before(time.Date(1, 1, 1, 1, 1, 1, 1, time.Local))
time.Now().UTC().Clock()
time.Now().UTC().Date()
time.Now().UTC().Day()
time.Now().UTC().Equal(time.Date(1, 1, 1, 1, 1, 1, 1, time.Local))
time.Now().UTC().Hour()
time.Now().UTC().Minute()
time.Now().UTC().Hour()
time.Now().UTC().Year()
time.Now().UTC().Add(time.Hour).Unix()

v.Day()
timeNow.Day()
}
2 changes: 1 addition & 1 deletion jsonrpc/filter_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -570,7 +570,7 @@ func (f *FilterManager) refreshFilterTimeout(filter *filterBase) {

// addFilterTimeout set timeout and add to heap
func (f *FilterManager) addFilterTimeout(filter *filterBase) {
filter.expiresAt = time.Now().Add(f.timeout)
filter.expiresAt = time.Now().UTC().Add(f.timeout)
f.timeouts.addFilter(filter)
f.emitSignalToUpdateCh()
}
Expand Down
2 changes: 1 addition & 1 deletion jsonrpc/filter_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,7 @@ func TestHeadStream_Concurrent(t *testing.T) {

// Write co-routine with jitter
go func() {
seed := time.Now().UnixNano()
seed := time.Now().UTC().UnixNano()
t.Logf("Using seed %d", seed)

z := rand.NewZipf(rand.New(rand.NewSource(seed)), 1.5, 1.5, 50)
Expand Down
2 changes: 1 addition & 1 deletion network/gossip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func WaitForSubscribers(ctx context.Context, srv *Server, topic string, expected

func TestSimpleGossip(t *testing.T) {
numServers := 10
sentMessage := fmt.Sprintf("%d", time.Now().Unix())
sentMessage := fmt.Sprintf("%d", time.Now().UTC().Unix())
servers, createErr := createServers(numServers, nil)

if createErr != nil {
Expand Down
2 changes: 1 addition & 1 deletion txpool/event_subscription_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func shuffleTxPoolEvents(
}

// Shuffle the events
mathRand.Seed(time.Now().UnixNano())
mathRand.Seed(time.Now().UTC().UnixNano())
mathRand.Shuffle(len(events), func(i, j int) {
events[i], events[j] = events[j], events[i]
})
Expand Down

0 comments on commit c615d0c

Please sign in to comment.