diff --git a/cmd/devp2p/internal/ethtest/suite.go b/cmd/devp2p/internal/ethtest/suite.go index 416df8067c..e8c6733dce 100644 --- a/cmd/devp2p/internal/ethtest/suite.go +++ b/cmd/devp2p/internal/ethtest/suite.go @@ -377,7 +377,7 @@ func (s *Suite) TestGetBlockBodies(t *utesting.T) { // randBuf makes a random buffer size kilobytes large. func randBuf(size int) []byte { - buf := make([]byte, size*common.Kilobytes) + buf := make([]byte, size*common.Kilobyte) rand.Read(buf) return buf } diff --git a/cmd/evm/eofparse.go b/cmd/evm/eofparse.go index 2897802b7b..b20dd5a4f8 100644 --- a/cmd/evm/eofparse.go +++ b/cmd/evm/eofparse.go @@ -106,7 +106,7 @@ func eofParseAction(ctx *cli.Context) error { } // If neither are passed in, read input from stdin. scanner := bufio.NewScanner(os.Stdin) - scanner.Buffer(make([]byte, common.Megabytes), 10*common.Megabytes) + scanner.Buffer(make([]byte, common.Megabyte), 10*common.Megabyte) for scanner.Scan() { l := strings.TrimSpace(scanner.Text()) if strings.HasPrefix(l, "#") || l == "" { @@ -198,7 +198,7 @@ func eofDumpAction(ctx *cli.Context) error { } // Otherwise read from stdin scanner := bufio.NewScanner(os.Stdin) - scanner.Buffer(make([]byte, common.Megabytes), 10*common.Megabytes) + scanner.Buffer(make([]byte, common.Megabyte), 10*common.Megabyte) for scanner.Scan() { l := strings.TrimSpace(scanner.Text()) if strings.HasPrefix(l, "#") || l == "" { diff --git a/cmd/evm/internal/t8ntool/tx_iterator.go b/cmd/evm/internal/t8ntool/tx_iterator.go index f572d62a6e..9f7c463b96 100644 --- a/cmd/evm/internal/t8ntool/tx_iterator.go +++ b/cmd/evm/internal/t8ntool/tx_iterator.go @@ -176,7 +176,7 @@ type rlpTxIterator struct { } func newRlpTxIterator(rlpData []byte) txIterator { - in := rlp.NewStream(bytes.NewBuffer(rlpData), common.Megabytes) + in := rlp.NewStream(bytes.NewBuffer(rlpData), common.Megabyte) in.List() return &rlpTxIterator{in} } diff --git a/cmd/geth/chaincmd.go b/cmd/geth/chaincmd.go index c479d89b6f..52e9f7f63f 100644 --- a/cmd/geth/chaincmd.go +++ b/cmd/geth/chaincmd.go @@ -351,8 +351,8 @@ func importChain(ctx *cli.Context) error { mem := new(runtime.MemStats) runtime.ReadMemStats(mem) - fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/common.Megabytes, float64(peakMemAlloc.Load())/common.Megabytes) - fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/common.Megabytes, float64(peakMemSys.Load())/common.Megabytes) + fmt.Printf("Object memory: %.3f MB current, %.3f MB peak\n", float64(mem.Alloc)/common.Megabyte, float64(peakMemAlloc.Load())/common.Megabyte) + fmt.Printf("System memory: %.3f MB current, %.3f MB peak\n", float64(mem.Sys)/common.Megabyte, float64(peakMemSys.Load())/common.Megabyte) fmt.Printf("Allocations: %.3f million\n", float64(mem.Mallocs)/1000000) fmt.Printf("GC pause: %v\n\n", time.Duration(mem.PauseTotalNs)) diff --git a/cmd/utils/cmd.go b/cmd/utils/cmd.go index 1148aad545..bb086b27e0 100644 --- a/cmd/utils/cmd.go +++ b/cmd/utils/cmd.go @@ -94,7 +94,7 @@ func StartNode(ctx *cli.Context, stack *node.Node, isConsole bool) { minFreeDiskSpace = 2 * ctx.Int(CacheFlag.Name) * ctx.Int(CacheGCFlag.Name) / 100 } if minFreeDiskSpace > 0 { - go monitorFreeDiskSpace(sigc, stack.InstanceDir(), uint64(minFreeDiskSpace)*common.Megabytes) + go monitorFreeDiskSpace(sigc, stack.InstanceDir(), uint64(minFreeDiskSpace)*common.Megabyte) } shutdown := func() { @@ -523,7 +523,7 @@ func ImportPreimages(db ethdb.Database, fn string) error { } // Accumulate the preimages and flush when enough ws gathered preimages[crypto.Keccak256Hash(blob)] = common.CopyBytes(blob) - if len(preimages) > common.Kilobytes { + if len(preimages) > common.Kilobyte { rawdb.WritePreimages(db, preimages) preimages = make(map[common.Hash][]byte) } diff --git a/cmd/utils/flags.go b/cmd/utils/flags.go index 05639a880f..a5a2d19fea 100644 --- a/cmd/utils/flags.go +++ b/cmd/utils/flags.go @@ -1587,11 +1587,11 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { // Cap the cache allowance and tune the garbage collector mem, err := gopsutil.VirtualMemory() if err == nil { - if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*common.Gigabytes { - log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/common.Megabytes, "addressable", 2*common.Kilobytes) - mem.Total = 2 * common.Gigabytes + if 32<<(^uintptr(0)>>63) == 32 && mem.Total > 2*common.Gigabyte { + log.Warn("Lowering memory allowance on 32bit arch", "available", mem.Total/common.Megabyte, "addressable", 2*common.Kilobyte) + mem.Total = 2 * common.Gigabyte } - allowance := int(mem.Total / common.Megabytes / 3) + allowance := int(mem.Total / common.Megabyte / 3) if cache := ctx.Int(CacheFlag.Name); cache > allowance { log.Warn("Sanitizing cache to Go's GC limits", "provided", cache, "updated", allowance) ctx.Set(CacheFlag.Name, strconv.Itoa(allowance)) @@ -1826,7 +1826,7 @@ func SetEthConfig(ctx *cli.Context, stack *node.Node, cfg *ethconfig.Config) { if rawdb.ReadCanonicalHash(chaindb, 0) != (common.Hash{}) { cfg.Genesis = nil // fallback to db content - //validate genesis has PoS enabled in block 0 + // validate genesis has PoS enabled in block 0 genesis, err := core.ReadGenesis(chaindb) if err != nil { Fatalf("Could not read genesis from database: %v", err) diff --git a/common/bytes.go b/common/bytes.go index c1d51a75bc..6faf49db33 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -25,10 +25,10 @@ import ( ) const ( - Kilobytes = 1024 - Megabytes = 1024 * Kilobytes - Gigabytes = 1024 * Megabytes - Terabytes = 1024 * Gigabytes + Kilobyte = 1024 + Megabyte = 1024 * Kilobyte + Gigabyte = 1024 * Megabyte + Terabyte = 1024 * Gigabyte ) // FromHex returns the bytes represented by the hexadecimal string s. diff --git a/common/size.go b/common/size.go index d713ab09b1..ea8239f429 100644 --- a/common/size.go +++ b/common/size.go @@ -26,14 +26,14 @@ type StorageSize float64 // String implements the stringer interface. func (s StorageSize) String() string { - if s > Terabytes { - return fmt.Sprintf("%.2f TiB", s/Terabytes) - } else if s > Gigabytes { - return fmt.Sprintf("%.2f GiB", s/Gigabytes) - } else if s > Megabytes { - return fmt.Sprintf("%.2f MiB", s/Megabytes) - } else if s > Kilobytes { - return fmt.Sprintf("%.2f KiB", s/Kilobytes) + if s > Terabyte { + return fmt.Sprintf("%.2f TiB", s/Terabyte) + } else if s > Gigabyte { + return fmt.Sprintf("%.2f GiB", s/Gigabyte) + } else if s > Megabyte { + return fmt.Sprintf("%.2f MiB", s/Megabyte) + } else if s > Kilobyte { + return fmt.Sprintf("%.2f KiB", s/Kilobyte) } else { return fmt.Sprintf("%.2f B", s) } @@ -42,14 +42,14 @@ func (s StorageSize) String() string { // TerminalString implements log.TerminalStringer, formatting a string for console // output during logging. func (s StorageSize) TerminalString() string { - if s > Terabytes { - return fmt.Sprintf("%.2fTiB", s/Terabytes) - } else if s > Gigabytes { - return fmt.Sprintf("%.2fGiB", s/Gigabytes) - } else if s > Megabytes { - return fmt.Sprintf("%.2fMiB", s/Megabytes) - } else if s > Kilobytes { - return fmt.Sprintf("%.2fKiB", s/Kilobytes) + if s > Terabyte { + return fmt.Sprintf("%.2fTiB", s/Terabyte) + } else if s > Gigabyte { + return fmt.Sprintf("%.2fGiB", s/Gigabyte) + } else if s > Megabyte { + return fmt.Sprintf("%.2fMiB", s/Megabyte) + } else if s > Kilobyte { + return fmt.Sprintf("%.2fKiB", s/Kilobyte) } else { return fmt.Sprintf("%.2fB", s) } diff --git a/core/blockchain.go b/core/blockchain.go index 8d756cb360..a17ed68280 100644 --- a/core/blockchain.go +++ b/core/blockchain.go @@ -170,14 +170,14 @@ func (c *CacheConfig) triedbConfig(isVerkle bool) *triedb.Config { } if c.StateScheme == rawdb.HashScheme { config.HashDB = &hashdb.Config{ - CleanCacheSize: c.TrieCleanLimit * common.Megabytes, + CleanCacheSize: c.TrieCleanLimit * common.Megabyte, } } if c.StateScheme == rawdb.PathScheme { config.PathDB = &pathdb.Config{ StateHistory: c.StateHistory, - CleanCacheSize: c.TrieCleanLimit * common.Megabytes, - WriteBufferSize: c.TrieDirtyLimit * common.Megabytes, + CleanCacheSize: c.TrieCleanLimit * common.Megabyte, + WriteBufferSize: c.TrieDirtyLimit * common.Megabyte, } } return config @@ -1518,9 +1518,9 @@ func (bc *BlockChain) writeBlockWithState(block *types.Block, receipts []*types. // If we exceeded our memory allowance, flush matured singleton nodes to disk var ( _, nodes, imgs = bc.triedb.Size() // all memory is contained within the nodes return for hashdb - limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * common.Megabytes + limit = common.StorageSize(bc.cacheConfig.TrieDirtyLimit) * common.Megabyte ) - if nodes > limit || imgs > 4*common.Megabytes { + if nodes > limit || imgs > 4*common.Megabyte { bc.triedb.Cap(limit - ethdb.IdealBatchSize) } // Find the next state trie we need to commit @@ -2100,7 +2100,7 @@ func (bc *BlockChain) insertSideChain(block *types.Block, it *insertIterator, ma // If memory use grew too large, import and continue. Sadly we need to discard // all raised events and logs from notifications since we're too heavy on the // memory here. - if len(blocks) >= 2048 || memory > 64*common.Megabytes { + if len(blocks) >= 2048 || memory > 64*common.Megabyte { log.Info("Importing heavy sidechain segment", "blocks", len(blocks), "start", blocks[0].NumberU64(), "end", block.NumberU64()) if _, _, err := bc.insertChain(blocks, true, false); err != nil { return nil, 0, err diff --git a/core/rawdb/accessors_chain.go b/core/rawdb/accessors_chain.go index d68441583a..fd04361a85 100644 --- a/core/rawdb/accessors_chain.go +++ b/core/rawdb/accessors_chain.go @@ -324,7 +324,7 @@ func ReadHeaderRange(db ethdb.Reader, number uint64, count uint64) []rlp.RawValu return rlpHeaders } // read remaining from ancients, cap at 2M - data, err := db.AncientRange(ChainFreezerHeaderTable, i+1-count, count, 2*common.Megabytes) + data, err := db.AncientRange(ChainFreezerHeaderTable, i+1-count, count, 2*common.Megabyte) if err != nil { log.Error("Failed to read headers from freezer", "err", err) return rlpHeaders diff --git a/core/rawdb/freezer_batch.go b/core/rawdb/freezer_batch.go index 1cfe047dc5..23167f8665 100644 --- a/core/rawdb/freezer_batch.go +++ b/core/rawdb/freezer_batch.go @@ -28,7 +28,7 @@ import ( // This is the maximum amount of data that will be buffered in memory // for a single freezer table batch. -const freezerBatchBufferLimit = 2 * common.Megabytes +const freezerBatchBufferLimit = 2 * common.Megabyte // freezerBatch is a write operation of multiple items on a freezer. type freezerBatch struct { diff --git a/core/state/database.go b/core/state/database.go index a4fcac2e24..24c8962ee9 100644 --- a/core/state/database.go +++ b/core/state/database.go @@ -37,7 +37,7 @@ const ( codeSizeCacheSize = 100000 // Cache size granted for caching clean code. - codeCacheSize = 64 * common.Megabytes + codeCacheSize = 64 * common.Megabyte // Number of address->curve point associations to keep. pointCacheSize = 4096 diff --git a/core/state/pruner/bloom.go b/core/state/pruner/bloom.go index 9dcc32d70b..0595678d87 100644 --- a/core/state/pruner/bloom.go +++ b/core/state/pruner/bloom.go @@ -56,7 +56,7 @@ type stateBloom struct { // to the https://hur.st/bloomfilter/?n=600000000&p=&m=2048MB&k=4, the parameters // are picked so that the false-positive rate for mainnet is low enough. func newStateBloomWithSize(size uint64) (*stateBloom, error) { - bloom, err := bloomfilter.New(size*common.Megabytes*8, 4) + bloom, err := bloomfilter.New(size*common.Megabyte*8, 4) if err != nil { return nil, err } @@ -83,7 +83,7 @@ func (bloom *stateBloom) Commit(filename, tempname string) error { return err } // Ensure the file is synced to disk - f, err := os.OpenFile(tempname, os.O_RDWR, 0666) + f, err := os.OpenFile(tempname, os.O_RDWR, 0o666) if err != nil { return err } diff --git a/core/state/snapshot/difflayer.go b/core/state/snapshot/difflayer.go index eb67272292..d0b0543041 100644 --- a/core/state/snapshot/difflayer.go +++ b/core/state/snapshot/difflayer.go @@ -41,7 +41,7 @@ var ( // Note, bumping this up might drastically increase the size of the bloom // filters that's stored in every diff layer. Don't do that without fully // understanding all the implications. - aggregatorMemoryLimit = uint64(4 * common.Megabytes) + aggregatorMemoryLimit = uint64(4 * common.Megabyte) // aggregatorItemLimit is an approximate number of items that will end up // in the aggregator layer before it's flushed out to disk. A plain account diff --git a/core/state/snapshot/generate.go b/core/state/snapshot/generate.go index 7554781f28..e20ffa49c7 100644 --- a/core/state/snapshot/generate.go +++ b/core/state/snapshot/generate.go @@ -71,7 +71,7 @@ func generateSnapshot(diskdb ethdb.KeyValueStore, triedb *triedb.Database, cache diskdb: diskdb, triedb: triedb, root: root, - cache: fastcache.New(cache * common.Megabytes), + cache: fastcache.New(cache * common.Megabyte), genMarker: genMarker, genPending: make(chan struct{}), genAbort: make(chan chan *generatorStats), @@ -284,7 +284,8 @@ func (dl *diskLayer) proveRange(ctx *generatorContext, trieId *trie.ID, prefix [ diskMore: diskMore, trieMore: cont, proofErr: err, - tr: tr}, + tr: tr, + }, nil } @@ -534,7 +535,7 @@ func generateStorages(ctx *generatorContext, dl *diskLayer, stateRoot common.Has return nil } // Loop for re-generating the missing storage slots. - var origin = common.CopyBytes(storeMarker) + origin := common.CopyBytes(storeMarker) for { id := trie.StorageTrieID(stateRoot, account, storageRoot) exhausted, last, err := dl.generateRange(ctx, id, append(rawdb.SnapshotStoragePrefix, account.Bytes()...), snapStorage, origin, storageCheckRange, onStorage, nil) diff --git a/core/state/snapshot/journal.go b/core/state/snapshot/journal.go index ceebc01010..7f2bfeb14c 100644 --- a/core/state/snapshot/journal.go +++ b/core/state/snapshot/journal.go @@ -139,7 +139,7 @@ func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *triedb.Database, root comm base := &diskLayer{ diskdb: diskdb, triedb: triedb, - cache: fastcache.New(cache * common.Megabytes), + cache: fastcache.New(cache * common.Megabyte), root: baseRoot, } snapshot, generator, err := loadAndParseJournal(diskdb, base) diff --git a/core/state/snapshot/snapshot.go b/core/state/snapshot/snapshot.go index ceaef5d37e..3fc54b2a7b 100644 --- a/core/state/snapshot/snapshot.go +++ b/core/state/snapshot/snapshot.go @@ -560,7 +560,7 @@ func diffToDisk(bottom *diffLayer) *diskLayer { // Ensure we don't write too much data blindly. It's ok to flush, the // root will go missing in case of a crash and we'll detect and regen // the snapshot. - if batch.ValueSize() > 64*common.Megabytes { + if batch.ValueSize() > 64*common.Megabyte { if err := batch.Write(); err != nil { log.Crit("Failed to write state changes", "err", err) } @@ -595,7 +595,7 @@ func diffToDisk(bottom *diffLayer) *diskLayer { // Ensure we don't write too much data blindly. It's ok to flush, the // root will go missing in case of a crash and we'll detect and regen // the snapshot. - if batch.ValueSize() > 64*common.Megabytes { + if batch.ValueSize() > 64*common.Megabyte { if err := batch.Write(); err != nil { log.Crit("Failed to write state changes", "err", err) } @@ -774,7 +774,6 @@ func (t *Tree) Verify(root common.Hash) error { } return hash, nil }, newGenerateStats(), true) - if err != nil { return err } diff --git a/core/txpool/blobpool/blobpool.go b/core/txpool/blobpool/blobpool.go index 12412d48e6..87f00d4844 100644 --- a/core/txpool/blobpool/blobpool.go +++ b/core/txpool/blobpool/blobpool.go @@ -53,14 +53,14 @@ const ( // txAvgSize is an approximate byte size of a transaction metadata to avoid // tiny overflows causing all txs to move a shelf higher, wasting disk space. - txAvgSize = 4 * common.Kilobytes + txAvgSize = 4 * common.Kilobyte // txMaxSize is the maximum size a single transaction can have, outside // the included blobs. Since blob transactions are pulled instead of pushed, // and only a small metadata is kept in ram, the rest is on disk, there is // no critical limit that should be enforced. Still, capping it to some sane // limit can never hurt. - txMaxSize = common.Megabytes + txMaxSize = common.Megabyte // maxTxsPerAccount is the maximum number of blob transactions admitted from // a single account. The limit is enforced to minimize the DoS potential of @@ -364,11 +364,11 @@ func (p *BlobPool) Init(gasTip uint64, head *types.Header, reserver txpool.Reser ) if p.config.Datadir != "" { queuedir = filepath.Join(p.config.Datadir, pendingTransactionStore) - if err := os.MkdirAll(queuedir, 0700); err != nil { + if err := os.MkdirAll(queuedir, 0o700); err != nil { return err } limbodir = filepath.Join(p.config.Datadir, limboedTransactionStore) - if err := os.MkdirAll(limbodir, 0700); err != nil { + if err := os.MkdirAll(limbodir, 0o700); err != nil { return err } } diff --git a/core/txpool/blobpool/config.go b/core/txpool/blobpool/config.go index 90ae4b8775..f10620a305 100644 --- a/core/txpool/blobpool/config.go +++ b/core/txpool/blobpool/config.go @@ -31,8 +31,8 @@ type Config struct { // DefaultConfig contains the default configurations for the transaction pool. var DefaultConfig = Config{ Datadir: "blobpool", - Datacap: 10 * common.Gigabytes / 4, // TODO(karalabe): /4 handicap for rollout, gradually bump back up to 10GB - PriceBump: 100, // either have patience or be aggressive, no mushy ground + Datacap: 10 * common.Gigabyte / 4, // TODO(karalabe): /4 handicap for rollout, gradually bump back up to 10GB + PriceBump: 100, // either have patience or be aggressive, no mushy ground } // sanitize checks the provided user configurations and changes anything that's diff --git a/core/txpool/legacypool/legacypool.go b/core/txpool/legacypool/legacypool.go index a870c9639d..b681339402 100644 --- a/core/txpool/legacypool/legacypool.go +++ b/core/txpool/legacypool/legacypool.go @@ -49,7 +49,7 @@ const ( // takes up based on its size. The slots are used as DoS protection, ensuring // that validating a new transaction remains a constant operation (in reality // O(maxslots), where max slots are 4 currently). - txSlotSize = 32 * common.Kilobytes + txSlotSize = 32 * common.Kilobyte // txMaxSize is the maximum size a single transaction can have. This field has // non-trivial consequences: larger transactions are significantly harder and @@ -970,7 +970,7 @@ func (pool *LegacyPool) Add(txs []*types.Transaction, sync bool) []error { newErrs, dirtyAddrs := pool.addTxsLocked(news) pool.mu.Unlock() - var nilSlot = 0 + nilSlot := 0 for _, err := range newErrs { for errs[nilSlot] != nil { nilSlot++ @@ -1466,7 +1466,7 @@ func (pool *LegacyPool) promoteExecutables(accounts []common.Address) []*types.T queuedGauge.Dec(int64(len(readies))) // Drop all transactions over the allowed limit - var caps = list.Cap(int(pool.config.AccountQueue)) + caps := list.Cap(int(pool.config.AccountQueue)) for _, tx := range caps { hash := tx.Hash() pool.all.Remove(hash) diff --git a/eth/backend.go b/eth/backend.go index e547708f0c..71dc9da726 100644 --- a/eth/backend.go +++ b/eth/backend.go @@ -126,7 +126,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { } config.TrieDirtyCache = 0 } - log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*common.Megabytes, "dirty", common.StorageSize(config.TrieDirtyCache)*common.Megabytes) + log.Info("Allocated trie memory caches", "clean", common.StorageSize(config.TrieCleanCache)*common.Megabyte, "dirty", common.StorageSize(config.TrieDirtyCache)*common.Megabyte) chainDb, err := stack.OpenDatabaseWithFreezer("chaindata", config.DatabaseCache, config.DatabaseHandles, config.DatabaseFreezer, "eth/db/chaindata/", false) if err != nil { @@ -173,7 +173,7 @@ func New(stack *node.Node, config *ethconfig.Config) (*Ethereum, error) { shutdownTracker: shutdowncheck.NewShutdownTracker(chainDb), } bcVersion := rawdb.ReadDatabaseVersion(chainDb) - var dbVer = "" + dbVer := "" if bcVersion != nil { dbVer = fmt.Sprintf("%d", *bcVersion) } diff --git a/eth/downloader/queue.go b/eth/downloader/queue.go index 4919060dcd..eed24db687 100644 --- a/eth/downloader/queue.go +++ b/eth/downloader/queue.go @@ -42,10 +42,10 @@ const ( ) var ( - blockCacheMaxItems = 8192 // Maximum number of blocks to cache before throttling the download - blockCacheInitialItems = 2048 // Initial number of blocks to start fetching, before we know the sizes of the blocks - blockCacheMemory = 256 * common.Megabytes // Maximum amount of memory to use for block caching - blockCacheSizeWeight = 0.1 // Multiplier to approximate the average block size based on past ones + blockCacheMaxItems = 8192 // Maximum number of blocks to cache before throttling the download + blockCacheInitialItems = 2048 // Initial number of blocks to start fetching, before we know the sizes of the blocks + blockCacheMemory = 256 * common.Megabyte // Maximum amount of memory to use for block caching + blockCacheSizeWeight = 0.1 // Multiplier to approximate the average block size based on past ones ) var ( diff --git a/eth/protocols/eth/handler.go b/eth/protocols/eth/handler.go index 09eff1e970..3ea851bc64 100644 --- a/eth/protocols/eth/handler.go +++ b/eth/protocols/eth/handler.go @@ -33,7 +33,7 @@ import ( const ( // softResponseLimit is the target maximum size of replies to data retrievals. - softResponseLimit = 2 * common.Megabytes + softResponseLimit = 2 * common.Megabyte // maxHeadersServe is the maximum number of block headers to serve. This number // is there to limit the number of disk lookups. @@ -160,11 +160,13 @@ func Handle(backend Backend, peer *Peer) error { } } -type msgHandler func(backend Backend, msg Decoder, peer *Peer) error -type Decoder interface { - Decode(val interface{}) error - Time() time.Time -} +type ( + msgHandler func(backend Backend, msg Decoder, peer *Peer) error + Decoder interface { + Decode(val interface{}) error + Time() time.Time + } +) var eth68 = map[uint64]msgHandler{ NewBlockHashesMsg: handleNewBlockhashes, @@ -194,7 +196,7 @@ func handleMessage(backend Backend, peer *Peer) error { } defer msg.Discard() - var handlers = eth68 + handlers := eth68 // Track the amount of time it takes to serve the request and run the handler if metrics.Enabled() { diff --git a/eth/protocols/eth/protocol.go b/eth/protocols/eth/protocol.go index a1098f3875..7c385fd88f 100644 --- a/eth/protocols/eth/protocol.go +++ b/eth/protocols/eth/protocol.go @@ -46,7 +46,7 @@ var ProtocolVersions = []uint{ETH68} var protocolLengths = map[uint]uint64{ETH68: 17} // maxMessageSize is the maximum cap on the size of a protocol message. -const maxMessageSize = 10 * common.Megabytes +const maxMessageSize = 10 * common.Megabyte const ( StatusMsg = 0x00 diff --git a/eth/protocols/snap/handler.go b/eth/protocols/snap/handler.go index 6011bc302c..fb218e05b2 100644 --- a/eth/protocols/snap/handler.go +++ b/eth/protocols/snap/handler.go @@ -35,7 +35,7 @@ import ( const ( // softResponseLimit is the target maximum size of replies to data retrievals. - softResponseLimit = 2 * common.Megabytes + softResponseLimit = 2 * common.Megabyte // maxCodeLookups is the maximum number of bytecodes to serve. This number is // there to limit the number of disk lookups. @@ -354,7 +354,7 @@ func ServiceGetStorageRangesQuery(chain *core.BlockChain, req *GetStorageRangesP if len(req.Origin) > 0 { origin, req.Origin = common.BytesToHash(req.Origin), nil } - var limit = common.MaxHash + limit := common.MaxHash if len(req.Limit) > 0 { limit, req.Limit = common.BytesToHash(req.Limit), nil } diff --git a/eth/protocols/snap/protocol.go b/eth/protocols/snap/protocol.go index bbb7382e64..0e4bb8fc3d 100644 --- a/eth/protocols/snap/protocol.go +++ b/eth/protocols/snap/protocol.go @@ -43,7 +43,7 @@ var ProtocolVersions = []uint{SNAP1} var protocolLengths = map[uint]uint64{SNAP1: 8} // maxMessageSize is the maximum cap on the size of a protocol message. -const maxMessageSize = 10 * common.Megabytes +const maxMessageSize = 10 * common.Megabyte const ( GetAccountRangeMsg = 0x00 diff --git a/eth/protocols/snap/sync.go b/eth/protocols/snap/sync.go index 8973b8ff1d..2a6f10eac3 100644 --- a/eth/protocols/snap/sync.go +++ b/eth/protocols/snap/sync.go @@ -48,12 +48,12 @@ const ( // minRequestSize is the minimum number of bytes to request from a remote peer. // This number is used as the low cap for account and storage range requests. // Bytecode and trienode are limited inherently by item count (1). - minRequestSize = 64 * common.Kilobytes + minRequestSize = 64 * common.Kilobyte // maxRequestSize is the maximum number of bytes to request from a remote peer. // This number is used as the high cap for account and storage range requests. // Bytecode and trienode are limited more explicitly by the caps below. - maxRequestSize = 512 * common.Kilobytes + maxRequestSize = 512 * common.Kilobyte // maxCodeRequestCount is the maximum number of bytecode blobs to request in a // single query. If this number is too low, we're not filling responses fully @@ -63,7 +63,7 @@ const ( // Deployed bytecodes are currently capped at 24KB, so the minimum request // size should be maxRequestSize / 24K. Assuming that most contracts do not // come close to that, requesting 4x should be a good approximation. - maxCodeRequestCount = maxRequestSize / (24 * common.Kilobytes) * 4 + maxCodeRequestCount = maxRequestSize / (24 * common.Kilobyte) * 4 // maxTrieRequestCount is the maximum number of trie node blobs to request in // a single query. If this number is too low, we're not filling responses fully @@ -95,7 +95,7 @@ const ( trienodeHealThrottleDecrease = 1.25 // batchSizeThreshold is the maximum size allowed for gentrie batch. - batchSizeThreshold = 8 * common.Megabytes + batchSizeThreshold = 8 * common.Megabyte ) var ( @@ -1987,9 +1987,7 @@ func (s *Syncer) processAccountResponse(res *accountResponse) { func (s *Syncer) processBytecodeResponse(res *bytecodeResponse) { batch := s.db.NewBatch() - var ( - codes uint64 - ) + var codes uint64 for i, hash := range res.hashes { code := res.codes[i] diff --git a/eth/tracers/api.go b/eth/tracers/api.go index 249af2b671..82ca467aba 100644 --- a/eth/tracers/api.go +++ b/eth/tracers/api.go @@ -61,7 +61,7 @@ const ( // on top of memory. // For non-archive nodes, this limit _will_ be overblown, as disk-backed tries // will only be found every ~15K blocks or so. - defaultTracechainMemLimit = common.StorageSize(500 * common.Megabytes) + defaultTracechainMemLimit = common.StorageSize(500 * common.Megabyte) // maximumPendingTraceStates is the maximum number of states allowed waiting // for tracing. The creation of trace state will be paused if the unused diff --git a/eth/tracers/internal/util.go b/eth/tracers/internal/util.go index d7feb68360..611e0610fd 100644 --- a/eth/tracers/internal/util.go +++ b/eth/tracers/internal/util.go @@ -25,7 +25,7 @@ import ( ) const ( - memoryPadLimit = common.Megabytes + memoryPadLimit = common.Megabyte ) // GetMemoryCopyPadded returns offset + size as a new slice. diff --git a/ethdb/batch.go b/ethdb/batch.go index 7b0f14f49d..efb8da41a5 100644 --- a/ethdb/batch.go +++ b/ethdb/batch.go @@ -20,7 +20,7 @@ import "github.com/ethereum/go-ethereum/common" // IdealBatchSize defines the size of the data batches should ideally add in one // write. -const IdealBatchSize = 100 * common.Kilobytes +const IdealBatchSize = 100 * common.Kilobyte // Batch is a write-only database that commits changes to its host database // when Write is called. A batch cannot be used concurrently. diff --git a/ethdb/pebble/pebble.go b/ethdb/pebble/pebble.go index 4be4819e09..85484f99c6 100644 --- a/ethdb/pebble/pebble.go +++ b/ethdb/pebble/pebble.go @@ -153,7 +153,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool, e handles = minHandles } logger := log.New("database", file) - logger.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*common.Megabytes), "handles", handles) + logger.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*common.Megabyte), "handles", handles) // The max memtable size is limited by the uint32 offsets stored in // internal/arenaskl.node, DeferredBatchOp, and flushableBatchEntry. @@ -170,7 +170,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool, e // Two memory tables is configured which is identical to leveldb, // including a frozen memory table and another live one. memTableLimit := 2 - memTableSize := cache * common.Megabytes / 2 / memTableLimit + memTableSize := cache * common.Megabyte / 2 / memTableLimit // The memory table size is currently capped at maxMemTableSize-1 due to a // known bug in the pebble where maxMemTableSize is not recognized as a @@ -191,7 +191,7 @@ func New(file string, cache int, handles int, namespace string, readonly bool, e // Pebble has a single combined cache area and the write // buffers are taken from this too. Assign all available // memory allowance for cache. - Cache: pebble.NewCache(int64(cache * common.Megabytes)), + Cache: pebble.NewCache(int64(cache * common.Megabyte)), MaxOpenFiles: handles, // The size of memory table(as well as the write buffer). @@ -212,13 +212,13 @@ func New(file string, cache int, handles int, namespace string, readonly bool, e // Per-level options. Options for at least one level must be specified. The // options for the last level are used for all subsequent levels. Levels: []pebble.LevelOptions{ - {TargetFileSize: 2 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, - {TargetFileSize: 4 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, - {TargetFileSize: 8 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, - {TargetFileSize: 16 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, - {TargetFileSize: 32 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, - {TargetFileSize: 64 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, - {TargetFileSize: 128 * common.Megabytes, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 2 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 4 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 8 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 16 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 32 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 64 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, + {TargetFileSize: 128 * common.Megabyte, FilterPolicy: bloom.FilterPolicy(10)}, }, ReadOnly: readonly, EventListener: &pebble.EventListener{ diff --git a/ethstats/ethstats.go b/ethstats/ethstats.go index eb9ab5f45e..d549e2e414 100644 --- a/ethstats/ethstats.go +++ b/ethstats/ethstats.go @@ -56,7 +56,7 @@ const ( // chainHeadChanSize is the size of channel listening to ChainHeadEvent. chainHeadChanSize = 10 - messageSizeLimit = 15 * common.Megabytes + messageSizeLimit = 15 * common.Megabyte ) // backend encompasses the bare-minimum functionality needed for ethstats reporting diff --git a/internal/era/e2store/e2store.go b/internal/era/e2store/e2store.go index 53f2b32401..2c8ff3a952 100644 --- a/internal/era/e2store/e2store.go +++ b/internal/era/e2store/e2store.go @@ -27,7 +27,7 @@ import ( const ( headerSize = 8 - valueSizeLimit = 50 * common.Megabytes + valueSizeLimit = 50 * common.Megabyte ) // Entry is a variable-length-data record in an e2store. diff --git a/rpc/http.go b/rpc/http.go index 56f766effa..e8544c2878 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -35,7 +35,7 @@ import ( ) const ( - defaultBodyLimit = 5 * common.Megabytes + defaultBodyLimit = 5 * common.Megabyte contentType = "application/json" ) diff --git a/rpc/websocket.go b/rpc/websocket.go index 87210a255d..eae8c6555c 100644 --- a/rpc/websocket.go +++ b/rpc/websocket.go @@ -39,7 +39,7 @@ const ( wsPingInterval = 30 * time.Second wsPingWriteTimeout = 5 * time.Second wsPongTimeout = 30 * time.Second - wsDefaultReadLimit = 32 * common.Megabytes + wsDefaultReadLimit = 32 * common.Megabyte ) var wsBufferPool = new(sync.Pool) @@ -49,7 +49,7 @@ var wsBufferPool = new(sync.Pool) // allowedOrigins should be a comma-separated list of allowed origin URLs. // To allow connections with any origin, pass "*". func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler { - var upgrader = websocket.Upgrader{ + upgrader := websocket.Upgrader{ ReadBufferSize: wsReadBuffer, WriteBufferSize: wsWriteBuffer, WriteBufferPool: wsBufferPool, @@ -347,7 +347,7 @@ func (wc *websocketCodec) writeJSON(ctx context.Context, v interface{}, isError // pingLoop sends periodic ping frames when the connection is idle. func (wc *websocketCodec) pingLoop() { - var pingTimer = time.NewTimer(wsPingInterval) + pingTimer := time.NewTimer(wsPingInterval) defer wc.wg.Done() defer pingTimer.Stop() diff --git a/triedb/pathdb/database.go b/triedb/pathdb/database.go index 4003c8ef56..049996a8b2 100644 --- a/triedb/pathdb/database.go +++ b/triedb/pathdb/database.go @@ -36,26 +36,24 @@ import ( const ( // defaultCleanSize is the default memory allowance of clean cache. - defaultCleanSize = 16 * common.Megabytes + defaultCleanSize = 16 * common.Megabyte // maxBufferSize is the maximum memory allowance of node buffer. // Too large buffer will cause the system to pause for a long // time when write happens. Also, the largest batch that pebble can // support is 4GB, node will panic if batch size exceeds this limit. - maxBufferSize = 256 * common.Megabytes + maxBufferSize = 256 * common.Megabyte // defaultBufferSize is the default memory allowance of node buffer // that aggregates the writes from above until it's flushed into the // disk. It's meant to be used once the initial sync is finished. // Do not increase the buffer size arbitrarily, otherwise the system // pause time will increase when the database writes happen. - defaultBufferSize = 64 * common.Megabytes + defaultBufferSize = 64 * common.Megabyte ) -var ( - // maxDiffLayers is the maximum diff layers allowed in the layer tree. - maxDiffLayers = 128 -) +// maxDiffLayers is the maximum diff layers allowed in the layer tree. +var maxDiffLayers = 128 // layer is the interface implemented by all state layers which includes some // public methods and some additional methods for internal usage. diff --git a/triedb/preimages.go b/triedb/preimages.go index c13201af67..1835936029 100644 --- a/triedb/preimages.go +++ b/triedb/preimages.go @@ -74,7 +74,7 @@ func (store *preimageStore) commit(force bool) error { store.lock.Lock() defer store.lock.Unlock() - if store.preimagesSize <= 4*common.Megabytes && !force { + if store.preimagesSize <= 4*common.Megabyte && !force { return nil } batch := store.disk.NewBatch()