1// Copyright 2018 The go-ethereum Authors 2// This file is part of the go-ethereum library. 3// 4// The go-ethereum library is free software: you can redistribute it and/or modify 5// it under the terms of the GNU Lesser General Public License as published by 6// the Free Software Foundation, either version 3 of the License, or 7// (at your option) any later version. 8// 9// The go-ethereum library is distributed in the hope that it will be useful, 10// but WITHOUT ANY WARRANTY; without even the implied warranty of 11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12// GNU Lesser General Public License for more details. 13// 14// You should have received a copy of the GNU Lesser General Public License 15// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17package mru 18 19import ( 20 "encoding/binary" 21 "time" 22) 23 24// TimestampProvider sets the time source of the mru package 25var TimestampProvider timestampProvider = NewDefaultTimestampProvider() 26 27// Encodes a point in time as a Unix epoch 28type Timestamp struct { 29 Time uint64 // Unix epoch timestamp, in seconds 30} 31 32// 8 bytes uint64 Time 33const timestampLength = 8 34 35// timestampProvider interface describes a source of timestamp information 36type timestampProvider interface { 37 Now() Timestamp // returns the current timestamp information 38} 39 40// binaryGet populates the timestamp structure from the given byte slice 41func (t *Timestamp) binaryGet(data []byte) error { 42 if len(data) != timestampLength { 43 return NewError(ErrCorruptData, "timestamp data has the wrong size") 44 } 45 t.Time = binary.LittleEndian.Uint64(data[:8]) 46 return nil 47} 48 49// binaryPut Serializes a Timestamp to a byte slice 50func (t *Timestamp) binaryPut(data []byte) error { 51 if len(data) != timestampLength { 52 return NewError(ErrCorruptData, "timestamp data has the wrong size") 53 } 54 binary.LittleEndian.PutUint64(data, t.Time) 55 return nil 56} 57 58type DefaultTimestampProvider struct { 59} 60 61// NewDefaultTimestampProvider creates a system clock based timestamp provider 62func NewDefaultTimestampProvider() *DefaultTimestampProvider { 63 return &DefaultTimestampProvider{} 64} 65 66// Now returns the current time according to this provider 67func (dtp *DefaultTimestampProvider) Now() Timestamp { 68 return Timestamp{ 69 Time: uint64(time.Now().Unix()), 70 } 71} 72