From 50e1acbb3a6c31ebd408e4064ab19ae6f71aa06d Mon Sep 17 00:00:00 2001 From: WeebDataHoarder <57538841+WeebDataHoarder@users.noreply.github.com> Date: Mon, 26 Feb 2024 19:45:13 +0100 Subject: [PATCH] Upgrade to new logger format --- cmd/api/api.go | 13 ++-- cmd/apitocache/apitocache.go | 7 +- cmd/archivetoarchive/archivetoarchive.go | 13 ++-- cmd/archivetoindex/archivetoindex.go | 49 ++++++------ cmd/cachetoarchive/cachetoarchive.go | 9 +-- cmd/daemon/daemon.go | 58 +++++++-------- cmd/daemon/ws.go | 15 ++-- cmd/index/index.go | 61 ++++++++------- cmd/legacytoarchive/legacytoarchive.go | 25 +++---- cmd/p2pool/main.go | 42 +++++------ cmd/p2pool/p2pool.go | 25 +++---- cmd/readcache/readcache.go | 11 ++- cmd/recoverpoolblock/recoverpoolblock.go | 41 +++++----- cmd/scansweeps/scansweeps.go | 15 ++-- cmd/utils/coinbase.go | 21 +++--- cmd/utils/transaction_lookup.go | 10 +-- cmd/web/web.go | 11 +-- monero/address/address_test.go | 4 +- monero/client/client.go | 4 +- monero/randomx/randomx_cgo.go | 4 +- p2pool/api/p2poolapi.go | 16 ++-- p2pool/cache/archive/archive.go | 17 ++--- p2pool/cache/legacy/legacy.go | 5 +- p2pool/mainchain/mainchain.go | 14 ++-- p2pool/mempool/mempool.go | 2 +- p2pool/p2p/client.go | 48 ++++++------ p2pool/p2p/server.go | 27 ++++--- p2pool/sidechain/blobcache.go | 8 +- p2pool/sidechain/consensus.go | 3 +- p2pool/sidechain/sidechain.go | 54 +++++++------- p2pool/sidechain/utils.go | 6 +- utils/logger.go | 95 ++++++++++++++++++++++-- 32 files changed, 393 insertions(+), 340 deletions(-) diff --git a/cmd/api/api.go b/cmd/api/api.go index faf7f50..0b2be25 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -21,7 +21,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/gorilla/mux" "io" - "log" "math" "net/http" _ "net/http/pprof" @@ -37,8 +36,6 @@ import ( ) func main() { - log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) - torHost := os.Getenv("TOR_SERVICE_ADDRESS") moneroHost := flag.String("host", "127.0.0.1", "IP address of your Monero node") moneroRpcPort := flag.Uint("rpc-port", 18081, "monerod RPC API port number") @@ -52,13 +49,13 @@ func main() { p2api := p2poolapi.NewP2PoolApi(*p2poolApiHost) if err := p2api.WaitSyncStart(); err != nil { - log.Panic(err) + utils.Panic(err) } consensus := p2api.Consensus() indexDb, err := index.OpenIndex(*dbString, consensus, p2api.DifficultyByHeight, p2api.SeedByHeight, p2api.ByTemplateId) if err != nil { - log.Panic(err) + utils.Panic(err) } defer indexDb.Close() @@ -188,7 +185,7 @@ func main() { uncleCount += len(slot.Uncles) bottom = slot.Block }); err != nil { - utils.Errorf("error scanning PPLNS window: %s", err) + utils.Errorf("", "error scanning PPLNS window: %s", err) if oldPoolInfo != nil { // got error, just update last pool @@ -2120,12 +2117,12 @@ func main() { if *debugListen != "" { go func() { if err := http.ListenAndServe(*debugListen, nil); err != nil { - log.Panic(err) + utils.Panic(err) } }() } if err := server.ListenAndServe(); err != nil { - log.Panic(err) + utils.Panic(err) } } diff --git a/cmd/apitocache/apitocache.go b/cmd/apitocache/apitocache.go index 3aa14f4..e045382 100644 --- a/cmd/apitocache/apitocache.go +++ b/cmd/apitocache/apitocache.go @@ -8,7 +8,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/sidechain" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "slices" "strconv" ) @@ -30,14 +29,14 @@ func main() { consensusData, _ := utils.MarshalJSON(poolInfo.SideChain.Consensus) consensus, err := sidechain.NewConsensusFromJSON(consensusData) if err != nil { - log.Panic(err) + utils.Panic(err) } - utils.Logf("Consensus id = %s", consensus.Id) + utils.Logf("Consensus", "Consensus id = %s", consensus.Id) cache, err := legacy.NewCache(consensus, *outputFile) if err != nil { - log.Panic(err) + utils.Panic(err) } defer cache.Close() diff --git a/cmd/archivetoarchive/archivetoarchive.go b/cmd/archivetoarchive/archivetoarchive.go index e5f880f..28291ac 100644 --- a/cmd/archivetoarchive/archivetoarchive.go +++ b/cmd/archivetoarchive/archivetoarchive.go @@ -10,7 +10,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/floatdrop/lru" - "log" "math" "os" ) @@ -30,7 +29,7 @@ func main() { consensus, err := sidechain.NewConsensusFromJSON(cf) if err != nil { - log.Panic(err) + utils.Panic(err) } difficultyCache := lru.New[uint64, types.Difficulty](1024) @@ -50,13 +49,13 @@ func main() { inputCache, err := archive.NewCache(*inputArchive, consensus, getDifficultyByHeight) if err != nil { - log.Panic(err) + utils.Panic(err) } defer inputCache.Close() outputCache, err := archive.NewCache(*outputArchive, consensus, getDifficultyByHeight) if err != nil { - log.Panic(err) + utils.Panic(err) } defer outputCache.Close() @@ -88,7 +87,7 @@ func main() { for i, b := range blocksAtHeight { blocksProcessed++ if _, err := b.PreProcessBlock(consensus, derivationCache, preAllocatedShares, getDifficultyByHeight, getByTemplateId); err != nil { - utils.Errorf("error processing block %s at %d, %s", types.HashFromBytes(b.CoinbaseExtra(sidechain.SideTemplateId)), b.Side.Height, err) + utils.Errorf("", "error processing block %s at %d, %s", types.HashFromBytes(b.CoinbaseExtra(sidechain.SideTemplateId)), b.Side.Height, err) } else { if parent := getByTemplateId(b.Side.Parent); parent != nil { topDepth := parent.Depth.Load() @@ -100,7 +99,7 @@ func main() { b.Depth.Store(topDepth - 1) } } else { - utils.Errorf("block %s at %d, could not get parent, fallback", types.HashFromBytes(b.CoinbaseExtra(sidechain.SideTemplateId)), b.Side.Height) + utils.Errorf("", "block %s at %d, could not get parent, fallback", types.HashFromBytes(b.CoinbaseExtra(sidechain.SideTemplateId)), b.Side.Height) b.Depth.Store(math.MaxUint64) } outputCache.Store(b) @@ -111,5 +110,5 @@ func main() { } } - utils.Logf("blocks processed %d", blocksProcessed) + utils.Logf("Archive", "blocks processed %d", blocksProcessed) } diff --git a/cmd/archivetoindex/archivetoindex.go b/cmd/archivetoindex/archivetoindex.go index 1b2aba4..50bb3d0 100644 --- a/cmd/archivetoindex/archivetoindex.go +++ b/cmd/archivetoindex/archivetoindex.go @@ -14,7 +14,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/floatdrop/lru" - "log" "math" "os" "sync" @@ -36,10 +35,10 @@ func main() { consensus, err := sidechain.NewConsensusFromJSON(cf) if err != nil { - log.Panic(err) + utils.Panic(err) } if err = consensus.InitHasher(2, randomx.FlagSecure, randomx.FlagFullMemory); err != nil { - log.Panic(err) + utils.Panic(err) } var headerCacheLock sync.RWMutex @@ -95,7 +94,7 @@ func main() { archiveCache, err := archive.NewCache(*inputArchive, consensus, getDifficultyByHeight) if err != nil { - log.Panic(err) + utils.Panic(err) } defer archiveCache.Close() @@ -143,7 +142,7 @@ func main() { indexDb, err := index.OpenIndex(*connString, consensus, getDifficultyByHeight, getSeedByHeight, getByTemplateIdDirect) if err != nil { - log.Panic(err) + utils.Panic(err) } defer indexDb.Close() @@ -171,7 +170,7 @@ func main() { if len(heightRanges) == 0 { for blocksAtHeight := range archiveCache.ScanHeights(0, math.MaxUint64) { if len(blocksAtHeight) == 0 { - log.Panicf("no blocks at %d + 1?", lastRangeHeight) + utils.Panicf("no blocks at %d + 1?", lastRangeHeight) } if lastRangeHeight == math.MaxUint64 { rangeStart = blocksAtHeight[0].Side.Height @@ -181,22 +180,22 @@ func main() { tipHeight: lastRangeHeight, tipEntries: lastTipEntries, }) - utils.Logf("range %d -> %d, total of %d height(s)", rangeStart, lastRangeHeight, lastRangeHeight-rangeStart+1) - utils.Logf("missing %d -> %d, total of %d height(s)", lastRangeHeight+1, blocksAtHeight[0].Side.Height-1, (blocksAtHeight[0].Side.Height-1)-(lastRangeHeight+1)+1) + utils.Logf("", "range %d -> %d, total of %d height(s)", rangeStart, lastRangeHeight, lastRangeHeight-rangeStart+1) + utils.Logf("", "missing %d -> %d, total of %d height(s)", lastRangeHeight+1, blocksAtHeight[0].Side.Height-1, (blocksAtHeight[0].Side.Height-1)-(lastRangeHeight+1)+1) rangeStart = blocksAtHeight[0].Side.Height } lastRangeHeight = blocksAtHeight[0].Side.Height totalStored += len(blocksAtHeight) lastTipEntries = blocksAtHeight } - utils.Logf("range %d -> %d, total of %d height(s)", rangeStart, lastRangeHeight, lastRangeHeight-rangeStart+1) + utils.Logf("", "range %d -> %d, total of %d height(s)", rangeStart, lastRangeHeight, lastRangeHeight-rangeStart+1) heightRanges = append(heightRanges, rangeEntry{ startHeight: rangeStart, tipHeight: lastRangeHeight, tipEntries: lastTipEntries, }) - utils.Logf("total stored %d", totalStored) + utils.Logf("", "total stored %d", totalStored) } var lastTime, lastHeight uint64 = math.MaxUint64, math.MaxUint64 @@ -224,18 +223,18 @@ func main() { } if bestTip == nil { - utils.Logf("skipped range %d to %d due to: nil tip", r.startHeight, r.tipHeight) + utils.Logf("", "skipped range %d to %d due to: nil tip", r.startHeight, r.tipHeight) continue } else if bestTip.Main.Coinbase.GenHeight > lastHeight { - utils.Logf("skipped range %d to %d due to: main height %d > %d", r.startHeight, r.tipHeight, bestTip.Main.Coinbase.GenHeight, lastHeight) + utils.Logf("", "skipped range %d to %d due to: main height %d > %d", r.startHeight, r.tipHeight, bestTip.Main.Coinbase.GenHeight, lastHeight) continue } else if (bestTip.Main.Timestamp - 60*5) > lastTime { - utils.Logf("skipped range %d to %d due to: timestamp %d > %d", r.startHeight, r.tipHeight, bestTip.Main.Timestamp, lastTime) + utils.Logf("", "skipped range %d to %d due to: timestamp %d > %d", r.startHeight, r.tipHeight, bestTip.Main.Timestamp, lastTime) continue } if err := processBlock(bestTip); err != nil { - utils.Logf("skipped range %d to %d due to: could not process tip: %s", r.startHeight, r.tipHeight, err) + utils.Logf("", "skipped range %d to %d due to: could not process tip: %s", r.startHeight, r.tipHeight, err) continue } @@ -251,15 +250,15 @@ func main() { // skip inserted heights for bestTip != nil && indexDb.GetTipSideBlockByTemplateId(bestTip.SideTemplateId(consensus)) != nil { - utils.Logf("skip id = %s, template id = %s, height = %d", bestTip.MainId(), bestTip.SideTemplateId(consensus), bestTip.Side.Height) + utils.Logf("", "skip id = %s, template id = %s, height = %d", bestTip.MainId(), bestTip.SideTemplateId(consensus), bestTip.Side.Height) bestTip = getByTemplateId(bestTip.Side.Parent) } for cur := bestTip; cur != nil; cur = getByTemplateId(cur.Side.Parent) { - utils.Logf("id = %s, template id = %s, height = %d", cur.MainId(), cur.SideTemplateId(consensus), cur.Side.Height) + utils.Logf("", "id = %s, template id = %s, height = %d", cur.MainId(), cur.SideTemplateId(consensus), cur.Side.Height) if err = indexDb.InsertOrUpdatePoolBlock(cur, index.InclusionInVerifiedChain); err != nil { - utils.Logf("error inserting %s, %s at %d: %s", cur.SideTemplateId(consensus), cur.MainId(), cur.Side.Height, err) + utils.Errorf("", "error inserting %s, %s at %d: %s", cur.SideTemplateId(consensus), cur.MainId(), cur.Side.Height, err) break } @@ -280,7 +279,7 @@ func main() { continue } if processBlock(e) != nil { - utils.Logf("error processing orphan/alternate %s, %s at %d: %s", e.SideTemplateId(consensus), e.MainId(), e.Side.Height, err) + utils.Errorf("", "error processing orphan/alternate %s, %s at %d: %s", e.SideTemplateId(consensus), e.MainId(), e.Side.Height, err) continue } if indexDb.GetSideBlockByMainId(e.MainId()) != nil { @@ -288,12 +287,12 @@ func main() { } if curId == e.SideTemplateId(consensus) { if err = indexDb.InsertOrUpdatePoolBlock(e, index.InclusionAlternateInVerifiedChain); err != nil { - log.Panicf("error inserting alternate %s, %s at %d: %s", e.SideTemplateId(consensus), e.MainId(), e.Side.Height, err) + utils.Panicf("error inserting alternate %s, %s at %d: %s", e.SideTemplateId(consensus), e.MainId(), e.Side.Height, err) break } } else { if err = indexDb.InsertOrUpdatePoolBlock(e, index.InclusionOrphan); err != nil { - log.Panicf("error inserting orphan %s, %s at %d: %s", e.SideTemplateId(consensus), e.MainId(), e.Side.Height, err) + utils.Panicf("error inserting orphan %s, %s at %d: %s", e.SideTemplateId(consensus), e.MainId(), e.Side.Height, err) break } } @@ -310,7 +309,7 @@ func main() { if err := indexDb.Query("SELECT MAX(main_height), MIN(main_height) FROM side_blocks WHERE inclusion = $1;", func(row index.RowScanInterface) error { return row.Scan(&maxHeight, &minHeight) }, index.InclusionInVerifiedChain); err != nil { - log.Panic(err) + utils.Panic(err) } heightCount := maxHeight - minHeight + 1 @@ -323,15 +322,15 @@ func main() { for stride := uint64(0); stride <= strides; stride++ { start := minHeight + stride*strideSize end := min(maxHeight, minHeight+stride*strideSize+strideSize) - utils.Logf("checking %d to %d", start, end) + utils.Logf("", "checking %d to %d", start, end) if headers, err := client.GetDefaultClient().GetBlockHeadersRangeResult(start, end, ctx); err != nil { - log.Panic(err) + utils.Panic(err) } else { for _, h := range headers.Headers { if err := cmdutils.FindAndInsertMainHeader(h, indexDb, func(b *sidechain.PoolBlock) { archiveCache.Store(b) }, client.GetDefaultClient(), getDifficultyByHeight, getByTemplateIdDirect, archiveCache.LoadByMainId, archiveCache.LoadByMainChainHeight, processBlock); err != nil { - log.Panic(err) + utils.Panic(err) continue } } @@ -341,7 +340,7 @@ func main() { mainBlocks, _ := indexDb.GetMainBlocksByQuery("WHERE side_template_id IS NOT NULL ORDER BY height DESC;") index.QueryIterate(mainBlocks, func(_ int, mb *index.MainBlock) (stop bool) { if err := cmdutils.FindAndInsertMainHeaderOutputs(mb, indexDb, client.GetDefaultClient(), getDifficultyByHeight, getByTemplateIdDirect, archiveCache.LoadByMainId, archiveCache.LoadByMainChainHeight, processBlock); err != nil { - log.Print(err) + utils.Error(err) } return false }) diff --git a/cmd/cachetoarchive/cachetoarchive.go b/cmd/cachetoarchive/cachetoarchive.go index 09b8137..2b68455 100644 --- a/cmd/cachetoarchive/cachetoarchive.go +++ b/cmd/cachetoarchive/cachetoarchive.go @@ -10,7 +10,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/floatdrop/lru" - "log" "math" "os" ) @@ -39,12 +38,12 @@ func main() { consensus, err := sidechain.NewConsensusFromJSON(cf) if err != nil { - log.Panic(err) + utils.Panic(err) } cache, err := legacy.NewCache(consensus, *inputFile) if err != nil { - log.Panic(err) + utils.Panic(err) } defer cache.Close() @@ -65,7 +64,7 @@ func main() { archiveCache, err := archive.NewCache(*outputArchive, consensus, getDifficultyByHeight) if err != nil { - log.Panic(err) + utils.Panic(err) } defer archiveCache.Close() @@ -78,7 +77,7 @@ func main() { calculatedBlockId := block.SideTemplateId(consensus) if expectedBlockId != calculatedBlockId { - utils.Errorf("ERROR: block height %d, template id %s, expected %s", block.Side.Height, calculatedBlockId, expectedBlockId) + utils.Errorf("", "block height %d, template id %s, expected %s", block.Side.Height, calculatedBlockId, expectedBlockId) } else { cachedBlocks[expectedBlockId] = block } diff --git a/cmd/daemon/daemon.go b/cmd/daemon/daemon.go index 44c7ffe..4af2eb8 100644 --- a/cmd/daemon/daemon.go +++ b/cmd/daemon/daemon.go @@ -14,7 +14,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/sidechain" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "net/http" _ "net/http/pprof" "sync" @@ -29,7 +28,6 @@ func blockId(b *sidechain.PoolBlock) types.Hash { var sideBlocksLock sync.RWMutex func main() { - log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) moneroHost := flag.String("host", "127.0.0.1", "IP address of your Monero node") moneroRpcPort := flag.Uint("rpc-port", 18081, "monerod RPC API port number") @@ -50,22 +48,22 @@ func main() { p2api := p2poolapi.NewP2PoolApi(*p2poolApiHost) if err := p2api.WaitSync(); err != nil { - log.Panic(err) + utils.Panic(err) } if *fullMode { if err := p2api.Consensus().InitHasher(1, randomx.FlagSecure, randomx.FlagFullMemory); err != nil { - log.Panic(err) + utils.Panic(err) } } else { if err := p2api.Consensus().InitHasher(1, randomx.FlagSecure); err != nil { - log.Panic(err) + utils.Panic(err) } } indexDb, err := index.OpenIndex(*dbString, p2api.Consensus(), p2api.DifficultyByHeight, p2api.SeedByHeight, p2api.ByTemplateId) if err != nil { - log.Panic(err) + utils.Panic(err) } defer indexDb.Close() @@ -75,7 +73,7 @@ func main() { if dbTip != nil { tipHeight = dbTip.SideHeight } - utils.Logf("[CHAIN] Last known database tip is %d\n", tipHeight) + utils.Logf("CHAIN", "Last known database tip is %d\n", tipHeight) window, uncles := p2api.StateFromTip() if *startFromHeight != 0 { @@ -96,12 +94,12 @@ func main() { return } for cur := tip; cur != nil; cur = p2api.ByTemplateId(cur.Side.Parent) { - utils.Logf("[CHAIN] Inserting share %s at height %d\n", blockId(cur).String(), cur.Side.Height) + utils.Logf("CHAIN", "Inserting share %s at height %d\n", blockId(cur).String(), cur.Side.Height) for _, u := range cur.Side.Uncles { - utils.Logf("[CHAIN] Inserting uncle %s at parent height %d\n", u.String(), cur.Side.Height) + utils.Logf("CHAIN", "Inserting uncle %s at parent height %d\n", u.String(), cur.Side.Height) } if err := indexDb.InsertOrUpdatePoolBlock(cur, index.InclusionInVerifiedChain); err != nil { - log.Panic(err) + utils.Panic(err) } if indexDb.GetTipSideBlockByTemplateId(cur.Side.Parent) != nil { //reached old tip @@ -113,7 +111,7 @@ func main() { var backfillScan []types.Hash for len(window) > 0 { - utils.Logf("[CHAIN] Found range %d -> %d (%s to %s), %d shares, %d uncles", window[0].Side.Height, window[len(window)-1].Side.Height, window[0].SideTemplateId(p2api.Consensus()), window[len(window)-1].SideTemplateId(p2api.Consensus()), len(window), len(uncles)) + utils.Logf("CHAIN", "Found range %d -> %d (%s to %s), %d shares, %d uncles", window[0].Side.Height, window[len(window)-1].Side.Height, window[0].SideTemplateId(p2api.Consensus()), window[len(window)-1].SideTemplateId(p2api.Consensus()), len(window), len(uncles)) for _, b := range window { indexDb.CachePoolBlock(b) } @@ -126,12 +124,12 @@ func main() { window = nil break } - utils.Logf("[CHAIN] Inserting share %s at height %d\n", blockId(b).String(), b.Side.Height) + utils.Logf("CHAIN", "Inserting share %s at height %d\n", blockId(b).String(), b.Side.Height) for _, u := range b.Side.Uncles { - utils.Logf("[CHAIN] Inserting uncle %s at parent height %d\n", u.String(), b.Side.Height) + utils.Logf("CHAIN", "Inserting uncle %s at parent height %d\n", u.String(), b.Side.Height) } if err := indexDb.InsertOrUpdatePoolBlock(b, index.InclusionInVerifiedChain); err != nil { - log.Panic(err) + utils.Panic(err) } if b.IsProofHigherThanMainDifficulty(p2api.Consensus().GetHasher(), indexDb.GetDifficultyByHeight, indexDb.GetSeedByHeight) { @@ -164,7 +162,7 @@ func main() { if err = indexDb.Query("SELECT (SELECT MAX(main_height) FROM side_blocks) AS max_height, (SELECT MAX(height) FROM main_blocks) AS current_height;", func(row index.RowScanInterface) error { return row.Scan(&maxHeight, ¤tHeight) }); err != nil { - log.Panic(err) + utils.Panic(err) } ctx := context.Background() @@ -190,13 +188,13 @@ func main() { for stride := uint64(0); stride <= strides; stride++ { start := currentHeight + stride*strideSize end := min(maxHeight-1, currentHeight+stride*strideSize+strideSize) - utils.Logf("checking %d to %d", start, end) + utils.Logf("", "checking %d to %d", start, end) if headers, err := client.GetDefaultClient().GetBlockHeadersRangeResult(start, end, ctx); err != nil { - log.Panic(err) + utils.Panic(err) } else { for _, h := range headers.Headers { if err := scanHeader(h); err != nil { - log.Panic(err) + utils.Panic(err) continue } } @@ -205,12 +203,12 @@ func main() { // backfill any missing headers when p2pool was down for _, mainId := range backfillScan { - utils.Logf("checking backfill %s", mainId) + utils.Logf("", "checking backfill %s", mainId) if header, err := client.GetDefaultClient().GetBlockHeaderByHash(mainId, ctx); err != nil { - utils.Logf("not found %s", mainId) + utils.Errorf("", "not found %s", mainId) } else { if err := scanHeader(*header); err != nil { - log.Panic(err) + utils.Panic(err) continue } } @@ -242,7 +240,7 @@ func main() { sideBlocksLock.Lock() defer sideBlocksLock.Unlock() if err := scanHeader(*cur); err != nil { - log.Panic(err) + utils.Panic(err) } }() } @@ -269,7 +267,7 @@ func main() { } if mainTip.Height == maxDepth { - utils.Logf("Reached maxdepth %d: Use scansweeps to backfill data", maxDepth) + utils.Logf("", "Reached maxdepth %d: Use scansweeps to backfill data", maxDepth) } for h := mainTip.Height - monero.MinerRewardUnlockTime; h <= actualTip.Height-monero.TransactionUnlockTime; h++ { @@ -282,7 +280,7 @@ func main() { } if err := cmdutils.ProcessFullBlock(b, indexDb); err != nil { - utils.Logf("error processing block %s at %d: %s", b.Id, b.Height, err) + utils.Logf("", "error processing block %s at %d: %s", b.Id, b.Height, err) } } } @@ -291,7 +289,7 @@ func main() { if *debugListen != "" { go func() { if err := http.ListenAndServe(*debugListen, nil); err != nil { - log.Panic(err) + utils.Panic(err) } }() } @@ -304,14 +302,14 @@ func main() { mainTip := p2api.MainTip() if tip == nil || mainTip == nil { - utils.Logf("could not fetch tip or main tip") + utils.Errorf("", "could not fetch tip or main tip") continue } if blockId(tip) != currentTip.TemplateId { if tip.Side.Height < currentTip.SideHeight { //wtf - log.Panicf("tip height less than ours, abort: %d < %d", tip.Side.Height, currentTip.SideHeight) + utils.Panicf("tip height less than ours, abort: %d < %d", tip.Side.Height, currentTip.SideHeight) } else { func() { sideBlocksLock.Lock() @@ -324,7 +322,7 @@ func main() { if mainTip.Id != currentMainTip.Id { if mainTip.Height < currentMainTip.Height { //wtf - log.Panicf("main tip height less than ours, abort: %d < %d", mainTip.Height, currentMainTip.Height) + utils.Panicf("main tip height less than ours, abort: %d < %d", mainTip.Height, currentMainTip.Height) } else { var prevHash types.Hash for cur, _ := client.GetDefaultClient().GetBlockHeaderByHash(mainTip.Id, ctx); cur != nil; cur, _ = client.GetDefaultClient().GetBlockHeaderByHash(prevHash, ctx) { @@ -337,14 +335,14 @@ func main() { doCheckOfOldBlocks.Store(true) } } - utils.Logf("[MAIN] Insert main block %d, id %s", cur.Height, curHash) + utils.Logf("MAIN", "Insert main block %d, id %s", cur.Height, curHash) func() { sideBlocksLock.Lock() defer sideBlocksLock.Unlock() doCheckOfOldBlocks.Store(true) if err := scanHeader(*cur); err != nil { - log.Panic(err) + utils.Panic(err) } prevHash, _ = types.HashFromString(cur.PrevHash) }() diff --git a/cmd/daemon/ws.go b/cmd/daemon/ws.go index e90a332..49319b9 100644 --- a/cmd/daemon/ws.go +++ b/cmd/daemon/ws.go @@ -7,7 +7,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/api" types2 "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "net/http" "nhooyr.io/websocket" "slices" @@ -96,7 +95,7 @@ func setupEventHandler(p2api *api.P2PoolApi, indexDb *index.Index) { }); i != -1 { listeners = slices.Delete(listeners, i, i+1) } - utils.Logf("[WS] Client %d detached after %.02f seconds", listenerId, time.Now().Sub(requestTime).Seconds()) + utils.Logf("WS", "Client %d detached after %.02f seconds", listenerId, time.Now().Sub(requestTime).Seconds()) }() ctx, cancel := context.WithCancel(request.Context()) @@ -116,7 +115,7 @@ func setupEventHandler(p2api *api.P2PoolApi, indexDb *index.Index) { Context: ctx, Cancel: cancel, }) - utils.Logf("[WS] Client %d attached", listenerId) + utils.Logf("WS", "Client %d attached", listenerId) }() defer c.Close(websocket.StatusInternalError, "closing") @@ -131,7 +130,7 @@ func setupEventHandler(p2api *api.P2PoolApi, indexDb *index.Index) { go func() { if err := server.ListenAndServe(); err != nil { - log.Panic(err) + utils.Panic(err) } }() @@ -349,7 +348,7 @@ func setupEventHandler(p2api *api.P2PoolApi, indexDb *index.Index) { q, _ := indexDb.GetMinerWebHooks(b.Miner) index.QueryIterate(q, func(_ int, w *index.MinerWebHook) (stop bool) { if err := cmdutils.SendSideBlock(w, ts, b.MinerAddress, b); err != nil { - utils.Logf("[WebHook] Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventSideBlock, b.MinerAddress.ToBase58(), w.Type, w.Url, err) + utils.Logf("WebHook", "Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventSideBlock, b.MinerAddress.ToBase58(), w.Type, w.Url, err) } return false }) @@ -463,7 +462,7 @@ func setupEventHandler(p2api *api.P2PoolApi, indexDb *index.Index) { q, _ := indexDb.GetMinerWebHooks(b.Miner) index.QueryIterate(q, func(_ int, w *index.MinerWebHook) (stop bool) { if err := cmdutils.SendOrphanedBlock(w, ts, b.MinerAddress, b); err != nil { - utils.Logf("[WebHook] Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventOrphanedBlock, b.MinerAddress.ToBase58(), w.Type, w.Url, err) + utils.Logf("WebHook", "Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventOrphanedBlock, b.MinerAddress.ToBase58(), w.Type, w.Url, err) } return false }) @@ -535,11 +534,11 @@ func setupEventHandler(p2api *api.P2PoolApi, indexDb *index.Index) { q, _ := indexDb.GetMinerWebHooks(payout.Miner) index.QueryIterate(q, func(_ int, w *index.MinerWebHook) (stop bool) { if err := cmdutils.SendFoundBlock(w, ts, addr, b, coinbaseOutputs); err != nil { - utils.Logf("[WebHook] Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventFoundBlock, addr.ToBase58(), w.Type, w.Url, err) + utils.Logf("WebHook", "Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventFoundBlock, addr.ToBase58(), w.Type, w.Url, err) } if err := cmdutils.SendPayout(w, ts, addr, payout); err != nil { - utils.Logf("[WebHook] Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventPayout, addr.ToBase58(), w.Type, w.Url, err) + utils.Logf("WebHook", "Error sending %s webhook to %s: type %s, url %s: %s", cmdutils.JSONEventPayout, addr.ToBase58(), w.Type, w.Url, err) } return false }) diff --git a/cmd/index/index.go b/cmd/index/index.go index 1e2769c..3a71e94 100644 --- a/cmd/index/index.go +++ b/cmd/index/index.go @@ -16,7 +16,6 @@ import ( "github.com/floatdrop/lru" "github.com/lib/pq" "io" - "log" "path" "reflect" "regexp" @@ -538,11 +537,11 @@ func (i *Index) GetMainBlocksByQueryStatement(stmt *sql.Stmt, params ...any) (Qu func (i *Index) GetMainBlockById(id types.Hash) (b *MainBlock) { if r, err := i.GetMainBlocksByQueryStatement(i.statements.GetMainBlockById, id[:]); err != nil { - log.Print(err) + utils.Print(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Print(r.Err()) } } return b @@ -550,11 +549,11 @@ func (i *Index) GetMainBlockById(id types.Hash) (b *MainBlock) { func (i *Index) GetMainBlockTip() (b *MainBlock) { if r, err := i.GetMainBlocksByQueryStatement(i.statements.TipMainBlock); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -562,11 +561,11 @@ func (i *Index) GetMainBlockTip() (b *MainBlock) { func (i *Index) GetMainBlockByCoinbaseId(id types.Hash) (b *MainBlock) { if r, err := i.GetMainBlocksByQuery("WHERE coinbase_id = $1;", id[:]); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -574,11 +573,11 @@ func (i *Index) GetMainBlockByCoinbaseId(id types.Hash) (b *MainBlock) { func (i *Index) GetMainBlockByGlobalOutputIndex(globalOutputIndex uint64) (b *MainBlock) { if r, err := i.GetMainBlocksByQuery("WHERE coinbase_id = (SELECT id FROM main_coinbase_outputs WHERE global_output_index = $1 LIMIT 1);", globalOutputIndex); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -586,11 +585,11 @@ func (i *Index) GetMainBlockByGlobalOutputIndex(globalOutputIndex uint64) (b *Ma func (i *Index) GetMainBlockByHeight(height uint64) (b *MainBlock) { if r, err := i.GetMainBlocksByQueryStatement(i.statements.GetMainBlockByHeight, height); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -598,11 +597,11 @@ func (i *Index) GetMainBlockByHeight(height uint64) (b *MainBlock) { func (i *Index) GetSideBlockByMainId(id types.Hash) (b *SideBlock) { if r, err := i.GetSideBlocksByQueryStatement(i.statements.GetSideBlockByMainId, id[:]); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -610,7 +609,7 @@ func (i *Index) GetSideBlockByMainId(id types.Hash) (b *SideBlock) { func (i *Index) GetSideBlocksByTemplateId(id types.Hash) QueryIterator[SideBlock] { if r, err := i.GetSideBlocksByQuery("WHERE template_id = $1;", id[:]); err != nil { - log.Print(err) + utils.Error(err) } else { return r } @@ -619,7 +618,7 @@ func (i *Index) GetSideBlocksByTemplateId(id types.Hash) QueryIterator[SideBlock func (i *Index) GetSideBlocksByUncleOfId(id types.Hash) QueryIterator[SideBlock] { if r, err := i.GetSideBlocksByQueryStatement(i.statements.GetSideBlockByUncleId, id[:]); err != nil { - log.Print(err) + utils.Error(err) } else { return r } @@ -628,11 +627,11 @@ func (i *Index) GetSideBlocksByUncleOfId(id types.Hash) QueryIterator[SideBlock] func (i *Index) GetTipSideBlockByTemplateId(id types.Hash) (b *SideBlock) { if r, err := i.GetSideBlocksByQueryStatement(i.statements.TipSideBlocksTemplateId, id[:], InclusionInVerifiedChain); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -640,7 +639,7 @@ func (i *Index) GetTipSideBlockByTemplateId(id types.Hash) (b *SideBlock) { func (i *Index) GetSideBlocksByMainHeight(height uint64) QueryIterator[SideBlock] { if r, err := i.GetSideBlocksByQuery("WHERE main_height = $1;", height); err != nil { - log.Print(err) + utils.Error(err) } else { return r } @@ -649,7 +648,7 @@ func (i *Index) GetSideBlocksByMainHeight(height uint64) QueryIterator[SideBlock func (i *Index) GetSideBlocksByHeight(height uint64) QueryIterator[SideBlock] { if r, err := i.GetSideBlocksByQuery("WHERE side_height = $1;", height); err != nil { - log.Print(err) + utils.Error(err) } else { return r } @@ -658,11 +657,11 @@ func (i *Index) GetSideBlocksByHeight(height uint64) QueryIterator[SideBlock] { func (i *Index) GetTipSideBlockByHeight(height uint64) (b *SideBlock) { if r, err := i.GetSideBlocksByQuery("WHERE side_height = $1 AND effective_height = $2 AND inclusion = $3;", height, height, InclusionInVerifiedChain); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -670,11 +669,11 @@ func (i *Index) GetTipSideBlockByHeight(height uint64) (b *SideBlock) { func (i *Index) GetSideBlockTip() (b *SideBlock) { if r, err := i.GetSideBlocksByQueryStatement(i.statements.TipSideBlock, InclusionInVerifiedChain); err != nil { - log.Print(err) + utils.Error(err) } else { defer r.Close() if _, b = r.Next(); b == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } } return b @@ -690,7 +689,7 @@ func (i *Index) GetSideBlocksInWindow(startHeight, windowSize uint64) QueryItera } if r, err := i.GetSideBlocksByQuery("WHERE effective_height <= $1 AND effective_height > $2 AND inclusion = $3 ORDER BY effective_height DESC, side_height DESC;", startHeight, startHeight-windowSize, InclusionInVerifiedChain); err != nil { - log.Print(err) + utils.Error(err) } else { return r } @@ -703,7 +702,7 @@ func (i *Index) GetSideBlocksByMinerIdInWindow(minerId, startHeight, windowSize } if r, err := i.GetSideBlocksByQuery("WHERE miner = $1 AND effective_height <= $2 AND effective_height > $3 AND inclusion = $4 ORDER BY effective_height DESC, side_height DESC;", minerId, startHeight, startHeight-windowSize, InclusionInVerifiedChain); err != nil { - log.Print(err) + utils.Error(err) } else { return r } @@ -901,11 +900,11 @@ func (i *Index) GetMainCoinbaseOutputs(coinbaseId types.Hash) (QueryIterator[Mai func (i *Index) GetMainCoinbaseOutputByIndex(coinbaseId types.Hash, index uint64) (o *MainCoinbaseOutput) { if stmt, err := i.handle.Prepare("SELECT " + MainCoinbaseOutputSelectFields + " FROM main_coinbase_outputs WHERE id = $1 AND index = $2 ORDER BY index ASC;"); err != nil { - log.Print(err) + utils.Error(err) return nil } else { if r, err := queryStatement[MainCoinbaseOutput](i, stmt, coinbaseId[:], index); err != nil { - log.Print(err) + utils.Error(err) return nil } else { defer r.Close() @@ -914,7 +913,7 @@ func (i *Index) GetMainCoinbaseOutputByIndex(coinbaseId types.Hash, index uint64 } defer r.Close() if _, o = r.Next(); o == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } return o } @@ -923,11 +922,11 @@ func (i *Index) GetMainCoinbaseOutputByIndex(coinbaseId types.Hash, index uint64 func (i *Index) GetMainCoinbaseOutputByGlobalOutputIndex(globalOutputIndex uint64) (o *MainCoinbaseOutput) { if stmt, err := i.handle.Prepare("SELECT " + MainCoinbaseOutputSelectFields + " FROM main_coinbase_outputs WHERE global_output_index = $1 ORDER BY index ASC;"); err != nil { - log.Print(err) + utils.Error(err) return nil } else { if r, err := queryStatement[MainCoinbaseOutput](i, stmt, globalOutputIndex); err != nil { - log.Print(err) + utils.Error(err) return nil } else { defer r.Close() @@ -936,7 +935,7 @@ func (i *Index) GetMainCoinbaseOutputByGlobalOutputIndex(globalOutputIndex uint6 } defer r.Close() if _, o = r.Next(); o == nil && r.Err() != nil { - log.Print(r.Err()) + utils.Error(r.Err()) } return o } diff --git a/cmd/legacytoarchive/legacytoarchive.go b/cmd/legacytoarchive/legacytoarchive.go index aeb6180..3d47d6a 100644 --- a/cmd/legacytoarchive/legacytoarchive.go +++ b/cmd/legacytoarchive/legacytoarchive.go @@ -8,7 +8,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/floatdrop/lru" - "log" "math" "os" "path" @@ -25,14 +24,14 @@ func main() { consensus, err := sidechain.NewConsensusFromJSON(cf) if err != nil { - log.Panic(err) + utils.Panic(err) } archiveCache, err := archive.NewCache(*outputArchive, consensus, func(height uint64) types.Difficulty { return types.ZeroDifficulty }) if err != nil { - log.Panic(err) + utils.Panic(err) } defer archiveCache.Close() @@ -51,10 +50,10 @@ func main() { return nil } else { if hexBuf, err := hex.DecodeString(string(buf)); err != nil { - log.Panic(err) + utils.Panic(err) } else { if block, err := sidechain.NewShareFromExportedBytes(hexBuf, consensus, derivationCache); err != nil { - utils.Logf("error decoding block %s, %s", id.String(), err) + utils.Error("", "error decoding block %s, %s", id.String(), err) } else { block.Depth.Store(math.MaxUint64) return block @@ -107,9 +106,9 @@ func main() { for i := 0; i <= 0xf; i++ { n := hex.EncodeToString([]byte{byte(i)}) dPath := path.Join(*inputFolder, "blocks", n[1:]) - utils.Logf("Reading directory %s", dPath) + utils.Logf("", "Reading directory %s", dPath) if dir, err := os.ReadDir(dPath); err != nil { - log.Panic(err) + utils.Panic(err) } else { for _, e := range dir { h, _ := hex.DecodeString(e.Name()) @@ -126,19 +125,19 @@ func main() { n := hex.EncodeToString([]byte{byte(i)}) dPath := path.Join(*inputFolder, "failed_blocks", n[1:]) if dir, err := os.ReadDir(dPath); err != nil { - log.Panic(err) + utils.Panic(err) } else { for _, e := range dir { fPath := path.Join(dPath, e.Name()) - utils.Logf("Processing %s", fPath) + utils.Logf("", "Processing %s", fPath) if buf, err := os.ReadFile(path.Join(dPath, e.Name())); err != nil { - log.Panic(err) + utils.Panic(err) } else { if hexBuf, err := hex.DecodeString(string(buf)); err != nil { - log.Panic(err) + utils.Panic(err) } else { if block, err := sidechain.NewShareFromExportedBytes(hexBuf, consensus, derivationCache); err != nil { - log.Panic(err) + utils.Panic(err) } else { block.Depth.Store(math.MaxUint64) archiveCache.Store(block) @@ -150,5 +149,5 @@ func main() { } } - utils.Logf("total stored %d", totalStored) + utils.Logf("", "total stored %d", totalStored) } diff --git a/cmd/p2pool/main.go b/cmd/p2pool/main.go index 18cade9..f18c2c9 100644 --- a/cmd/p2pool/main.go +++ b/cmd/p2pool/main.go @@ -9,7 +9,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/sidechain" "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "net" "net/http" _ "net/http/pprof" @@ -27,9 +26,6 @@ import ( ) func main() { - - log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) - currentConsensus := sidechain.ConsensusDefault //monerod related @@ -68,14 +64,14 @@ func main() { //TODO extend verbosity to debug flag flag.Parse() - if buildInfo, _ := debug.ReadBuildInfo(); buildInfo != nil { - utils.Logf("P2Pool Consensus Software %s %s (go version %s)", types.CurrentSoftwareId, types.CurrentSoftwareVersion, buildInfo.GoVersion) - } else { - utils.Logf("P2Pool Consensus Software %s %s (go version %s)", types.CurrentSoftwareId, types.CurrentSoftwareVersion, runtime.Version()) + if *doDebug { + utils.LogFile = true } - if *doDebug { - log.SetFlags(log.Flags() | log.Lshortfile) + if buildInfo, _ := debug.ReadBuildInfo(); buildInfo != nil { + utils.Logf("P2Pool", "Consensus Software %s %s (go version %s)", types.CurrentSoftwareId, types.CurrentSoftwareVersion, buildInfo.GoVersion) + } else { + utils.Logf("P2Pool", "Consensus Software %s %s (go version %s)", types.CurrentSoftwareId, types.CurrentSoftwareVersion, runtime.Version()) } client.SetDefaultClientSettings(fmt.Sprintf("http://%s:%d", *moneroHost, *moneroRpcPort)) @@ -106,11 +102,11 @@ func main() { if *consensusConfigFile != "" { consensusData, err := os.ReadFile(*consensusConfigFile) if err != nil { - log.Panic(err) + utils.Panic(err) } if newConsensus, err := sidechain.NewConsensusFromJSON(consensusData); err != nil { - log.Panic(err) + utils.Panic(err) } else { changeConsensus(newConsensus) } @@ -137,7 +133,7 @@ func main() { } if instance, err := NewP2Pool(currentConsensus, settings); err != nil { - log.Fatalf("Could not start p2pool: %s", err) + utils.Fatalf("Could not start p2pool: %s", err) } else { defer instance.Close(nil) @@ -154,7 +150,7 @@ func main() { return } - utils.Logf("[API] Handling %s %s", request.Method, request.URL.String()) + utils.Logf("API", "Handling %s %s", request.Method, request.URL.String()) serveMux.ServeHTTP(writer, request) }), @@ -163,7 +159,7 @@ func main() { go func() { //TODO: context/wait if err := server.ListenAndServe(); err != nil { - log.Panic(err) + utils.Panic(err) } }() @@ -172,7 +168,7 @@ func main() { if *debugListen != "" { go func() { if err := http.ListenAndServe(*debugListen, nil); err != nil { - log.Panic(err) + utils.Panic(err) } }() } @@ -186,7 +182,7 @@ func main() { //TODO: dns resolution of hosts if addrPort, err := netip.ParseAddrPort(peerAddr); err != nil { - log.Panic(err) + utils.Panic(err) } else { instance.Server().AddToPeerList(addrPort) connectList = append(connectList, addrPort) @@ -194,7 +190,7 @@ func main() { } if !*noDns && currentConsensus.SeedNode() != "" { - utils.Logf("Loading seed peers from %s", currentConsensus.SeedNode()) + utils.Logf("P2Pool", "Loading seed peers from %s", currentConsensus.SeedNode()) records, _ := net.LookupTXT(currentConsensus.SeedNode()) if len(records) > 0 { for _, r := range records { @@ -214,7 +210,7 @@ func main() { } if *peerList != "" { - utils.Logf("Loading peers from %s", *peerList) + utils.Logf("P2Pool", "Loading peers from %s", *peerList) if len(*peerList) > 4 && (*peerList)[:4] == "http" { func() { r, err := http.DefaultClient.Get(*peerList) @@ -255,7 +251,7 @@ func main() { contents = append(contents, '\n') } if err := os.WriteFile(*peerList, contents, 0644); err != nil { - utils.Logf("error writing peer list %s: %s", *peerList, err.Error()) + utils.Errorf("P2Pool", "error writing peer list %s: %s", *peerList, err.Error()) break } } @@ -265,7 +261,7 @@ func main() { if *addSelf { if addrs, err := utils.GetOutboundIPv6(); err != nil { - utils.Logf("[P2Pool] Could not get interface ipv6 addresses: %s", err) + utils.Errorf("P2Pool", "Could not get interface ipv6 addresses: %s", err) } else { for _, addr := range addrs { if addr.Is6() { @@ -289,7 +285,7 @@ func main() { go func(addrPort netip.AddrPort) { defer wg.Done() if err := instance.Server().Connect(addrPort); err != nil { - utils.Logf("error connecting to initial peer %s: %s", addrPort.String(), err.Error()) + utils.Errorf("error connecting to initial peer %s: %s", addrPort.String(), err.Error()) } }(addrPort) } @@ -313,7 +309,7 @@ func main() { instance.WaitUntilClosed() } if closeError := instance.CloseError(); closeError != nil { - log.Panic(err) + utils.Panic(err) } else { os.Exit(0) } diff --git a/cmd/p2pool/p2pool.go b/cmd/p2pool/p2pool.go index 8c095c6..6b0b2a4 100644 --- a/cmd/p2pool/p2pool.go +++ b/cmd/p2pool/p2pool.go @@ -21,7 +21,6 @@ import ( p2pooltypes "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/types" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "slices" "strconv" "sync" @@ -146,12 +145,12 @@ func (p *P2Pool) Close(err error) { if started && err != nil { close(p.closed) - log.Panicf("[P2Pool] Closed due to error %s", err) + utils.Panicf("[P2Pool] Closed due to error %s", err) } else if started { close(p.closed) - utils.Logf("[P2Pool] Closed") + utils.Logf("P2Pool", "Closed") } else if err != nil { - utils.Logf("[P2Pool] Received extra error during closing %s", err) + utils.Logf("P2Pool", "Received extra error during closing %s", err) } } @@ -426,11 +425,11 @@ func (p *P2Pool) getInfo() error { return err } else { if info.BusySyncing { - utils.Logf("[P2Pool] monerod is busy syncing, trying again in 5 seconds") + utils.Logf("P2Pool", "monerod is busy syncing, trying again in 5 seconds") time.Sleep(time.Second * 5) return p.getInfo() } else if !info.Synchronized { - utils.Logf("[P2Pool] monerod is not synchronized, trying again in 5 seconds") + utils.Logf("P2Pool", "monerod is not synchronized, trying again in 5 seconds") time.Sleep(time.Second * 5) return p.getInfo() } @@ -534,7 +533,7 @@ func (p *P2Pool) UpdateMinerData(data *p2pooltypes.MinerData) { } func (p *P2Pool) UpdateBlockFound(data *sidechain.ChainMain, block *sidechain.PoolBlock) { - utils.Logf("[P2Pool] BLOCK FOUND: main chain block at height %d, id %s was mined by this p2pool", data.Height, data.Id) + utils.Logf("P2Pool", "BLOCK FOUND: main chain block at height %d, id %s was mined by this p2pool", data.Height, data.Id) p.listenersLock.RLock() defer p.listenersLock.RUnlock() @@ -562,15 +561,15 @@ func (p *P2Pool) SubmitBlock(b *block.Block) { if t := b.Coinbase.Extra.GetTag(transaction.TxExtraTagNonce); t != nil { extraNonce = binary.LittleEndian.Uint32(t.Data) } - utils.Logf("[P2Pool] submit_block: height = %d, template id = %s, nonce = %d, extra_nonce = %d, blob = %d bytes", b.Coinbase.GenHeight, templateId.String(), b.Nonce, extraNonce, len(blob)) + utils.Logf("P2Pool", "submit_block: height = %d, template id = %s, nonce = %d, extra_nonce = %d, blob = %d bytes", b.Coinbase.GenHeight, templateId.String(), b.Nonce, extraNonce, len(blob)) if result, err := p.ClientRPC().SubmitBlock(blob); err != nil { - utils.Logf("[P2Pool] submit_block: daemon returned error: %s, height = %d, template id = %s, nonce = %d, extra_nonce = %d", err, b.Coinbase.GenHeight, templateId.String(), b.Nonce, extraNonce) + utils.Logf("P2Pool", "submit_block: daemon returned error: %s, height = %d, template id = %s, nonce = %d, extra_nonce = %d", err, b.Coinbase.GenHeight, templateId.String(), b.Nonce, extraNonce) } else { if result.Status == "OK" { - utils.Logf("[P2Pool] submit_block: BLOCK ACCEPTED at height = %d, template id = %s", b.Coinbase.GenHeight, templateId.String()) + utils.Logf("P2Pool", "submit_block: BLOCK ACCEPTED at height = %d, template id = %s", b.Coinbase.GenHeight, templateId.String()) } else { - utils.Logf("[P2Pool] submit_block: daemon sent unrecognizable reply: %s, height = %d, template id = %s, nonce = %d, extra_nonce = %d", result.Status, b.Coinbase.GenHeight, templateId.String(), b.Nonce, extraNonce) + utils.Logf("P2Pool", "submit_block: daemon sent unrecognizable reply: %s, height = %d, template id = %s, nonce = %d, extra_nonce = %d", result.Status, b.Coinbase.GenHeight, templateId.String(), b.Nonce, extraNonce) } } } @@ -607,12 +606,12 @@ func (p *P2Pool) UpdateTip(tip *sidechain.PoolBlock) { func (p *P2Pool) Broadcast(block *sidechain.PoolBlock) { minerData := p.GetMinerDataTip() if (block.Main.Coinbase.GenHeight)+2 < minerData.Height { - utils.Logf("[P2Pool] Trying to broadcast a stale block %s (mainchain height %d, current height is %d)", block.SideTemplateId(p.consensus), block.Main.Coinbase.GenHeight, minerData.Height) + utils.Logf("P2Pool", "Trying to broadcast a stale block %s (mainchain height %d, current height is %d)", block.SideTemplateId(p.consensus), block.Main.Coinbase.GenHeight, minerData.Height) return } if block.Main.Coinbase.GenHeight > (minerData.Height + 2) { - utils.Logf("[P2Pool] Trying to broadcast a block %s ahead on mainchain (mainchain height %d, current height is %d)", block.SideTemplateId(p.consensus), block.Main.Coinbase.GenHeight, minerData.Height) + utils.Logf("P2Pool", "Trying to broadcast a block %s ahead on mainchain (mainchain height %d, current height is %d)", block.SideTemplateId(p.consensus), block.Main.Coinbase.GenHeight, minerData.Height) return } diff --git a/cmd/readcache/readcache.go b/cmd/readcache/readcache.go index 3a5adb6..1bfd85e 100644 --- a/cmd/readcache/readcache.go +++ b/cmd/readcache/readcache.go @@ -6,7 +6,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/sidechain" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "os" "path" ) @@ -35,12 +34,12 @@ func main() { consensus, err := sidechain.NewConsensusFromJSON(cf) if err != nil { - log.Panic(err) + utils.Panic(err) } cache, err := legacy.NewCache(consensus, *inputFile) if err != nil { - log.Panic(err) + utils.Panic(err) } defer cache.Close() @@ -51,13 +50,13 @@ func main() { calculatedBlockId := block.SideTemplateId(consensus) if expectedBlockId != calculatedBlockId { - utils.Logf("ERROR: block height %d, template id %s, expected %s", block.Side.Height, calculatedBlockId, expectedBlockId) + utils.Errorf("", "block height %d, template id %s, expected %s", block.Side.Height, calculatedBlockId, expectedBlockId) } else { blob, err := block.MarshalBinary() if err != nil { - log.Panic(err) + utils.Panic(err) } - utils.Logf("block height %d, template id %s, version %d", block.Side.Height, calculatedBlockId, block.ShareVersion()) + utils.Logf("", "block height %d, template id %s, version %d", block.Side.Height, calculatedBlockId, block.ShareVersion()) _ = os.WriteFile(path.Join(*outputFolder, expectedBlockId.String()+".raw"), blob, 0664) } diff --git a/cmd/recoverpoolblock/recoverpoolblock.go b/cmd/recoverpoolblock/recoverpoolblock.go index f941e5d..395fe40 100644 --- a/cmd/recoverpoolblock/recoverpoolblock.go +++ b/cmd/recoverpoolblock/recoverpoolblock.go @@ -23,7 +23,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "git.gammaspectra.live/P2Pool/sha3" "github.com/floatdrop/lru" - "log" "math" "os" "runtime" @@ -45,21 +44,21 @@ func main() { cf, err := os.ReadFile(*inputConsensus) if err != nil { - log.Panic(err) + utils.Panic(err) } inputTemplateData, err := os.ReadFile(*inputTemplate) if err != nil { - log.Panic(err) + utils.Panic(err) } jsonTemplate, err := JSONFromTemplate(inputTemplateData) if err != nil { - log.Panic(err) + utils.Panic(err) } consensus, err := sidechain.NewConsensusFromJSON(cf) if err != nil { - log.Panic(err) + utils.Panic(err) } var headerCacheLock sync.RWMutex @@ -103,7 +102,7 @@ func main() { archiveCache, err := archive.NewCache(*inputArchive, consensus, getDifficultyByHeight) if err != nil { - log.Panic(err) + utils.Panic(err) } defer archiveCache.Close() @@ -157,7 +156,7 @@ func main() { getTransactionsEntries := func(h ...types.Hash) (r mempool.Mempool) { if data, jsonTx, err := client.GetDefaultClient().GetTransactions(h...); err != nil { - utils.Logf("could not get txids: %s", err) + utils.Errorf("", "could not get txids: %s", err) return nil } else { r = make(mempool.Mempool, len(jsonTx)) @@ -214,7 +213,7 @@ func main() { headerId, _ := types.HashFromString(header.Hash) if b, err := client.GetDefaultClient().GetBlock(headerId, context.Background()); err != nil { - log.Panic(err) + utils.Panic(err) } else { //generalization, actual reward could be different in some cases ij, _ := b.InnerJSON() @@ -232,7 +231,7 @@ func main() { deltaReward = v2.CoinbaseReward - baseMainReward } - utils.Logf("pool delta reward: %d (%s), base %d (%s), expected %d (%s)", deltaReward, utils.XMRUnits(deltaReward), baseMainReward, utils.XMRUnits(baseMainReward), v2.CoinbaseReward, utils.XMRUnits(v2.CoinbaseReward)) + utils.Logf("", "pool delta reward: %d (%s), base %d (%s), expected %d (%s)", deltaReward, utils.XMRUnits(deltaReward), baseMainReward, utils.XMRUnits(baseMainReward), v2.CoinbaseReward, utils.XMRUnits(v2.CoinbaseReward)) poolBlock = &sidechain.PoolBlock{ Main: block.Block{ @@ -303,23 +302,23 @@ func main() { if bytes.Compare(poolBlock.CoinbaseExtra(sidechain.SideCoinbasePublicKey), kP.PublicKey.AsSlice()) == 0 && bytes.Compare(kP.PrivateKey.AsSlice(), poolBlock.Side.CoinbasePrivateKey[:]) == 0 { poolBlock.Side.CoinbasePrivateKeySeed = expectedSeed } else { - utils.Logf("not deterministic private key") + utils.Logf("", "not deterministic private key") } } currentOutputs, _ := sidechain.CalculateOutputs(poolBlock, consensus, getDifficultyByHeight, getByTemplateIdDirect, derivationCache, sidechain.PreAllocateShares(consensus.ChainWindowSize*2), make([]uint64, consensus.ChainWindowSize*2)) if currentOutputs == nil { - log.Panic("could not calculate outputs blob") + utils.Panicf("could not calculate outputs blob") } poolBlock.Main.Coinbase.Outputs = currentOutputs if blob, err := currentOutputs.MarshalBinary(); err != nil { - log.Panic(err) + utils.Panic(err) } else { poolBlock.Main.Coinbase.OutputsBlobSize = uint64(len(blob)) } - utils.Logf("expected main id %s, template id %s, coinbase id %s", expectedMainId, expectedTemplateId, expectedCoinbaseId) + utils.Logf("", "expected main id %s, template id %s, coinbase id %s", expectedMainId, expectedTemplateId, expectedCoinbaseId) rctHash := crypto.Keccak256([]byte{0}) type partialBlobWork struct { @@ -344,7 +343,7 @@ func main() { } w := coinbases[routineIndex] if workIndex%(1024*256) == 0 { - utils.Logf("try %d/%d @ %d ~%.2f%%", workIndex, max, nonceSize, (float64(workIndex)/math.MaxUint32)*100) + utils.Logf("", "try %d/%d @ %d ~%.2f%%", workIndex, max, nonceSize, (float64(workIndex)/math.MaxUint32)*100) } binary.LittleEndian.PutUint32(w.EncodedBuffer[w.EncodedOffset:], uint32(workIndex)) idHasher := w.Hashers[0] @@ -413,18 +412,18 @@ func main() { searchForNonces(nonceSize, math.MaxUint32) } - utils.Logf("found extra nonce %d, size %d", foundExtraNonce.Load(), foundExtraNonceSize.Load()) + utils.Logf("", "found extra nonce %d, size %d", foundExtraNonce.Load(), foundExtraNonceSize.Load()) poolBlock.Main.Coinbase.Extra[1].VarInt = uint64(foundExtraNonceSize.Load()) poolBlock.Main.Coinbase.Extra[1].Data = make([]byte, foundExtraNonceSize.Load()) binary.LittleEndian.PutUint32(poolBlock.Main.Coinbase.Extra[1].Data, foundExtraNonce.Load()) if poolBlock.Main.Coinbase.CalculateId() != expectedCoinbaseId { - log.Panic() + utils.Panic() } - utils.Logf("got coinbase id %s", poolBlock.Main.Coinbase.CalculateId()) + utils.Logf("", "got coinbase id %s", poolBlock.Main.Coinbase.CalculateId()) minerTxBlob, _ = poolBlock.Main.Coinbase.MarshalBinary() - utils.Logf("raw coinbase: %s", hex.EncodeToString(minerTxBlob)) + utils.Logf("", "raw coinbase: %s", hex.EncodeToString(minerTxBlob)) var collectedTransactions mempool.Mempool @@ -498,18 +497,18 @@ func main() { medianWeight := getHeaderByHeight(poolBlock.Main.Coinbase.GenHeight).LongTermWeight - utils.Logf("collected transaction candidates: %d", len(collectedTransactions)) + utils.Logf("", "collected transaction candidates: %d", len(collectedTransactions)) if totalTxWeight+minerTxWeight <= medianWeight { //special case for solution := range collectedTransactions.PerfectSum(deltaReward) { - utils.Logf("got %d, %d (%s)", solution.Weight(), solution.Fees(), utils.XMRUnits(solution.Fees())) + utils.Logf("", "got %d, %d (%s)", solution.Weight(), solution.Fees(), utils.XMRUnits(solution.Fees())) } } else { //sort in preference order pickedTxs := collectedTransactions.Pick(baseMainReward, minerTxWeight, medianWeight) - utils.Logf("got %d, %d (%s)", pickedTxs.Weight(), pickedTxs.Fees(), utils.XMRUnits(pickedTxs.Fees())) + utils.Logf("", "got %d, %d (%s)", pickedTxs.Weight(), pickedTxs.Fees(), utils.XMRUnits(pickedTxs.Fees())) } //TODO: nonce diff --git a/cmd/scansweeps/scansweeps.go b/cmd/scansweeps/scansweeps.go index 300858d..440761c 100644 --- a/cmd/scansweeps/scansweeps.go +++ b/cmd/scansweeps/scansweeps.go @@ -9,7 +9,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/monero/client" p2poolapi "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/api" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "time" ) @@ -28,12 +27,12 @@ func main() { p2api := p2poolapi.NewP2PoolApi(*p2poolApiHost) if err := p2api.WaitSync(); err != nil { - log.Panic(err) + utils.Panic(err) } indexDb, err := index.OpenIndex(*dbString, p2api.Consensus(), p2api.DifficultyByHeight, p2api.SeedByHeight, p2api.ByTemplateId) if err != nil { - log.Panic(err) + utils.Panic(err) } defer indexDb.Close() @@ -52,7 +51,7 @@ func main() { } return nil }); err != nil { - log.Panic(err) + utils.Panic(err) } stopHeight := tipHeight - monero.MinerRewardUnlockTime @@ -60,25 +59,25 @@ func main() { stopHeight = tipHeight } - utils.Logf("Starting at height %d, stopping at %d", startHeight, stopHeight) + utils.Logf("", "Starting at height %d, stopping at %d", startHeight, stopHeight) isProcessedPrevious := true for height := startHeight; height <= stopHeight; height++ { b := indexDb.GetMainBlockByHeight(height) if b == nil { - utils.Logf("Block at %d is nil", height) + utils.Logf("", "Block at %d is nil", height) continue } if isProcessed, ok := b.GetMetadata("processed").(bool); ok && isProcessed && isProcessedPrevious { - utils.Logf("Block %s at %d (%s) has already been processed", b.Id, b.Height, time.Unix(int64(b.Timestamp), 0).UTC().Format("02-01-2006 15:04:05 MST")) + utils.Logf("", "Block %s at %d (%s) has already been processed", b.Id, b.Height, time.Unix(int64(b.Timestamp), 0).UTC().Format("02-01-2006 15:04:05 MST")) continue } isProcessedPrevious = false if err := cmdutils.ProcessFullBlock(b, indexDb); err != nil { - utils.Logf("error processing block %s at %d: %s", b.Id, b.Height, err) + utils.Logf("", "error processing block %s at %d: %s", b.Id, b.Height, err) } } diff --git a/cmd/utils/coinbase.go b/cmd/utils/coinbase.go index 4616eee..8180b01 100644 --- a/cmd/utils/coinbase.go +++ b/cmd/utils/coinbase.go @@ -15,7 +15,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/floatdrop/lru" - "log" "math" ) @@ -88,11 +87,11 @@ func FindAndInsertMainHeader(h daemon.BlockHeader, indexDb *index.Index, storeFu return nil } - utils.Logf("checking block %s at height %d: %d candidate(s)", mainId, h.Height, len(candidates)) + utils.Logf("Monero", "checking block %s at height %d: %d candidate(s)", mainId, h.Height, len(candidates)) mainBlock, err := GetMainBlock(mainId, client) if err != nil { - utils.Logf("could not get main block: %e", err) + utils.Errorf("Monero", "could not get main block: %e", err) // insert errored block as-is if err := indexDb.InsertOrUpdateMainBlock(indexMain); err != nil { return err @@ -121,7 +120,7 @@ func FindAndInsertMainHeader(h daemon.BlockHeader, indexDb *index.Index, storeFu } if sideTemplateId == types.ZeroHash || len(extraNonce) == 0 { - utils.Logf("checking block %s at height %d: not a p2pool block", mainId, h.Height) + utils.Logf("Monero", "checking block %s at height %d: not a p2pool block", mainId, h.Height) if err := indexDb.InsertOrUpdateMainBlock(indexMain); err != nil { return err } @@ -189,16 +188,16 @@ func FindAndInsertMainHeader(h daemon.BlockHeader, indexDb *index.Index, storeFu if err := indexDb.InsertOrUpdateMainBlock(indexMain); err != nil { return err } - utils.Logf("INSERTED found block %s at height %d, template id %s", mainId, h.Height, sideTemplateId) + utils.Logf("Monero", "INSERTED found block %s at height %d, template id %s", mainId, h.Height, sideTemplateId) if err := FindAndInsertMainHeaderOutputs(indexMain, indexDb, client, difficultyByHeight, getByTemplateId, getByMainId, getByMainHeight, processBlock); err != nil { - utils.Logf("error inserting coinbase outputs: %s", err) + utils.Errorf("", "error inserting coinbase outputs: %s", err) } return nil } else { data, _ := t.MarshalBinary() newBlock := &sidechain.PoolBlock{} if err := newBlock.UnmarshalBinary(indexDb.Consensus(), &sidechain.NilDerivationCache{}, data); err != nil { - log.Panic(err) + utils.Panic(err) } copy(newBlock.CoinbaseExtra(sidechain.SideExtraNonce), extraNonce) newBlock.Main.Nonce = uint32(h.Nonce) @@ -227,16 +226,16 @@ func FindAndInsertMainHeader(h daemon.BlockHeader, indexDb *index.Index, storeFu if err := indexDb.InsertOrUpdateMainBlock(indexMain); err != nil { return err } - utils.Logf("INSERTED ALTERNATE found block %s at height %d, template id %s", mainId, h.Height, sideTemplateId) + utils.Logf("", "INSERTED ALTERNATE found block %s at height %d, template id %s", mainId, h.Height, sideTemplateId) if err := FindAndInsertMainHeaderOutputs(indexMain, indexDb, client, difficultyByHeight, getByTemplateId, getByMainId, getByMainHeight, processBlock); err != nil { - utils.Logf("error inserting coinbase outputs: %s", err) + utils.Errorf("", "error inserting coinbase outputs: %s", err) } return nil } } } - utils.Logf("checking block %s at height %d, template id %s: could not find matching template id", mainId, h.Height, sideTemplateId) + utils.Logf("", "checking block %s at height %d, template id %s: could not find matching template id", mainId, h.Height, sideTemplateId) // could not find template, maybe it's other pool? @@ -254,7 +253,7 @@ func FindAndInsertMainHeader(h daemon.BlockHeader, indexDb *index.Index, storeFu func FindAndInsertMainHeaderOutputs(mb *index.MainBlock, indexDb *index.Index, client *client.Client, difficultyByHeight block.GetDifficultyByHeightFunc, getByTemplateId sidechain.GetByTemplateIdFunc, getByMainId sidechain.GetByMainIdFunc, getByMainHeight sidechain.GetByMainHeightFunc, processBlock func(b *sidechain.PoolBlock) error) error { if !index.QueryHasResults(indexDb.GetMainCoinbaseOutputs(mb.CoinbaseId)) { //fill information - utils.Logf("inserting coinbase outputs for %s, template id %s, coinbase id %s", mb.Id, mb.SideTemplateId, mb.CoinbaseId) + utils.Logf("", "inserting coinbase outputs for %s, template id %s, coinbase id %s", mb.Id, mb.SideTemplateId, mb.CoinbaseId) var t *sidechain.PoolBlock if t = getByTemplateId(mb.SideTemplateId); t == nil || t.MainId() != mb.Id { t = nil diff --git a/cmd/utils/transaction_lookup.go b/cmd/utils/transaction_lookup.go index c674cd9..5d38e36 100644 --- a/cmd/utils/transaction_lookup.go +++ b/cmd/utils/transaction_lookup.go @@ -127,7 +127,7 @@ func ProcessFullBlock(b *index.MainBlock, indexDb *index.Index) error { return fmt.Errorf("could not get main block for %s at %d: %w", b.Id, b.Height, err) } - utils.Logf("Block %s at %d (%s), processing %d transactions", b.Id, b.Height, time.Unix(int64(b.Timestamp), 0).UTC().Format("02-01-2006 15:04:05 MST"), len(mainBlock.Transactions)) + utils.Logf("", "Block %s at %d (%s), processing %d transactions", b.Id, b.Height, time.Unix(int64(b.Timestamp), 0).UTC().Format("02-01-2006 15:04:05 MST"), len(mainBlock.Transactions)) // try to fetch extra nonce if existing { @@ -150,7 +150,7 @@ func ProcessFullBlock(b *index.MainBlock, indexDb *index.Index) error { if sideTemplateId != types.ZeroHash && len(extraNonce) != 0 { b.SetMetadata("merge_mining_tag", sideTemplateId) b.SetMetadata("extra_nonce", binary.LittleEndian.Uint32(extraNonce)) - utils.Logf("p2pool tags found template id %s, extra nonce %d", sideTemplateId, binary.LittleEndian.Uint32(extraNonce)) + utils.Logf("", "p2pool tags found template id %s, extra nonce %d", sideTemplateId, binary.LittleEndian.Uint32(extraNonce)) } const txInputThreshold = 4 @@ -217,7 +217,7 @@ func ProcessFullBlock(b *index.MainBlock, indexDb *index.Index) error { } if likelyMiner { - utils.Logf("transaction %s is LIKELY for %s: miner ratio %.02f (%d/%d), none %.02f (%d/%d), other %.02f (%d/%d); coinbase %d, sweep %d", txId, topMiner.Address.ToBase58(), minerRatio, minerCount, len(inputs), noMinerRatio, noMinerCount, len(inputs), otherMinerRatio, otherMinerCount, len(inputs), topMiner.CoinbaseCount, topMiner.SweepCount) + utils.Logf("", "transaction %s is LIKELY for %s: miner ratio %.02f (%d/%d), none %.02f (%d/%d), other %.02f (%d/%d); coinbase %d, sweep %d", txId, topMiner.Address.ToBase58(), minerRatio, minerCount, len(inputs), noMinerRatio, noMinerCount, len(inputs), otherMinerRatio, otherMinerCount, len(inputs), topMiner.CoinbaseCount, topMiner.SweepCount) minimalInputs := make(index.MinimalTransactionInputQueryResults, len(inputs)) @@ -273,10 +273,10 @@ func ProcessFullBlock(b *index.MainBlock, indexDb *index.Index) error { return err } } else { - utils.Logf("transaction %s is NOT likely for %s: miner ratio %.02f (%d/%d), none %.02f (%d/%d), other %.02f (%d/%d); coinbase %d, sweep %d", txId, topMiner.Address.ToBase58(), minerRatio, topMiner.Count, len(inputs), noMinerRatio, noMinerCount, len(inputs), otherMinerRatio, otherMinerCount, len(inputs), topMiner.CoinbaseCount, topMiner.SweepCount) + utils.Logf("", "transaction %s is NOT likely for %s: miner ratio %.02f (%d/%d), none %.02f (%d/%d), other %.02f (%d/%d); coinbase %d, sweep %d", txId, topMiner.Address.ToBase58(), minerRatio, topMiner.Count, len(inputs), noMinerRatio, noMinerCount, len(inputs), otherMinerRatio, otherMinerCount, len(inputs), topMiner.CoinbaseCount, topMiner.SweepCount) } } else { - //utils.Logf("transaction %s does not have enough matches, %d outputs", txId, len(inputs)) + //utils.Logf("", "transaction %s does not have enough matches, %d outputs", txId, len(inputs)) } } } diff --git a/cmd/web/web.go b/cmd/web/web.go index ac15751..44cbfd4 100644 --- a/cmd/web/web.go +++ b/cmd/web/web.go @@ -18,7 +18,6 @@ import ( "github.com/gorilla/mux" "github.com/valyala/quicktemplate" "io" - "log" "math" "net/http" _ "net/http/pprof" @@ -130,8 +129,6 @@ func main() { return make([]byte, 0, 1024*1024) //1 MiB allocations } - log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) - //monerod related moneroHost := flag.String("host", "127.0.0.1", "IP address of your Monero node") moneroRpcPort := flag.Uint("rpc-port", 18081, "monerod RPC API port number") @@ -194,10 +191,10 @@ func main() { consensusData, _ := utils.MarshalJSON(basePoolInfo.SideChain.Consensus) consensus, err := sidechain.NewConsensusFromJSON(consensusData) if err != nil { - log.Panic(err) + utils.Panic(err) } - utils.Logf("Consensus id = %s", consensus.Id) + utils.Logf("Consensus", "Consensus id = %s", consensus.Id) var lastPoolInfo atomic.Pointer[cmdutils.PoolInfoResult] @@ -1253,12 +1250,12 @@ func main() { if *debugListen != "" { go func() { if err := http.ListenAndServe(*debugListen, nil); err != nil { - log.Panic(err) + utils.Panic(err) } }() } if err := server.ListenAndServe(); err != nil { - log.Panic(err) + utils.Panic(err) } } diff --git a/monero/address/address_test.go b/monero/address/address_test.go index 3bcc245..b1b5b22 100644 --- a/monero/address/address_test.go +++ b/monero/address/address_test.go @@ -6,7 +6,7 @@ import ( "git.gammaspectra.live/P2Pool/edwards25519" "git.gammaspectra.live/P2Pool/p2pool-observer/monero/crypto" "git.gammaspectra.live/P2Pool/p2pool-observer/types" - "log" + "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "sync/atomic" "testing" ) @@ -22,7 +22,7 @@ var ephemeralPubKey, _ = hex.DecodeString("20efc1310db960b0e8d22c8b85b3414fcaa1e func init() { h, _ := hex.DecodeString("74b98b1e7ce5fc50d1634f8634622395ec2a19a4698a016fedd8139df374ac00") if _, err := privateKey.SetCanonicalBytes(h); err != nil { - log.Panic(err) + utils.Panic(err) } } diff --git a/monero/client/client.go b/monero/client/client.go index 36e99e6..3be7452 100644 --- a/monero/client/client.go +++ b/monero/client/client.go @@ -9,8 +9,8 @@ import ( "git.gammaspectra.live/P2Pool/go-monero/pkg/rpc/daemon" "git.gammaspectra.live/P2Pool/p2pool-observer/monero/transaction" "git.gammaspectra.live/P2Pool/p2pool-observer/types" + "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/floatdrop/lru" - "log" "sync" "sync/atomic" "time" @@ -39,7 +39,7 @@ func GetDefaultClient() *Client { if c = client.Load(); c == nil { //fallback for lock racing if c, err := NewClient(address); err != nil { - log.Panic(err) + utils.Panic(err) } else { client.Store(c) return c diff --git a/monero/randomx/randomx_cgo.go b/monero/randomx/randomx_cgo.go index 716c548..44788b1 100644 --- a/monero/randomx/randomx_cgo.go +++ b/monero/randomx/randomx_cgo.go @@ -170,7 +170,7 @@ func (h *hasherState) Init(key []byte) (err error) { h.key = make([]byte, len(key)) copy(h.key, key) - utils.Logf("[RandomX] Initializing to seed %s", hex.EncodeToString(h.key)) + utils.Logf("RandomX", "Initializing to seed %s", hex.EncodeToString(h.key)) if h.dataset.GoInit(h.key, uint32(runtime.NumCPU())) == false { return errors.New("could not initialize dataset") } @@ -182,7 +182,7 @@ func (h *hasherState) Init(key []byte) (err error) { return err } - utils.Logf("[RandomX] Initialized to seed %s", hex.EncodeToString(h.key)) + utils.Logf("RandomX", "Initialized to seed %s", hex.EncodeToString(h.key)) return nil } diff --git a/p2pool/api/p2poolapi.go b/p2pool/api/p2poolapi.go index e73b859..d0a39e7 100644 --- a/p2pool/api/p2poolapi.go +++ b/p2pool/api/p2poolapi.go @@ -47,14 +47,14 @@ func (p *P2PoolApi) WaitSync() (err error) { status := p.Status() for ; p == nil || !p.Status().Synchronized; status = p.Status() { if p == nil { - utils.Logf("[API] Not synchronized (nil), waiting five seconds") + utils.Logf("API", "Not synchronized (nil), waiting five seconds") } else { - utils.Logf("[API] Not synchronized (height %d, id %s, blocks %d), waiting five seconds", status.Height, status.Id, status.Blocks) + utils.Logf("API", "Not synchronized (height %d, id %s, blocks %d), waiting five seconds", status.Height, status.Id, status.Blocks) } time.Sleep(time.Second * 5) } - utils.Logf("[API] SYNCHRONIZED (height %d, id %s, blocks %d)", status.Height, status.Id, status.Blocks) - utils.Logf("[API] Consensus id = %s\n", p.Consensus().Id) + utils.Logf("API", "SYNCHRONIZED (height %d, id %s, blocks %d)", status.Height, status.Id, status.Blocks) + utils.Logf("API", "Consensus id = %s\n", p.Consensus().Id) return nil } @@ -67,17 +67,17 @@ func (p *P2PoolApi) WaitSyncStart() (err error) { status := p.Status() for ; p == nil || !p.Status().Synchronized; status = p.Status() { if p == nil { - utils.Logf("[API] Not synchronized (nil), waiting one seconds") + utils.Logf("API", "Not synchronized (nil), waiting one seconds") } else { - utils.Logf("[API] Not synchronized (height %d, id %s, blocks %d)", status.Height, status.Id, status.Blocks) + utils.Logf("API", "Not synchronized (height %d, id %s, blocks %d)", status.Height, status.Id, status.Blocks) break } time.Sleep(time.Second * 1) } if status.Synchronized { - utils.Logf("[API] SYNCHRONIZED (height %d, id %s, blocks %d)", status.Height, status.Id, status.Blocks) + utils.Logf("API", "SYNCHRONIZED (height %d, id %s, blocks %d)", status.Height, status.Id, status.Blocks) } - utils.Logf("[API] Consensus id = %s\n", p.Consensus().Id) + utils.Logf("API", "Consensus id = %s\n", p.Consensus().Id) return nil } diff --git a/p2pool/cache/archive/archive.go b/p2pool/cache/archive/archive.go index ee90ace..80a1b07 100644 --- a/p2pool/cache/archive/archive.go +++ b/p2pool/cache/archive/archive.go @@ -9,7 +9,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" bolt "go.etcd.io/bbolt" - "log" "math" "slices" "time" @@ -85,7 +84,7 @@ func (c *Cache) Store(block *sidechain.PoolBlock) { sideId := block.SideTemplateId(c.consensus) if bytes.Compare(sideId[:], block.CoinbaseExtra(sidechain.SideTemplateId)) != 0 { //wrong calculated template id - log.Panicf("wrong template id, expected %s, got %s", types.HashFromBytes(block.CoinbaseExtra(sidechain.SideTemplateId)), sideId) + utils.Panicf("wrong template id, expected %s, got %s", types.HashFromBytes(block.CoinbaseExtra(sidechain.SideTemplateId)), sideId) return } mainId := block.MainId() @@ -123,7 +122,7 @@ func (c *Cache) Store(block *sidechain.PoolBlock) { } if blob, err := block.AppendBinaryFlags(make([]byte, 0, block.BufferLength()), storePruned, storeCompact); err == nil { - utils.Logf("[Archive Cache] Store block id = %s, template id = %s, height = %d, sidechain height = %d, depth = %d, pruned = %t, compact = %t, blob size = %d bytes", mainId.String(), sideId.String(), block.Main.Coinbase.GenHeight, block.Side.Height, block.Depth.Load(), storePruned, storeCompact, len(blob)) + utils.Logf("Archive Cache", "Store block id = %s, template id = %s, height = %d, sidechain height = %d, depth = %d, pruned = %t, compact = %t, blob size = %d bytes", mainId.String(), sideId.String(), block.Main.Coinbase.GenHeight, block.Side.Height, block.Depth.Load(), storePruned, storeCompact, len(blob)) if err = c.db.Update(func(tx *bolt.Tx) error { b1 := tx.Bucket(blocksByMainId) @@ -164,7 +163,7 @@ func (c *Cache) Store(block *sidechain.PoolBlock) { } return nil }); err != nil { - utils.Logf("[Archive Cache] bolt error: %s", err) + utils.Logf("Archive Cache", "bolt error: %s", err) } } } @@ -216,12 +215,12 @@ func (c *Cache) decodeBlock(blob []byte) *sidechain.PoolBlock { reader := bytes.NewReader(blob[8:]) if (flags & 0b10) > 0 { if err := b.FromCompactReader(c.consensus, c.derivationCache, reader); err != nil { - utils.Logf("[Archive Cache] error decoding block: %s", err) + utils.Logf("Archive Cache", "error decoding block: %s", err) return nil } } else { if err := b.FromReader(c.consensus, c.derivationCache, reader); err != nil { - utils.Logf("[Archive Cache] error decoding block: %s", err) + utils.Logf("Archive Cache", "error decoding block: %s", err) return nil } } @@ -261,7 +260,7 @@ func (c *Cache) LoadByTemplateId(id types.Hash) (result sidechain.UniquePoolBloc } return nil }); err != nil { - utils.Logf("[Archive Cache] error fetching blocks with template id %s, %s", id.String(), err) + utils.Logf("Archive Cache", "error fetching blocks with template id %s, %s", id.String(), err) return nil } for _, buf := range blocks { @@ -366,7 +365,7 @@ func (c *Cache) LoadBySideChainHeight(height uint64) (result sidechain.UniquePoo } return nil }); err != nil { - utils.Logf("[Archive Cache] error fetching blocks with sidechain height %d, %s", height, err) + utils.Logf("Archive Cache", "error fetching blocks with sidechain height %d, %s", height, err) return nil } for _, buf := range blocks { @@ -393,7 +392,7 @@ func (c *Cache) LoadByMainChainHeight(height uint64) (result sidechain.UniquePoo } return nil }); err != nil { - utils.Logf("[Archive Cache] error fetching blocks with sidechain height %d, %s", height, err) + utils.Logf("Archive Cache", "error fetching blocks with sidechain height %d, %s", height, err) return nil } for _, buf := range blocks { diff --git a/p2pool/cache/legacy/legacy.go b/p2pool/cache/legacy/legacy.go index 5bcb449..7f8a7a4 100644 --- a/p2pool/cache/legacy/legacy.go +++ b/p2pool/cache/legacy/legacy.go @@ -6,7 +6,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/sidechain" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "io" - "log" "os" "sync" "sync/atomic" @@ -68,7 +67,7 @@ func (c *Cache) LoadAll(l cache.Loadee) { c.loadingStarted.Do(func() { c.loadingInProgress.Store(true) defer c.loadingInProgress.Store(false) - log.Print("[Cache] Loading cached blocks") + utils.Logf("Cache", "Loading cached blocks") var blobLen [4]byte buf := make([]byte, 0, blockSize) @@ -102,7 +101,7 @@ func (c *Cache) LoadAll(l cache.Loadee) { blocksLoaded++ } - utils.Logf("[Cache] Loaded %d cached blocks", blocksLoaded) + utils.Logf("Cache", "Loaded %d cached blocks", blocksLoaded) }) } diff --git a/p2pool/mainchain/mainchain.go b/p2pool/mainchain/mainchain.go index d95f594..6ead2b8 100644 --- a/p2pool/mainchain/mainchain.go +++ b/p2pool/mainchain/mainchain.go @@ -210,7 +210,7 @@ func (c *MainChain) updateMedianTimestamp() { // Shift it +1 block compared to Monero's code because we don't have the latest block yet when we receive new miner data ts := (timestamps[TimestampWindow/2] + timestamps[TimestampWindow/2+1]) / 2 - utils.Logf("[MainChain] Median timestamp updated to %d", ts) + utils.Logf("MainChain", "Median timestamp updated to %d", ts) c.medianTimestamp.Store(ts) } @@ -232,7 +232,7 @@ func (c *MainChain) HandleMainHeader(mainHeader *mainblock.Header) { c.highest = mainData.Height } - utils.Logf("[MainChain] new main chain block: height = %d, id = %s, timestamp = %d, reward = %s", mainData.Height, mainData.Id.String(), mainData.Timestamp, utils.XMRUnits(mainData.Reward)) + utils.Logf("MainChain", "new main chain block: height = %d, id = %s, timestamp = %d, reward = %s", mainData.Height, mainData.Id.String(), mainData.Timestamp, utils.XMRUnits(mainData.Reward)) c.updateMedianTimestamp() } @@ -262,7 +262,7 @@ func (c *MainChain) HandleMainBlock(b *mainblock.Block) { c.highest = mainData.Height } - utils.Logf("[MainChain] new main chain block: height = %d, id = %s, timestamp = %d, reward = %s", mainData.Height, mainData.Id.String(), mainData.Timestamp, utils.XMRUnits(mainData.Reward)) + utils.Logf("MainChain", "new main chain block: height = %d, id = %s, timestamp = %d, reward = %s", mainData.Height, mainData.Id.String(), mainData.Timestamp, utils.XMRUnits(mainData.Reward)) c.updateMedianTimestamp() }() @@ -389,7 +389,7 @@ func (c *MainChain) DownloadBlockHeaders(currentHeight uint64) error { Difficulty: types.DifficultyFrom64(header.Difficulty), }) } - utils.Logf("[MainChain] Downloaded headers for range %d to %d", startHeight, currentHeight-1) + utils.Logf("MainChain", "Downloaded headers for range %d to %d", startHeight, currentHeight-1) } c.updateMedianTimestamp() @@ -437,7 +437,7 @@ func (c *MainChain) HandleMinerData(minerData *p2pooltypes.MinerData) { c.updateMedianTimestamp() - utils.Logf("[MainChain] new miner data: major_version = %d, height = %d, prev_id = %s, seed_hash = %s, difficulty = %s", minerData.MajorVersion, minerData.Height, minerData.PrevId.String(), minerData.SeedHash.String(), minerData.Difficulty.StringNumeric()) + utils.Logf("MainChain", "new miner data: major_version = %d, height = %d, prev_id = %s, seed_hash = %s, difficulty = %s", minerData.MajorVersion, minerData.Height, minerData.PrevId.String(), minerData.SeedHash.String(), minerData.Difficulty.StringNumeric()) // Tx secret keys from all miners change every block, so cache can be cleared here if c.sidechain.PreCalcFinished() { @@ -447,7 +447,7 @@ func (c *MainChain) HandleMinerData(minerData *p2pooltypes.MinerData) { if c.p2pool.Started() { for h := minerData.Height; h > 0 && (h+BlockHeadersRequired) > minerData.Height; h-- { if d, ok := c.mainchainByHeight.Get(h); !ok || d.Difficulty.Equals(types.ZeroDifficulty) { - utils.Logf("[MainChain] Main chain data for height = %d is missing, requesting from monerod again", h) + utils.Logf("MainChain", "Main chain data for height = %d is missing, requesting from monerod again", h) missingHeights = append(missingHeights, h) } } @@ -462,7 +462,7 @@ func (c *MainChain) HandleMinerData(minerData *p2pooltypes.MinerData) { go func(height uint64) { wg.Done() if err := c.getBlockHeader(height); err != nil { - utils.Logf("[MainChain] %s", err) + utils.Errorf("MainChain", "%s", err) } }(h) } diff --git a/p2pool/mempool/mempool.go b/p2pool/mempool/mempool.go index a61c3c5..1ebb70c 100644 --- a/p2pool/mempool/mempool.go +++ b/p2pool/mempool/mempool.go @@ -109,7 +109,7 @@ func (m Mempool) perfectSumRecursion(c chan Mempool, targetFee uint64, i int, cu if currentSum < targetFee && i < len(m) { if top != nil && *top < i { *top = i - utils.Logf("index %d/%d", i, len(m)) + utils.Logf("Mempool", "index %d/%d", i, len(m)) } m3 := append(m2, m[i]) m.perfectSumRecursion(c, targetFee, i+1, currentSum+m[i].Fee, nil, m3) diff --git a/p2pool/p2p/client.go b/p2pool/p2p/client.go index 151b78a..9f25137 100644 --- a/p2pool/p2p/client.go +++ b/p2pool/p2p/client.go @@ -136,7 +136,7 @@ func (c *Client) Ban(duration time.Duration, err error) { func (c *Client) OnAfterHandshake() { c.SendListenPort() c.SendBlockRequest(types.ZeroHash) - utils.Logf("[P2PClient] Peer %s after handshake complete: sent LISTEN_PORT + tip BLOCK_REQUEST", c.AddressPort.String()) + utils.Logf("P2PClient", "Peer %s after handshake complete: sent LISTEN_PORT + tip BLOCK_REQUEST", c.AddressPort.String()) c.LastBroadcastTimestamp.Store(uint64(time.Now().Unix())) } @@ -163,7 +163,7 @@ func (c *Client) SendMissingBlockRequestAtRandom(hash types.Hash, allowedClients } if b := c.Owner.GetCachedBlock(hash); b != nil { - utils.Logf("[P2PClient] Using cached block for id = %s", hash.String()) + utils.Logf("P2PClient", "Using cached block for id = %s", hash.String()) if _, err, _ := c.Owner.SideChain().AddPoolBlockExternal(b); err == nil { return allowedClients } @@ -192,7 +192,7 @@ func (c *Client) SendMissingBlockRequest(hash types.Hash) { } if b := c.Owner.GetCachedBlock(hash); b != nil { - utils.Logf("[P2PClient] Using cached block for id = %s", hash.String()) + utils.Logf("P2PClient", "Using cached block for id = %s", hash.String()) if missingBlocks, err, _ := c.Owner.SideChain().AddPoolBlockExternal(b); err == nil { for _, id := range missingBlocks { c.SendMissingBlockRequest(id) @@ -258,7 +258,7 @@ func (c *Client) SendBlockResponse(block *sidechain.PoolBlock) { if block != nil { blockData, err := block.AppendBinaryFlags(make([]byte, 0, block.BufferLength()), false, false) if err != nil { - utils.Logf("[P2PClient] Peer %s tried to respond with a block but received error, disconnecting: %s", c.AddressPort, err) + utils.Logf("P2PClient", "Peer %s tried to respond with a block but received error, disconnecting: %s", c.AddressPort, err) c.Close() return } @@ -282,7 +282,7 @@ func (c *Client) SendPeerListRequest() { MessageId: MessagePeerListRequest, }) c.LastPeerListRequestTimestamp.Store(uint64(time.Now().UnixMicro())) - //utils.Logf("[P2PClient] Sending PEER_LIST_REQUEST to %s", c.AddressPort.String()) + //utils.Logf("P2PClient", "Sending PEER_LIST_REQUEST to %s", c.AddressPort.String()) } func (c *Client) SendPeerListResponse(list []netip.AddrPort) { @@ -373,7 +373,7 @@ func (c *Client) OnConnection() { c.HandshakeComplete.Store(true) c.SetError(fmt.Errorf("already connected as %s (%d)", otherClient.AddressPort, otherClient.PeerId.Load())) //same peer - utils.Logf("[P2PClient] Connected to other same peer: %s (%d) is also %s (%d)", c.AddressPort, c.PeerId.Load(), otherClient.AddressPort, otherClient.PeerId.Load()) + utils.Logf("P2PClient", "Connected to other same peer: %s (%d) is also %s (%d)", c.AddressPort, c.PeerId.Load(), otherClient.AddressPort, otherClient.PeerId.Load()) c.Close() return } @@ -457,7 +457,7 @@ func (c *Client) OnConnection() { var block *sidechain.PoolBlock //if empty, return chain tip if templateId == types.ZeroHash { - utils.Logf("[P2PClient] Peer %s requested tip", c.AddressPort.String()) + utils.Logf("P2PClient", "Peer %s requested tip", c.AddressPort.String()) // Don't return stale chain tip if block = c.Owner.SideChain().GetChainTip(); block != nil && (block.Main.Coinbase.GenHeight+2) < c.Owner.MainChain().GetMinerDataTip().Height { block = nil @@ -465,9 +465,9 @@ func (c *Client) OnConnection() { } else { block = c.Owner.SideChain().GetPoolBlockByTemplateId(templateId) if block == nil { - utils.Logf("[P2PClient] Peer %s requested id = %s, got nil", c.AddressPort.String(), templateId) + utils.Logf("P2PClient", "Peer %s requested id = %s, got nil", c.AddressPort.String(), templateId) } else { - utils.Logf("[P2PClient] Peer %s requested id = %s, got height = %d, main height = %d", c.AddressPort.String(), templateId, block.Side.Height, block.Main.Coinbase.GenHeight) + utils.Logf("P2PClient", "Peer %s requested id = %s, got height = %d, main height = %d", c.AddressPort.String(), templateId, block.Side.Height, block.Main.Coinbase.GenHeight) } } @@ -502,7 +502,7 @@ func (c *Client) OnConnection() { c.Ban(DefaultBanTime, err) return } else if blockSize == 0 { - utils.Logf("[P2PClient] Peer %s sent nil BLOCK_RESPONSE to id = %s", c.AddressPort.String(), expectedBlockId) + utils.Logf("P2PClient", "Peer %s sent nil BLOCK_RESPONSE to id = %s", c.AddressPort.String(), expectedBlockId) if isChainTipBlockRequest && time.Now().Unix() >= int64(c.NextOutgoingPeerListRequestTimestamp.Load()) { c.SendPeerListRequest() } @@ -521,7 +521,7 @@ func (c *Client) OnConnection() { } } - utils.Logf("[P2PClient] Peer %s tip is at id = %s, height = %d, main height = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight) + utils.Logf("P2PClient", "Peer %s tip is at id = %s, height = %d, main height = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight) peerHeight := block.Main.Coinbase.GenHeight ourHeight := c.Owner.MainChain().GetMinerDataTip().Height @@ -545,7 +545,7 @@ func (c *Client) OnConnection() { } } if c.Owner.SideChain().BlockSeen(block) { - //utils.Logf("[P2PClient] Peer %s block id = %s, height = %d (nonce %d, extra_nonce %d) was received before, skipping it", c.AddressPort.String(), types.HashFromBytes(block.CoinbaseExtra(sidechain.SideTemplateId)), block.Side.Height, block.Main.Nonce, block.ExtraNonce()) + //utils.Logf("P2PClient", "Peer %s block id = %s, height = %d (nonce %d, extra_nonce %d) was received before, skipping it", c.AddressPort.String(), types.HashFromBytes(block.CoinbaseExtra(sidechain.SideTemplateId)), block.Side.Height, block.Main.Nonce, block.ExtraNonce()) break } if missingBlocks, err, ban := c.Owner.SideChain().AddPoolBlockExternal(block); err != nil { @@ -553,7 +553,7 @@ func (c *Client) OnConnection() { c.Ban(DefaultBanTime, err) return } else { - utils.Logf("[P2PClient] Peer %s error adding block id = %s, height = %d, main height = %d, timestamp = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight, block.Main.Timestamp) + utils.Logf("P2PClient", "Peer %s error adding block id = %s, height = %d, main height = %d, timestamp = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight, block.Main.Timestamp) break } } else { @@ -611,7 +611,7 @@ func (c *Client) OnConnection() { c.LastBroadcastTimestamp.Store(uint64(time.Now().Unix())) - //utils.Logf("[P2PClient] Peer %s broadcast tip is at id = %s, height = %d, main height = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight) + //utils.Logf("P2PClient", "Peer %s broadcast tip is at id = %s, height = %d, main height = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight) if missingBlocks, err := c.Owner.SideChain().PreprocessBlock(block); err != nil { for _, id := range missingBlocks { @@ -636,7 +636,7 @@ func (c *Client) OnConnection() { if (ourHeight - peerHeight) < 5 { elapsedTime := time.Now().Sub(ourMinerData.TimeReceived) if (ourHeight-peerHeight) > 1 || elapsedTime > (time.Second*10) { - utils.Logf("[P2PClient] Peer %s broadcasted a stale block (%d ms late, mainchain height %d, expected >= %d), ignoring it", c.AddressPort.String(), elapsedTime.Milliseconds(), peerHeight, ourHeight) + utils.Logf("P2PClient", "Peer %s broadcasted a stale block (%d ms late, mainchain height %d, expected >= %d), ignoring it", c.AddressPort.String(), elapsedTime.Milliseconds(), peerHeight, ourHeight) } } else { c.Ban(DefaultBanTime, fmt.Errorf("broadcasted an unreasonably stale block (mainchain height %d, expected >= %d)", peerHeight, ourHeight)) @@ -644,15 +644,15 @@ func (c *Client) OnConnection() { } } else if peerHeight > ourHeight { if peerHeight >= (ourHeight + 2) { - utils.Logf("[P2PClient] Peer %s is ahead on mainchain (mainchain height %d, your height %d). Is monerod stuck or lagging?", c.AddressPort.String(), peerHeight, ourHeight) + utils.Logf("P2PClient", "Peer %s is ahead on mainchain (mainchain height %d, your height %d). Is monerod stuck or lagging?", c.AddressPort.String(), peerHeight, ourHeight) } } else { - utils.Logf("[P2PClient] Peer %s is mining on an alternative mainchain tip (mainchain height %d, previous_id = %s)", c.AddressPort.String(), peerHeight, block.Main.PreviousId) + utils.Logf("P2PClient", "Peer %s is mining on an alternative mainchain tip (mainchain height %d, previous_id = %s)", c.AddressPort.String(), peerHeight, block.Main.PreviousId) } } if c.Owner.SideChain().BlockSeen(block) { - //utils.Logf("[P2PClient] Peer %s block id = %s, height = %d (nonce %d, extra_nonce %d) was received before, skipping it", c.AddressPort.String(), types.HashFromBytes(block.CoinbaseExtra(sidechain.SideTemplateId)), block.Side.Height, block.Main.Nonce, block.ExtraNonce()) + //utils.Logf("P2PClient", "Peer %s block id = %s, height = %d (nonce %d, extra_nonce %d) was received before, skipping it", c.AddressPort.String(), types.HashFromBytes(block.CoinbaseExtra(sidechain.SideTemplateId)), block.Side.Height, block.Main.Nonce, block.ExtraNonce()) break } @@ -661,7 +661,7 @@ func (c *Client) OnConnection() { if ban { c.Ban(DefaultBanTime, err) } else { - utils.Logf("[P2PClient] Peer %s error adding block id = %s, height = %d, main height = %d, timestamp = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight, block.Main.Timestamp) + utils.Logf("P2PClient", "Peer %s error adding block id = %s, height = %d, main height = %d, timestamp = %d", c.AddressPort.String(), tipHash, block.Side.Height, block.Main.Coinbase.GenHeight, block.Main.Timestamp) } return } else { @@ -764,7 +764,7 @@ func (c *Client) OnConnection() { var port uint16 if firstPeerResponse { - utils.Logf("[P2PClient] Peer %s initial PEER_LIST_RESPONSE: num_peers %d", c.AddressPort.String(), numPeers) + utils.Logf("P2PClient", "Peer %s initial PEER_LIST_RESPONSE: num_peers %d", c.AddressPort.String(), numPeers) } for i := uint8(0); i < numPeers; i++ { if isV6, err := c.ReadByte(); err != nil { @@ -788,7 +788,7 @@ func (c *Client) OnConnection() { c.VersionInformation.Protocol = p2pooltypes.ProtocolVersion(binary.LittleEndian.Uint32(rawIp[0:])) c.VersionInformation.SoftwareVersion = p2pooltypes.SoftwareVersion(binary.LittleEndian.Uint32(rawIp[4:])) c.VersionInformation.SoftwareId = p2pooltypes.SoftwareId(binary.LittleEndian.Uint32(rawIp[8:])) - utils.Logf("[P2PClient] Peer %s version information: %s", c.AddressPort.String(), c.VersionInformation.String()) + utils.Logf("P2PClient", "Peer %s version information: %s", c.AddressPort.String(), c.VersionInformation.String()) c.afterInitialProtocolExchange() } @@ -862,7 +862,7 @@ func (c *Client) afterInitialProtocolExchange() { func (c *Client) sendHandshakeChallenge() { if _, err := rand.Read(c.handshakeChallenge[:]); err != nil { - utils.Logf("[P2PServer] Unable to generate handshake challenge for %s", c.AddressPort.String()) + utils.Logf("P2PServer", "Unable to generate handshake challenge for %s", c.AddressPort.String()) c.Close() return } @@ -915,7 +915,7 @@ func (c *Client) SendMessage(message *ClientMessage) { if !c.Closed.Load() { bufLen := len(message.Buffer) + 1 if bufLen > MaxBufferSize { - utils.Logf("[P2PClient] Peer %s tried to send more than %d bytes, sent %d, disconnecting", c.AddressPort, MaxBufferSize, len(message.Buffer)+1) + utils.Logf("P2PClient", "Peer %s tried to send more than %d bytes, sent %d, disconnecting", c.AddressPort, MaxBufferSize, len(message.Buffer)+1) c.Close() return } @@ -973,6 +973,6 @@ func (c *Client) Close() bool { _ = c.Connection.Close() close(c.closeChannel) - utils.Logf("[P2PClient] Peer %s connection closed", c.AddressPort.String()) + utils.Logf("P2PClient", "Peer %s connection closed", c.AddressPort.String()) return true } diff --git a/p2pool/p2p/server.go b/p2pool/p2p/server.go index a1d2f0d..1e6a054 100644 --- a/p2pool/p2p/server.go +++ b/p2pool/p2p/server.go @@ -12,7 +12,6 @@ import ( p2pooltypes "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/types" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" unsafeRandom "math/rand/v2" "net" "net/netip" @@ -147,13 +146,13 @@ func NewServer(p2pool P2PoolInterface, listenAddress string, externalListenPort } func (s *Server) RefreshOutgoingIPv6() { - utils.Logf("[P2PServer] Refreshing outgoing IPv6") + utils.Logf("P2PServer", "Refreshing outgoing IPv6") addrs, _ := utils.GetOutboundIPv6() s.ipv6AddrsLock.Lock() defer s.ipv6AddrsLock.Unlock() s.ipv6OutgoingAddresses = addrs for _, a := range addrs { - utils.Logf("[P2PServer] Outgoing IPv6: %s", a.String()) + utils.Logf("P2PServer", "Outgoing IPv6: %s", a.String()) } } @@ -309,7 +308,7 @@ func (s *Server) UpdateClientConnections() { if currentTime >= (lastAlive + timeout) { idleTime := currentTime - lastAlive - utils.Logf("[P2PServer] peer %s has been idle for %d seconds, disconnecting", client.AddressPort, idleTime) + utils.Logf("P2PServer", "peer %s has been idle for %d seconds, disconnecting", client.AddressPort, idleTime) client.Close() continue } @@ -365,7 +364,7 @@ func (s *Server) UpdateClientConnections() { // Special case: when we can't find p2pool peers, scan through monerod peers (try 25 peers at a time) if !hasGoodPeers && len(s.moneroPeerList) > 0 { - utils.Logf("[P2PServer] Scanning monerod peers, %d left", len(s.moneroPeerList)) + utils.Logf("P2PServer", "Scanning monerod peers, %d left", len(s.moneroPeerList)) for i := 0; i < 25 && len(s.moneroPeerList) > 0; i++ { peerList = append(peerList, s.moneroPeerList[len(s.moneroPeerList)-1]) s.moneroPeerList = s.moneroPeerList[:len(s.moneroPeerList)-1] @@ -392,7 +391,7 @@ func (s *Server) UpdateClientConnections() { return } if err := s.Connect(peer.AddressPort); err != nil { - utils.Logf("[P2PServer] Connection to %s rejected (%s)", peer.AddressPort.String(), err.Error()) + utils.Logf("P2PServer", "Connection to %s rejected (%s)", peer.AddressPort.String(), err.Error()) } }() i++ @@ -404,7 +403,7 @@ func (s *Server) UpdateClientConnections() { wg.Wait() if attempts == 0 && !hasGoodPeers && len(s.moneroPeerList) == 0 { - utils.Logf("[P2PServer] No connections to other p2pool nodes, check your monerod/p2pool/network/firewall setup!") + utils.Logf("P2PServer", "No connections to other p2pool nodes, check your monerod/p2pool/network/firewall setup!") if moneroPeerList, err := s.p2pool.ClientRPC().GetPeerList(); err == nil { s.moneroPeerList = make(PeerList, 0, len(moneroPeerList.WhiteList)) for _, p := range moneroPeerList.WhiteList { @@ -434,7 +433,7 @@ func (s *Server) UpdateClientConnections() { } return 0 }) - utils.Logf("[P2PServer] monerod peer list loaded (%d peers)", len(s.moneroPeerList)) + utils.Logf("P2PServer", "monerod peer list loaded (%d peers)", len(s.moneroPeerList)) } } } @@ -574,13 +573,13 @@ func (s *Server) Listen() (err error) { }(); err != nil { go func() { defer conn.Close() - utils.Logf("[P2PServer] Connection from %s rejected (%s)", conn.RemoteAddr().String(), err.Error()) + utils.Logf("P2PServer", "Connection from %s rejected (%s)", conn.RemoteAddr().String(), err.Error()) }() continue } func() { - utils.Logf("[P2PServer] Incoming connection from %s", conn.RemoteAddr().String()) + utils.Logf("P2PServer", "Incoming connection from %s", conn.RemoteAddr().String()) s.clientsLock.Lock() defer s.clientsLock.Unlock() @@ -654,9 +653,9 @@ func (s *Server) DirectConnect(addrPort netip.AddrPort) (*Client, error) { } if localAddr != nil { - utils.Logf("[P2PServer] Outgoing connection to %s using %s", addrPort.String(), localAddr.String()) + utils.Logf("P2PServer", "Outgoing connection to %s using %s", addrPort.String(), localAddr.String()) } else { - utils.Logf("[P2PServer] Outgoing connection to %s", addrPort.String()) + utils.Logf("P2PServer", "Outgoing connection to %s", addrPort.String()) } if conn, err := (&net.Dialer{Timeout: time.Second * 5, LocalAddr: localAddr}).DialContext(s.ctx, "tcp", addrPort.String()); err != nil { @@ -741,7 +740,7 @@ func (s *Server) Ban(ip netip.Addr, duration time.Duration, err error) { return } - utils.Logf("[P2PServer] Banned %s for %s: %s", ip.String(), duration.String(), err.Error()) + utils.Logf("P2PServer", "Banned %s for %s: %s", ip.String(), duration.String(), err.Error()) if !ip.IsLoopback() { ip = ip.Unmap() var prefix netip.Prefix @@ -804,7 +803,7 @@ func (s *Server) Broadcast(block *sidechain.PoolBlock) { buffer := make([]byte, 4, block.BufferLength()+4) blockData, err := block.AppendBinaryFlags(buffer, false, false) if err != nil { - log.Panicf("[P2PServer] Tried to broadcast block %s at height %d but received error: %s", block.SideTemplateId(s.Consensus()), block.Side.Height, err) + utils.Panicf("[P2PServer] Tried to broadcast block %s at height %d but received error: %s", block.SideTemplateId(s.Consensus()), block.Side.Height, err) return } binary.LittleEndian.PutUint32(blockData, uint32(len(blockData)-4)) diff --git a/p2pool/sidechain/blobcache.go b/p2pool/sidechain/blobcache.go index e080028..e6f7864 100644 --- a/p2pool/sidechain/blobcache.go +++ b/p2pool/sidechain/blobcache.go @@ -49,7 +49,7 @@ func (c *SideChain) saveBlock(block *PoolBlock) { blob, _ := block.MarshalBinary() if err := c.server.SetBlob(c.uncompressedBlockId(block), blob); err != nil { - utils.Logf("error saving %s: %s", block.SideTemplateId(c.Consensus()).String(), err.Error()) + utils.Errorf("", "error saving %s: %s", block.SideTemplateId(c.Consensus()).String(), err.Error()) } return } @@ -58,7 +58,7 @@ func (c *SideChain) saveBlock(block *PoolBlock) { blob, _ := block.MarshalBinary() if err := c.server.SetBlob(c.uncompressedBlockId(block), blob); err != nil { - utils.Logf("error saving %s: %s", block.SideTemplateId(c.Consensus()).String(), err.Error()) + utils.Errorf("", "error saving %s: %s", block.SideTemplateId(c.Consensus()).String(), err.Error()) } return } @@ -271,9 +271,9 @@ func (c *SideChain) saveBlock(block *PoolBlock) { compactBlob, _ := block.MarshalBinaryFlags(true, true) if (blockFlags & BlockSaveOptionTemplate) != 0 { - utils.Logf("compress block (template) %s in compressed %d bytes, full %d bytes, pruned %d bytes, compact %d bytes", block.SideTemplateId(c.Consensus()).String(), len(blob), len(fullBlob), len(prunedBlob), len(compactBlob)) + utils.Logf("", "compress block (template) %s in compressed %d bytes, full %d bytes, pruned %d bytes, compact %d bytes", block.SideTemplateId(c.Consensus()).String(), len(blob), len(fullBlob), len(prunedBlob), len(compactBlob)) } else { - utils.Logf("compress block %s in compressed %d bytes, full %d bytes, pruned %d bytes, compact %d bytes", block.SideTemplateId(c.Consensus()).String(), len(blob), len(fullBlob), len(prunedBlob), len(compactBlob)) + utils.Logf("", "compress block %s in compressed %d bytes, full %d bytes, pruned %d bytes, compact %d bytes", block.SideTemplateId(c.Consensus()).String(), len(blob), len(fullBlob), len(prunedBlob), len(compactBlob)) } if err := c.server.SetBlob(c.compressedBlockId(block), blob); err != nil { diff --git a/p2pool/sidechain/consensus.go b/p2pool/sidechain/consensus.go index 4e9cb74..e3744b7 100644 --- a/p2pool/sidechain/consensus.go +++ b/p2pool/sidechain/consensus.go @@ -9,7 +9,6 @@ import ( "git.gammaspectra.live/P2Pool/p2pool-observer/monero/randomx" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" - "log" "strconv" ) @@ -182,7 +181,7 @@ func (c *Consensus) verify() bool { case NetworkStagenet: c.HardForks = p2poolStageNetHardForks default: - log.Panicf("invalid network type for determining hardfork") + utils.Panicf("invalid network type for determining hardfork") } } diff --git a/p2pool/sidechain/sidechain.go b/p2pool/sidechain/sidechain.go index 17c51b6..ae36fd0 100644 --- a/p2pool/sidechain/sidechain.go +++ b/p2pool/sidechain/sidechain.go @@ -258,7 +258,7 @@ func (c *SideChain) AddPoolBlockExternal(block *PoolBlock) (missingBlocks []type err = fmt.Errorf("panic: %v", e) } ban = true - utils.Logf("[SideChain]: add_external_block: panic %v, block %+v", e, block) + utils.Errorf("SideChain", "add_external_block: panic %v, block %+v", e, block) } }() @@ -304,7 +304,7 @@ func (c *SideChain) AddPoolBlockExternal(block *PoolBlock) (missingBlocks []type //already added newMainId := block.MainId() oldMainId := block.MainId() - utils.Logf("[SideChain]: add_external_block: block id = %s is already added. New main id = %s, old main id = %s", templateId, newMainId, oldMainId) + utils.Logf("SideChain", "add_external_block: block id = %s is already added. New main id = %s, old main id = %s", templateId, newMainId, oldMainId) if newMainId != oldMainId && otherBlock.Verified.Load() && !otherBlock.Invalid.Load() { //other sections have been verified already, check PoW for new Main blocks @@ -314,9 +314,9 @@ func (c *SideChain) AddPoolBlockExternal(block *PoolBlock) (missingBlocks []type return nil, err, false } else { if isHigherMainChain, err := block.IsProofHigherThanMainDifficultyWithError(c.Consensus().GetHasher(), c.server.GetDifficultyByHeight, c.getSeedByHeightFunc()); err != nil { - utils.Logf("[SideChain] add_external_block: couldn't get mainchain difficulty for height = %d: %s", block.Main.Coinbase.GenHeight, err) + utils.Logf("SideChain", "add_external_block: couldn't get mainchain difficulty for height = %d: %s", block.Main.Coinbase.GenHeight, err) } else if isHigherMainChain { - utils.Logf("[SideChain]: add_external_block: ALTERNATE block %s has enough PoW for Monero height %d, submitting it", templateId.String(), block.Main.Coinbase.GenHeight) + utils.Logf("SideChain", "add_external_block: ALTERNATE block %s has enough PoW for Monero height %d, submitting it", templateId.String(), block.Main.Coinbase.GenHeight) c.server.SubmitBlock(&block.Main) } if isHigher, err := block.IsProofHigherThanDifficultyWithError(c.Consensus().GetHasher(), c.getSeedByHeightFunc()); err != nil { @@ -329,7 +329,7 @@ func (c *SideChain) AddPoolBlockExternal(block *PoolBlock) (missingBlocks []type c.sidechainLock.Lock() defer c.sidechainLock.Unlock() - utils.Logf("[SideChain] add_external_block: ALTERNATE height = %d, id = %s, mainchain height = %d, verified = %t, total = %d", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.Verified.Load(), c.blocksByTemplateId.Count()) + utils.Logf("SideChain", "add_external_block: ALTERNATE height = %d, id = %s, mainchain height = %d, verified = %t, total = %d", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.Verified.Load(), c.blocksByTemplateId.Count()) block.Verified.Store(true) block.Invalid.Store(false) @@ -381,9 +381,9 @@ func (c *SideChain) AddPoolBlockExternal(block *PoolBlock) (missingBlocks []type return nil, err, false } else { if isHigherMainChain, err := block.IsProofHigherThanMainDifficultyWithError(c.Consensus().GetHasher(), c.server.GetDifficultyByHeight, c.getSeedByHeightFunc()); err != nil { - utils.Logf("[SideChain] add_external_block: couldn't get mainchain difficulty for height = %d: %s", block.Main.Coinbase.GenHeight, err) + utils.Logf("SideChain", "add_external_block: couldn't get mainchain difficulty for height = %d: %s", block.Main.Coinbase.GenHeight, err) } else if isHigherMainChain { - utils.Logf("[SideChain]: add_external_block: block %s has enough PoW for Monero height %d, submitting it", templateId.String(), block.Main.Coinbase.GenHeight) + utils.Logf("SideChain", "add_external_block: block %s has enough PoW for Monero height %d, submitting it", templateId.String(), block.Main.Coinbase.GenHeight) c.server.SubmitBlock(&block.Main) } if isHigher, err := block.IsProofHigherThanDifficultyWithError(c.Consensus().GetHasher(), c.getSeedByHeightFunc()); err != nil { @@ -428,7 +428,7 @@ func (c *SideChain) AddPoolBlock(block *PoolBlock) (err error) { c.blocksByTemplateId.Put(block.SideTemplateId(c.Consensus()), block) - utils.Logf("[SideChain] add_block: height = %d, id = %s, mainchain height = %d, verified = %t, total = %d", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.Verified.Load(), c.blocksByTemplateId.Count()) + utils.Logf("SideChain", "add_block: height = %d, id = %s, mainchain height = %d, verified = %t, total = %d", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.Verified.Load(), c.blocksByTemplateId.Count()) if block.SideTemplateId(c.Consensus()) == c.watchBlockSidechainId { c.server.UpdateBlockFound(c.watchBlock, block) @@ -479,7 +479,7 @@ func (c *SideChain) verifyLoop(blockToVerify *PoolBlock) (err error) { } if verification, invalid := c.verifyBlock(block); invalid != nil { - utils.Logf("[SideChain] block at height = %d, id = %s, mainchain height = %d, mined by %s is invalid: %s", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork()), invalid.Error()) + utils.Logf("SideChain", "block at height = %d, id = %s, mainchain height = %d, mined by %s is invalid: %s", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork()), invalid.Error()) block.Invalid.Store(true) block.Verified.Store(verification == nil) if block == blockToVerify { @@ -487,7 +487,7 @@ func (c *SideChain) verifyLoop(blockToVerify *PoolBlock) (err error) { err = invalid } } else if verification != nil { - //utils.Logf("[SideChain] can't verify block at height = %d, id = %s, mainchain height = %d, mined by %s: %s", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(), verification.Error()) + //utils.Logf("SideChain", "can't verify block at height = %d, id = %s, mainchain height = %d, mined by %s: %s", block.Side.Height, block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(), verification.Error()) block.Verified.Store(false) block.Invalid.Store(false) } else { @@ -495,12 +495,12 @@ func (c *SideChain) verifyLoop(blockToVerify *PoolBlock) (err error) { block.Invalid.Store(false) if block.ShareVersion() > ShareVersion_V1 { - utils.Logf("[SideChain] verified block at height = %d, depth = %d, id = %s, mainchain height = %d, mined by %s via %s %s", block.Side.Height, block.Depth.Load(), block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork()), block.Side.ExtraBuffer.SoftwareId, block.Side.ExtraBuffer.SoftwareVersion) + utils.Logf("SideChain", "verified block at height = %d, depth = %d, id = %s, mainchain height = %d, mined by %s via %s %s", block.Side.Height, block.Depth.Load(), block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork()), block.Side.ExtraBuffer.SoftwareId, block.Side.ExtraBuffer.SoftwareVersion) } else { if signalingVersion := block.ShareVersionSignaling(); signalingVersion > ShareVersion_None { - utils.Logf("[SideChain] verified block at height = %d, depth = %d, id = %s, mainchain height = %d, mined by %s, signaling v%d", block.Side.Height, block.Depth.Load(), block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork()), signalingVersion) + utils.Logf("SideChain", "verified block at height = %d, depth = %d, id = %s, mainchain height = %d, mined by %s, signaling v%d", block.Side.Height, block.Depth.Load(), block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork()), signalingVersion) } else { - utils.Logf("[SideChain] verified block at height = %d, depth = %d, id = %s, mainchain height = %d, mined by %s", block.Side.Height, block.Depth.Load(), block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork())) + utils.Logf("SideChain", "verified block at height = %d, depth = %d, id = %s, mainchain height = %d, mined by %s", block.Side.Height, block.Depth.Load(), block.SideTemplateId(c.Consensus()), block.Main.Coinbase.GenHeight, block.GetAddress().ToBase58(c.Consensus().NetworkType.AddressNetwork())) } } @@ -532,7 +532,7 @@ func (c *SideChain) verifyLoop(blockToVerify *PoolBlock) (err error) { if isLongerChain, _ := c.isLongerChain(highestBlock, block); isLongerChain { highestBlock = block } else if highestBlock != nil && highestBlock.Side.Height > block.Side.Height { - utils.Logf("[SideChain] block at height = %d, id = %s, is not a longer chain than height = %d, id = %s", block.Side.Height, block.SideTemplateId(c.Consensus()), highestBlock.Side.Height, highestBlock.SideTemplateId(c.Consensus())) + utils.Logf("SideChain", "block at height = %d, id = %s, is not a longer chain than height = %d, id = %s", block.Side.Height, block.SideTemplateId(c.Consensus()), highestBlock.Side.Height, highestBlock.SideTemplateId(c.Consensus())) } if block.WantBroadcast.Load() && !block.Broadcasted.Swap(true) { @@ -580,7 +580,7 @@ func (c *SideChain) verifyBlock(block *PoolBlock) (verification error, invalid e // Also, having so many blocks on top of this one means it was verified by the network at some point // We skip checks in this case to make pruning possible if block.Depth.Load() > ((c.Consensus().ChainWindowSize-1)*2 + UncleBlockDepth) { - utils.Logf("[SideChain] block at height = %d, id = %s skipped verification", block.Side.Height, block.SideTemplateId(c.Consensus())) + utils.Logf("SideChain", "block at height = %d, id = %s skipped verification", block.Side.Height, block.SideTemplateId(c.Consensus())) return nil, nil } @@ -706,7 +706,7 @@ func (c *SideChain) verifyBlock(block *PoolBlock) (verification error, invalid e // Verify difficulty and miner rewards only for blocks in PPLNS window if block.Depth.Load() >= c.Consensus().ChainWindowSize { - utils.Logf("[SideChain] block at height = %d, id = %s skipped diff/reward verification", block.Side.Height, block.SideTemplateId(c.Consensus())) + utils.Logf("SideChain", "block at height = %d, id = %s skipped diff/reward verification", block.Side.Height, block.SideTemplateId(c.Consensus())) return } @@ -800,7 +800,7 @@ func (c *SideChain) updateDepths(block *PoolBlock) { for _, child := range blocksAtHeight { if child.Side.Parent == block.SideTemplateId(c.Consensus()) { if i != 1 { - utils.Logf("[SideChain] Block %s side height %d is inconsistent with child's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, child.Side.Height) + utils.Logf("SideChain", "Block %s side height %d is inconsistent with child's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, child.Side.Height) return } else { updateDepth(block, child.Depth.Load()+1) @@ -832,7 +832,7 @@ func (c *SideChain) updateDepths(block *PoolBlock) { if child.Side.Parent == block.SideTemplateId(c.Consensus()) { if i != 1 { - utils.Logf("[SideChain] Block %s side height %d is inconsistent with child's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, child.Side.Height) + utils.Logf("SideChain", "Block %s side height %d is inconsistent with child's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, child.Side.Height) return } else if blockDepth > 0 { updateDepth(child, blockDepth-1) @@ -853,7 +853,7 @@ func (c *SideChain) updateDepths(block *PoolBlock) { if parent := block.iteratorGetParent(c.getPoolBlockByTemplateId); parent != nil { if parent.Side.Height+1 != block.Side.Height { - utils.Logf("[SideChain] Block %s side height %d is inconsistent with parent's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, parent.Side.Height) + utils.Logf("SideChain", "Block %s side height %d is inconsistent with parent's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, parent.Side.Height) return } @@ -867,7 +867,7 @@ func (c *SideChain) updateDepths(block *PoolBlock) { _ = block.iteratorUncles(c.getPoolBlockByTemplateId, func(uncle *PoolBlock) { if uncle.Side.Height >= block.Side.Height || (uncle.Side.Height+UncleBlockDepth < block.Side.Height) { - utils.Logf("[SideChain] Block %s side height %d is inconsistent with uncle's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, uncle.Side.Height) + utils.Logf("SideChain", "Block %s side height %d is inconsistent with uncle's side_height %d", block.SideTemplateId(c.Consensus()), block.Side.Height, uncle.Side.Height) returnFromUncles = true return } @@ -898,7 +898,7 @@ func (c *SideChain) updateChainTip(block *PoolBlock) { tip := c.GetChainTip() if block == tip { - utils.Logf("[SideChain] Trying to update chain tip to the same block again. Ignoring it.") + utils.Logf("SideChain", "Trying to update chain tip to the same block again. Ignoring it.") return } @@ -916,15 +916,15 @@ func (c *SideChain) updateChainTip(block *PoolBlock) { c.precalcFinished.Store(true) c.derivationCache.Clear() - utils.Logf("[SideChain] SYNCHRONIZED to tip %s", block.SideTemplateId(c.Consensus())) + utils.Logf("SideChain", "SYNCHRONIZED to tip %s", block.SideTemplateId(c.Consensus())) } c.pruneOldBlocks() } } else if block.Side.Height > tip.Side.Height { - utils.Logf("[SideChain] block %s, height = %d, is not a longer chain than %s, height = %d", block.SideTemplateId(c.Consensus()), block.Side.Height, tip.SideTemplateId(c.Consensus()), tip.Side.Height) + utils.Logf("SideChain", "block %s, height = %d, is not a longer chain than %s, height = %d", block.SideTemplateId(c.Consensus()), block.Side.Height, tip.SideTemplateId(c.Consensus()), tip.Side.Height) } else if block.Side.Height+UncleBlockDepth > tip.Side.Height { - utils.Logf("[SideChain] possible uncle block: id = %s, height = %d", block.SideTemplateId(c.Consensus()), block.Side.Height) + utils.Logf("SideChain", "possible uncle block: id = %s, height = %d", block.SideTemplateId(c.Consensus()), block.Side.Height) } if block.WantBroadcast.Load() && !block.Broadcasted.Swap(true) { @@ -974,7 +974,7 @@ func (c *SideChain) pruneOldBlocks() { c.blocksByTemplateId.Delete(templateId) numBlocksPruned++ } else { - utils.Logf("[SideChain] blocksByHeight and blocksByTemplateId are inconsistent at height = %d, id = %s", height, block.SideTemplateId(c.Consensus())) + utils.Logf("SideChain", "blocksByHeight and blocksByTemplateId are inconsistent at height = %d, id = %s", height, block.SideTemplateId(c.Consensus())) } v = slices.Delete(v, i, i+1) @@ -992,14 +992,14 @@ func (c *SideChain) pruneOldBlocks() { } if numBlocksPruned > 0 { - utils.Logf("[SideChain] pruned %d old blocks at heights <= %d", numBlocksPruned, h) + utils.Logf("SideChain", "pruned %d old blocks at heights <= %d", numBlocksPruned, h) if !c.precalcFinished.Swap(true) { c.derivationCache.Clear() } numSeenBlocksPruned := c.cleanupSeenBlocks() if numSeenBlocksPruned > 0 { - //utils.Logf("[SideChain] pruned %d seen blocks", numBlocksPruned) + //utils.Logf("SideChain", "pruned %d seen blocks", numBlocksPruned) } } } diff --git a/p2pool/sidechain/utils.go b/p2pool/sidechain/utils.go index 2ef8cae..f3b41a6 100644 --- a/p2pool/sidechain/utils.go +++ b/p2pool/sidechain/utils.go @@ -588,19 +588,19 @@ func IsLongerChain(block, candidate *PoolBlock, consensus *Consensus, getByTempl // Candidate chain must be built on top of recent mainchain blocks if headerTip := getChainMainByHash(types.ZeroHash); headerTip != nil { if candidateMainchainHeight+10 < headerTip.Height { - utils.Logf("[SideChain] Received a longer alternative chain but it's stale: height %d, current height %d", candidateMainchainHeight, headerTip.Height) + utils.Logf("SideChain", "Received a longer alternative chain but it's stale: height %d, current height %d", candidateMainchainHeight, headerTip.Height) return false, true } limit := consensus.ChainWindowSize * 4 * consensus.TargetBlockTime / monero.BlockTime if candidateMainchainMinHeight+limit < headerTip.Height { - utils.Logf("[SideChain] Received a longer alternative chain but it's stale: min height %d, must be >= %d", candidateMainchainMinHeight, headerTip.Height-limit) + utils.Logf("SideChain", "Received a longer alternative chain but it's stale: min height %d, must be >= %d", candidateMainchainMinHeight, headerTip.Height-limit) return false, true } // Candidate chain must have been mined on top of at least half as many known Monero blocks, compared to the current chain if len(candidateChainMoneroBlocks)*2 < len(currentChainMoneroBlocks) { - utils.Logf("[SideChain] Received a longer alternative chain but it wasn't mined on current Monero blockchain: only %d / %d blocks found", len(candidateChainMoneroBlocks), len(currentChainMoneroBlocks)) + utils.Logf("SideChain", "Received a longer alternative chain but it wasn't mined on current Monero blockchain: only %d / %d blocks found", len(candidateChainMoneroBlocks), len(currentChainMoneroBlocks)) return false, true } diff --git a/utils/logger.go b/utils/logger.go index 9d5584a..3ebdd3d 100644 --- a/utils/logger.go +++ b/utils/logger.go @@ -1,9 +1,18 @@ package utils -import "log" +import ( + "fmt" + "os" + "runtime" + "strings" + "time" +) type LogLevel int +var LogFile bool +var LogFunc bool + const ( LogLevelError = LogLevel(1 << iota) LogLevelInfo @@ -13,30 +22,102 @@ const ( var GlobalLogLevel = LogLevelError | LogLevelInfo -func Errorf(format string, v ...any) { +func Panic(v ...any) { + s := fmt.Sprint(v...) + innerPrint("", "PANIC", s) + panic(s) +} + +func Panicf(format string, v ...any) { + s := fmt.Sprintf(format, v...) + innerPrint("", "PANIC", s) + panic(s) +} + +func Fatalf(format string, v ...any) { + innerPrint("", "FATAL", fmt.Sprintf(format, v...)) + os.Exit(1) +} + +func Error(v ...any) { if GlobalLogLevel&LogLevelError == 0 { return } - log.Printf(format, v...) + innerPrint("", "ERROR", fmt.Sprint(v...)) } -func Logf(format string, v ...any) { +func Errorf(prefix, format string, v ...any) { + if GlobalLogLevel&LogLevelError == 0 { + return + } + innerPrint(prefix, "ERROR", fmt.Sprintf(format, v...)) +} + +func Print(v ...any) { if GlobalLogLevel&LogLevelInfo == 0 { return } - log.Printf(format, v...) + innerPrint("", "INFO", fmt.Sprint(v...)) +} + +func Logf(prefix, format string, v ...any) { + if GlobalLogLevel&LogLevelInfo == 0 { + return + } + innerPrint(prefix, "INFO", fmt.Sprintf(format, v...)) } func Noticef(format string, v ...any) { if GlobalLogLevel&LogLevelNotice == 0 { return } - log.Printf(format, v...) + innerPrint("", "NOTICE", fmt.Sprintf(format, v...)) } func Debugf(format string, v ...any) { if GlobalLogLevel&LogLevelDebug == 0 { return } - log.Printf(format, v...) + innerPrint("", "DEBUG", fmt.Sprintf(format, v...)) +} + +func innerPrint(prefix, class, v string) { + timestamp := time.Now().UTC().Format("2006-01-02 15:04:05.000") + if LogFile { + var function string + pc, file, line, ok := runtime.Caller(2) + if !ok { + file = "???" + line = 0 + pc = 0 + } + short := file + for i := len(file) - 1; i > 0; i-- { + if file[i] == '/' { + short = file[i+1:] + break + } + } + + if LogFunc { + if pc != 0 { + if details := runtime.FuncForPC(pc); details != nil { + function = details.Name() + } + } + shortFunc := function + for i := len(function) - 1; i > 0; i-- { + if function[i] == '/' { + shortFunc = function[i+1:] + break + } + } + funcItems := strings.Split(shortFunc, ".") + fmt.Printf("%s %s:%d:%s [%s] %s %s\n", timestamp, short, line, funcItems[len(funcItems)-1], prefix, class, strings.TrimSpace(v)) + } else { + fmt.Printf("%s %s:%d [%s] %s %s\n", timestamp, short, line, prefix, class, strings.TrimSpace(v)) + } + } else { + fmt.Printf("%s [%s] %s %s\n", timestamp, prefix, class, strings.TrimSpace(v)) + } }