Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed p2p error #69

Merged
merged 2 commits into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions cmd/amc/accountcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func importWallet(ctx *cli.Context) error {
utils.Fatalf("Could not read wallet file: %v", err)
}

stack, err := node.NewNode(ctx.Context, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
return err
}
Expand All @@ -226,7 +226,7 @@ func accountList(ctx *cli.Context) error {
}
}

stack, err := node.NewNode(ctx.Context, &cfg)
stack, err := node.NewNode(ctx, &cfg)
if err != nil {
return err
}
Expand Down Expand Up @@ -342,7 +342,7 @@ func accountUpdate(ctx *cli.Context) error {
utils.Fatalf("No accounts specified to update")
}

stack, err := node.NewNode(ctx.Context, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
return err
}
Expand All @@ -369,7 +369,7 @@ func accountImport(ctx *cli.Context) error {
utils.Fatalf("Failed to load the private key: %v", err)
}

stack, err := node.NewNode(ctx.Context, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
return err
}
Expand Down
117 changes: 73 additions & 44 deletions cmd/amc/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@
package main

import (
"context"
"fmt"
"github.com/amazechain/amc/common/types"
"github.com/amazechain/amc/log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"runtime"
"strings"
"sync"
"syscall"
"time"

"github.com/amazechain/amc/accounts"

Expand Down Expand Up @@ -60,15 +60,6 @@ func appRun(ctx *cli.Context) error {
}

log.Init(DefaultConfig.NodeCfg, DefaultConfig.LoggerCfg)
//log.SetLogger(log.WithContext(c, log.With(zap.NewLogger(zapLog), "caller", log.DefaultCaller)))

c, cancel := context.WithCancel(context.Background())

// initializing the node and providing the current git commit there
//log.WithFields(logrus.Fields{"git_branch": version.GitBranch, "git_tag": version.GitTag, "git_commit": version.GitCommit}).Info("Build info")

//todo
//log.Infof("blockchain %v", DefaultConfig)

if DefaultConfig.PprofCfg.Pprof {
if DefaultConfig.PprofCfg.MaxCpu > 0 {
Expand All @@ -89,27 +80,24 @@ func appRun(ctx *cli.Context) error {
}()
}

n, err := node.NewNode(c, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
log.Error("Failed start Node", "err", err)
return err
}

// Unlock any account specifically requested
unlockAccounts(ctx, n, &DefaultConfig)
StartNode(ctx, stack, false)

if err := n.Start(); err != nil {
cancel()
return err
}
// Unlock any account specifically requested
unlockAccounts(ctx, stack, &DefaultConfig)

// Register wallet event handlers to open and auto-derive wallets
events := make(chan accounts.WalletEvent, 16)
n.AccountManager().Subscribe(events)
stack.AccountManager().Subscribe(events)

go func() {
// Open any wallets already attached
for _, wallet := range n.AccountManager().Wallets() {
for _, wallet := range stack.AccountManager().Wallets() {
if err := wallet.Open(""); err != nil {
log.Warn("Failed to open wallet", "url", wallet.URL(), "err", err)
}
Expand Down Expand Up @@ -140,34 +128,11 @@ func appRun(ctx *cli.Context) error {
}
}()

wg := sync.WaitGroup{}
wg.Add(1)
appWait(cancel, &wg)
n.Close()
wg.Wait()
stack.Wait()

return nil
}

func appWait(cancelFunc context.CancelFunc, group *sync.WaitGroup) {
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)

signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

go func() {
sig := <-sigs
log.Info(sig.String())
done <- true
}()

log.Info("waiting signal ...")
<-done
log.Info("app quit ...")
cancelFunc()
group.Done()
}

// unlockAccounts unlocks any account specifically requested.
func unlockAccounts(ctx *cli.Context, stack *node.Node, cfg *conf.Config) {
var unlocks []string
Expand Down Expand Up @@ -211,3 +176,67 @@ func MakePasswordList(ctx *cli.Context) []string {
}
return lines
}

func StartNode(ctx *cli.Context, stack *node.Node, isConsole bool) {
if err := stack.Start(); err != nil {
log.Critf("Error starting protocol stack: %v", err)
}
go func() {
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigc)

if ctx.IsSet(MinFreeDiskSpaceFlag.Name) {
minFreeDiskSpace := ctx.Int(MinFreeDiskSpaceFlag.Name)
go monitorFreeDiskSpace(sigc, stack.InstanceDir(), uint64(minFreeDiskSpace)*1024*1024*1024)
}

shutdown := func() {
log.Info("Got interrupt, shutting down...")
go stack.Close()
for i := 10; i > 0; i-- {
<-sigc
if i > 1 {
log.Warn("Already shutting down, interrupt more to panic.", "times", i-1)
}
}
panic("Panic closing the amc node")
}

if isConsole {
// In JS console mode, SIGINT is ignored because it's handled by the console.
// However, SIGTERM still shuts down the node.
for {
sig := <-sigc
if sig == syscall.SIGTERM {
shutdown()
return
}
}
} else {
<-sigc
shutdown()
}
}()
}

func monitorFreeDiskSpace(sigc chan os.Signal, path string, freeDiskSpaceCritical uint64) {
if path == "" {
return
}
for {
freeSpace, err := getFreeDiskSpace(path)
if err != nil {
log.Warn("Failed to get free disk space", "path", path, "err", err)
break
}
if freeSpace < freeDiskSpaceCritical {
log.Error("Low disk space. Gracefully shutting down Geth to prevent database corruption.", "available", types.StorageSize(freeSpace), "path", path)
sigc <- syscall.SIGTERM
break
} else if freeSpace < 2*freeDiskSpaceCritical {
log.Warn("Disk space is running low. Geth will shutdown if disk space runs below critical level.", "available", types.StorageSize(freeSpace), "critical_level", types.StorageSize(freeDiskSpaceCritical), "path", path)
}
time.Sleep(30 * time.Second)
}
}
8 changes: 8 additions & 0 deletions cmd/amc/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,13 @@ var (
Destination: &DefaultConfig.NodeCfg.DataDir,
}

MinFreeDiskSpaceFlag = &cli.IntFlag{
Name: "data.dir.minfreedisk",
Usage: "Minimum free disk space in GB, once reached triggers auto shut down (default = 10GB, 0 = disabled)",
Value: 10,
Destination: &DefaultConfig.NodeCfg.MinFreeDiskSpace,
}

FromDataDirFlag = &cli.StringFlag{
Name: "chaindata.from",
Usage: "source data dir",
Expand Down Expand Up @@ -508,6 +515,7 @@ var (
settingFlag = []cli.Flag{
DataDirFlag,
ChainFlag,
MinFreeDiskSpaceFlag,
}
accountFlag = []cli.Flag{
PasswordFileFlag,
Expand Down
44 changes: 44 additions & 0 deletions cmd/amc/diskusage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Copyright 2023 The AmazeChain Authors
// This file is part of the AmazeChain library.
//
// The AmazeChain library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The AmazeChain library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>.

//go:build !windows && !openbsd
// +build !windows,!openbsd

package main

import (
"fmt"

"golang.org/x/sys/unix"
)

func getFreeDiskSpace(path string) (uint64, error) {
var stat unix.Statfs_t
if err := unix.Statfs(path, &stat); err != nil {
return 0, fmt.Errorf("failed to call Statfs: %v", err)
}

// Available blocks * size per block = available space in bytes
var bavail = stat.Bavail
// nolint:staticcheck
if stat.Bavail < 0 {
// FreeBSD can have a negative number of blocks available
// because of the grace limit.
bavail = 0
}
//nolint:unconvert
return uint64(bavail) * uint64(stat.Bsize), nil
}
38 changes: 23 additions & 15 deletions common/txs_pool/txs_pool.go → cmd/amc/diskusage_openbsd.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,31 @@
// You should have received a copy of the GNU Lesser General Public License
// along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>.

package txs_pool
//go:build openbsd
// +build openbsd

package main

import (
"github.com/amazechain/amc/common/transaction"
"github.com/amazechain/amc/common/types"
"github.com/amazechain/amc/contracts/deposit"
"fmt"

"golang.org/x/sys/unix"
)

type ITxsPool interface {
Has(hash types.Hash) bool
Pending(enforceTips bool) map[types.Address][]*transaction.Transaction
GetTransaction() ([]*transaction.Transaction, error)
GetTx(hash types.Hash) *transaction.Transaction
AddRemotes(txs []*transaction.Transaction) []error
AddLocal(tx *transaction.Transaction) error
Stats() (int, int, int, int)
Nonce(addr types.Address) uint64
Content() (map[types.Address][]*transaction.Transaction, map[types.Address][]*transaction.Transaction)
SetDeposit(deposit *deposit.Deposit)
func getFreeDiskSpace(path string) (uint64, error) {
var stat unix.Statfs_t
if err := unix.Statfs(path, &stat); err != nil {
return 0, fmt.Errorf("failed to call Statfs: %v", err)
}

// Available blocks * size per block = available space in bytes
var bavail = stat.F_bavail
// Not sure if the following check is necessary for OpenBSD
if stat.F_bavail < 0 {
// FreeBSD can have a negative number of blocks available
// because of the grace limit.
bavail = 0
}
//nolint:unconvert
return uint64(bavail) * uint64(stat.F_bsize), nil
}
38 changes: 38 additions & 0 deletions cmd/amc/diskusage_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2022 The AmazeChain Authors
// This file is part of the AmazeChain library.
//
// The AmazeChain library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The AmazeChain library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>.

package main

import (
"fmt"

"golang.org/x/sys/windows"
)

func getFreeDiskSpace(path string) (uint64, error) {

cwd, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, fmt.Errorf("failed to call UTF16PtrFromString: %v", err)
}

var freeBytesAvailableToCaller, totalNumberOfBytes, totalNumberOfFreeBytes uint64
if err := windows.GetDiskFreeSpaceEx(cwd, &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes); err != nil {
return 0, fmt.Errorf("failed to call GetDiskFreeSpaceEx: %v", err)
}

return freeBytesAvailableToCaller, nil
}
6 changes: 3 additions & 3 deletions cmd/amc/exportcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ var (

func exportTransactions(ctx *cli.Context) error {

stack, err := node.NewNode(ctx.Context, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -125,7 +125,7 @@ func exportTransactions(ctx *cli.Context) error {

func exportBalance(ctx *cli.Context) error {

stack, err := node.NewNode(ctx.Context, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -164,7 +164,7 @@ func exportBalance(ctx *cli.Context) error {

func exportDBState(ctx *cli.Context) error {

stack, err := node.NewNode(ctx.Context, &DefaultConfig)
stack, err := node.NewNode(ctx, &DefaultConfig)
if err != nil {
return err
}
Expand Down
2 changes: 2 additions & 0 deletions common/blockchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ type IBlockChain interface {
DB() kv.RwDB
Quit() <-chan struct{}

Close() error

WriteBlockWithState(block block.IBlock, receipts []*block.Receipt, ibs *state.IntraBlockState, nopay map[types.Address]*uint256.Int) error

GetDepositInfo(address types.Address) (*uint256.Int, *uint256.Int)
Expand Down
Loading