Skip to content

Commit

Permalink
fix: revert chequebook withdrawal
Browse files Browse the repository at this point in the history
  • Loading branch information
notanatol committed Mar 7, 2024
1 parent 69195f5 commit d41d269
Show file tree
Hide file tree
Showing 12 changed files with 96 additions and 144 deletions.
132 changes: 66 additions & 66 deletions cmd/bee/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,71 +22,71 @@ import (
)

const (
optionNameDataDir = "data-dir"
optionNameCacheCapacity = "cache-capacity"
optionNameDBOpenFilesLimit = "db-open-files-limit"
optionNameDBBlockCacheCapacity = "db-block-cache-capacity"
optionNameDBWriteBufferSize = "db-write-buffer-size"
optionNameDBDisableSeeksCompaction = "db-disable-seeks-compaction"
optionNamePassword = "password"
optionNamePasswordFile = "password-file"
optionNameAPIAddr = "api-addr"
optionNameP2PAddr = "p2p-addr"
optionNameNATAddr = "nat-addr"
optionNameP2PWSEnable = "p2p-ws-enable"
optionNameDebugAPIEnable = "debug-api-enable"
optionNameDebugAPIAddr = "debug-api-addr"
optionNameBootnodes = "bootnode"
optionNameNetworkID = "network-id"
optionWelcomeMessage = "welcome-message"
optionCORSAllowedOrigins = "cors-allowed-origins"
optionNameTracingEnabled = "tracing-enable"
optionNameTracingEndpoint = "tracing-endpoint"
optionNameTracingHost = "tracing-host"
optionNameTracingPort = "tracing-port"
optionNameTracingServiceName = "tracing-service-name"
optionNameVerbosity = "verbosity"
optionNamePaymentThreshold = "payment-threshold"
optionNamePaymentTolerance = "payment-tolerance-percent"
optionNamePaymentEarly = "payment-early-percent"
optionNameResolverEndpoints = "resolver-options"
optionNameBootnodeMode = "bootnode-mode"
optionNameClefSignerEnable = "clef-signer-enable"
optionNameClefSignerEndpoint = "clef-signer-endpoint"
optionNameClefSignerEthereumAddress = "clef-signer-ethereum-address"
optionNameSwapEndpoint = "swap-endpoint" // deprecated: use rpc endpoint instead
optionNameBlockchainRpcEndpoint = "blockchain-rpc-endpoint"
optionNameSwapFactoryAddress = "swap-factory-address"
optionNameSwapInitialDeposit = "swap-initial-deposit"
optionNameSwapEnable = "swap-enable"
optionNameChequebookEnable = "chequebook-enable"
optionNameSwapDeploymentGasPrice = "swap-deployment-gas-price"
optionNameFullNode = "full-node"
optionNamePostageContractAddress = "postage-stamp-address"
optionNamePostageContractStartBlock = "postage-stamp-start-block"
optionNamePriceOracleAddress = "price-oracle-address"
optionNameRedistributionAddress = "redistribution-address"
optionNameStakingAddress = "staking-address"
optionNameBlockTime = "block-time"
optionWarmUpTime = "warmup-time"
optionNameMainNet = "mainnet"
optionNameRetrievalCaching = "cache-retrieval"
optionNameDevReserveCapacity = "dev-reserve-capacity"
optionNameResync = "resync"
optionNamePProfBlock = "pprof-profile"
optionNamePProfMutex = "pprof-mutex"
optionNameStaticNodes = "static-nodes"
optionNameAllowPrivateCIDRs = "allow-private-cidrs"
optionNameSleepAfter = "sleep-after"
optionNameRestrictedAPI = "restricted"
optionNameTokenEncryptionKey = "token-encryption-key"
optionNameAdminPasswordHash = "admin-password"
optionNameUsePostageSnapshot = "use-postage-snapshot"
optionNameStorageIncentivesEnable = "storage-incentives-enable"
optionNameStateStoreCacheCapacity = "statestore-cache-capacity"
optionNameTargetNeighborhood = "target-neighborhood"
optionNameNeighborhoodSuggester = "neighborhood-suggester"
optionNameWithdrawalAddress = "withdrawal-address"
optionNameDataDir = "data-dir"
optionNameCacheCapacity = "cache-capacity"
optionNameDBOpenFilesLimit = "db-open-files-limit"
optionNameDBBlockCacheCapacity = "db-block-cache-capacity"
optionNameDBWriteBufferSize = "db-write-buffer-size"
optionNameDBDisableSeeksCompaction = "db-disable-seeks-compaction"
optionNamePassword = "password"
optionNamePasswordFile = "password-file"
optionNameAPIAddr = "api-addr"
optionNameP2PAddr = "p2p-addr"
optionNameNATAddr = "nat-addr"
optionNameP2PWSEnable = "p2p-ws-enable"
optionNameDebugAPIEnable = "debug-api-enable"
optionNameDebugAPIAddr = "debug-api-addr"
optionNameBootnodes = "bootnode"
optionNameNetworkID = "network-id"
optionWelcomeMessage = "welcome-message"
optionCORSAllowedOrigins = "cors-allowed-origins"
optionNameTracingEnabled = "tracing-enable"
optionNameTracingEndpoint = "tracing-endpoint"
optionNameTracingHost = "tracing-host"
optionNameTracingPort = "tracing-port"
optionNameTracingServiceName = "tracing-service-name"
optionNameVerbosity = "verbosity"
optionNamePaymentThreshold = "payment-threshold"
optionNamePaymentTolerance = "payment-tolerance-percent"
optionNamePaymentEarly = "payment-early-percent"
optionNameResolverEndpoints = "resolver-options"
optionNameBootnodeMode = "bootnode-mode"
optionNameClefSignerEnable = "clef-signer-enable"
optionNameClefSignerEndpoint = "clef-signer-endpoint"
optionNameClefSignerEthereumAddress = "clef-signer-ethereum-address"
optionNameSwapEndpoint = "swap-endpoint" // deprecated: use rpc endpoint instead
optionNameBlockchainRpcEndpoint = "blockchain-rpc-endpoint"
optionNameSwapFactoryAddress = "swap-factory-address"
optionNameSwapInitialDeposit = "swap-initial-deposit"
optionNameSwapEnable = "swap-enable"
optionNameChequebookEnable = "chequebook-enable"
optionNameSwapDeploymentGasPrice = "swap-deployment-gas-price"
optionNameFullNode = "full-node"
optionNamePostageContractAddress = "postage-stamp-address"
optionNamePostageContractStartBlock = "postage-stamp-start-block"
optionNamePriceOracleAddress = "price-oracle-address"
optionNameRedistributionAddress = "redistribution-address"
optionNameStakingAddress = "staking-address"
optionNameBlockTime = "block-time"
optionWarmUpTime = "warmup-time"
optionNameMainNet = "mainnet"
optionNameRetrievalCaching = "cache-retrieval"
optionNameDevReserveCapacity = "dev-reserve-capacity"
optionNameResync = "resync"
optionNamePProfBlock = "pprof-profile"
optionNamePProfMutex = "pprof-mutex"
optionNameStaticNodes = "static-nodes"
optionNameAllowPrivateCIDRs = "allow-private-cidrs"
optionNameSleepAfter = "sleep-after"
optionNameRestrictedAPI = "restricted"
optionNameTokenEncryptionKey = "token-encryption-key"
optionNameAdminPasswordHash = "admin-password"
optionNameUsePostageSnapshot = "use-postage-snapshot"
optionNameStorageIncentivesEnable = "storage-incentives-enable"
optionNameStateStoreCacheCapacity = "statestore-cache-capacity"
optionNameTargetNeighborhood = "target-neighborhood"
optionNameNeighborhoodSuggester = "neighborhood-suggester"
optionNameWhitelistedWithdrawalAddress = "withdrawal-address"
)

// nolint:gochecknoinits
Expand Down Expand Up @@ -305,7 +305,7 @@ func (c *command) setAllFlags(cmd *cobra.Command) {
cmd.Flags().Uint64(optionNameStateStoreCacheCapacity, 100_000, "lru memory caching capacity in number of statestore entries")
cmd.Flags().String(optionNameTargetNeighborhood, "", "neighborhood to target in binary format (ex: 111111001) for mining the initial overlay")
cmd.Flags().String(optionNameNeighborhoodSuggester, "https://api.swarmscan.io/v1/network/neighborhoods/suggestion", "suggester for target neighborhood")
cmd.Flags().String(optionNameWithdrawalAddress, "", "Withdrawal target address")
cmd.Flags().String(optionNameWhitelistedWithdrawalAddress, "", "Withdrawal target address")
}

func newLogger(cmd *cobra.Command, verbosity string) (log.Logger, error) {
Expand Down
2 changes: 0 additions & 2 deletions cmd/bee/cmd/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"strings"

"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/node"
"github.com/ethersphere/bee/pkg/settlement/swap/erc20"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -92,7 +91,6 @@ func (c *command) initDeployCmd() error {
chainID,
swapBackend,
overlayEthAddress,
common.Address{}, // not required for deploy
transactionService,
chequebookFactory,
swapInitialDeposit,
Expand Down
2 changes: 1 addition & 1 deletion cmd/bee/cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ func buildBeeNode(ctx context.Context, c *command, cmd *cobra.Command, logger lo
StatestoreCacheCapacity: c.config.GetUint64(optionNameStateStoreCacheCapacity),
TargetNeighborhood: c.config.GetString(optionNameTargetNeighborhood),
NeighborhoodSuggester: c.config.GetString(optionNameNeighborhoodSuggester),
WithdrawalAddress: c.config.GetString(optionNameWithdrawalAddress),
WhitelistedWithdrawalAddress: c.config.GetStringSlice(optionNameWhitelistedWithdrawalAddress),
})

return b, err
Expand Down
7 changes: 7 additions & 0 deletions pkg/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,8 @@ type Service struct {
erc20Service erc20.Service
chainID int64

whitelistedWithdrawalAddress []common.Address

preMapHooks map[string]func(v string) (string, error)
validate *validator.Validate

Expand Down Expand Up @@ -254,6 +256,7 @@ type ExtraOptions struct {
func New(
publicKey, pssPublicKey ecdsa.PublicKey,
ethereumAddress common.Address,
whitelistedWithdrawalAddress []string,
logger log.Logger,
transaction transaction.Service,
batchStore postage.Storer,
Expand Down Expand Up @@ -303,6 +306,10 @@ func New(
})
s.stamperStore = stamperStore

for _, v := range whitelistedWithdrawalAddress {
s.whitelistedWithdrawalAddress = append(s.whitelistedWithdrawalAddress, common.HexToAddress(v))
}

return s
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func newTestServer(t *testing.T, o testServerOptions) (*http.Client, *websocket.
o.BeeMode = api.FullMode
}

s := api.New(o.PublicKey, o.PSSPublicKey, o.EthereumAddress, o.Logger, transaction, o.BatchStore, o.BeeMode, true, true, backend, o.CORSAllowedOrigins, inmemstore.New())
s := api.New(o.PublicKey, o.PSSPublicKey, o.EthereumAddress, nil, o.Logger, transaction, o.BatchStore, o.BeeMode, true, true, backend, o.CORSAllowedOrigins, inmemstore.New())
testutil.CleanupCloser(t, s)

s.SetP2P(o.P2P)
Expand Down Expand Up @@ -395,7 +395,7 @@ func TestParseName(t *testing.T) {
pk, _ := crypto.GenerateSecp256k1Key()
signer := crypto.NewDefaultSigner(pk)

s := api.New(pk.PublicKey, pk.PublicKey, common.Address{}, log, nil, nil, 1, false, false, nil, []string{"*"}, inmemstore.New())
s := api.New(pk.PublicKey, pk.PublicKey, common.Address{}, nil, log, nil, nil, 1, false, false, nil, []string{"*"}, inmemstore.New())
s.Configure(signer, nil, nil, api.Options{}, api.ExtraOptions{Resolver: tC.res}, 1, nil)
s.MountAPI()

Expand Down
11 changes: 9 additions & 2 deletions pkg/api/wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"math/big"
"net/http"

"slices"

"github.com/ethereum/go-ethereum/common"
"github.com/ethersphere/bee/pkg/bigint"
"github.com/ethersphere/bee/pkg/jsonhttp"
Expand Down Expand Up @@ -81,7 +83,12 @@ func (s *Service) walletWithdrawHandler(w http.ResponseWriter, r *http.Request)
ctx := r.Context()
var bzz bool
// check if coin is xdai or bzz
// check whitelisted

if !slices.Contains(s.whitelistedWithdrawalAddress, *path.Address) {
logger.Error(nil, "provided address not whitelisted")
jsonhttp.InternalServerError(w, "provided address not whitelisted")
return
}

if bzz {
currentBalance, err := s.erc20Service.BalanceOf(ctx, s.ethereumAddress)
Expand Down Expand Up @@ -124,7 +131,7 @@ func (s *Service) walletWithdrawHandler(w http.ResponseWriter, r *http.Request)
txHash, err := withdraw(ctx, s.chainBackend, *path.Address, queries.Amount)
if err != nil {
logger.Error(err, "withdraw")
jsonhttp.InternalServerError(w, "pending nonce")
jsonhttp.InternalServerError(w, "withdraw")
return
}

Expand Down
2 changes: 0 additions & 2 deletions pkg/node/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ func InitChequebookService(
chainID int64,
backend transaction.Backend,
overlayEthAddress common.Address,
withdrawalAddress common.Address,
transactionService transaction.Service,
chequebookFactory chequebook.Factory,
initialDeposit string,
Expand Down Expand Up @@ -163,7 +162,6 @@ func InitChequebookService(
backend,
chainID,
overlayEthAddress,
withdrawalAddress,
chequeSigner,
erc20Service,
)
Expand Down
4 changes: 2 additions & 2 deletions pkg/node/devnode.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func NewDevBee(logger log.Logger, o *DevOptions) (b *DevBee, err error) {
return nil, fmt.Errorf("debug api listener: %w", err)
}

debugApiService = api.New(mockKey.PublicKey, mockKey.PublicKey, overlayEthAddress, logger, mockTransaction, batchStore, api.DevMode, true, true, chainBackend, o.CORSAllowedOrigins, inmemstore.New())
debugApiService = api.New(mockKey.PublicKey, mockKey.PublicKey, overlayEthAddress, nil, logger, mockTransaction, batchStore, api.DevMode, true, true, chainBackend, o.CORSAllowedOrigins, inmemstore.New())
debugAPIServer := &http.Server{
IdleTimeout: 30 * time.Second,
ReadHeaderTimeout: 3 * time.Second,
Expand Down Expand Up @@ -398,7 +398,7 @@ func NewDevBee(logger log.Logger, o *DevOptions) (b *DevBee, err error) {
}),
)

apiService := api.New(mockKey.PublicKey, mockKey.PublicKey, overlayEthAddress, logger, mockTransaction, batchStore, api.DevMode, true, true, chainBackend, o.CORSAllowedOrigins, inmemstore.New())
apiService := api.New(mockKey.PublicKey, mockKey.PublicKey, overlayEthAddress, nil, logger, mockTransaction, batchStore, api.DevMode, true, true, chainBackend, o.CORSAllowedOrigins, inmemstore.New())

apiService.Configure(signer, authenticator, tracer, api.Options{
CORSAllowedOrigins: o.CORSAllowedOrigins,
Expand Down
10 changes: 4 additions & 6 deletions pkg/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ type Options struct {
StatestoreCacheCapacity uint64
TargetNeighborhood string
NeighborhoodSuggester string
WithdrawalAddress string
WhitelistedWithdrawalAddress []string
}

const (
Expand Down Expand Up @@ -316,7 +316,6 @@ func NewBee(
var (
chainBackend transaction.Backend
overlayEthAddress common.Address
withdrawalAddress common.Address
chainID int64
transactionService transaction.Service
transactionMonitor transaction.Monitor
Expand Down Expand Up @@ -423,6 +422,7 @@ func NewBee(
*publicKey,
pssPrivateKey.PublicKey,
overlayEthAddress,
o.WhitelistedWithdrawalAddress,
logger,
transactionService,
batchStore,
Expand Down Expand Up @@ -462,6 +462,7 @@ func NewBee(
*publicKey,
pssPrivateKey.PublicKey,
overlayEthAddress,
o.WhitelistedWithdrawalAddress,
logger,
transactionService,
batchStore,
Expand Down Expand Up @@ -527,8 +528,6 @@ func NewBee(

erc20Service = erc20.New(transactionService, erc20Address)

withdrawalAddress = common.HexToAddress(o.WithdrawalAddress)

if o.ChequebookEnable && chainEnabled {
chequebookService, err = InitChequebookService(
ctx,
Expand All @@ -538,7 +537,6 @@ func NewBee(
chainID,
chainBackend,
overlayEthAddress,
withdrawalAddress,
transactionService,
chequebookFactory,
o.SwapInitialDeposit,
Expand Down Expand Up @@ -1099,7 +1097,7 @@ func NewBee(

if o.APIAddr != "" {
if apiService == nil {
apiService = api.New(*publicKey, pssPrivateKey.PublicKey, overlayEthAddress, logger, transactionService, batchStore, beeNodeMode, o.ChequebookEnable, o.SwapEnable, chainBackend, o.CORSAllowedOrigins, stamperStore)
apiService = api.New(*publicKey, pssPrivateKey.PublicKey, overlayEthAddress, o.WhitelistedWithdrawalAddress, logger, transactionService, batchStore, beeNodeMode, o.ChequebookEnable, o.SwapEnable, chainBackend, o.CORSAllowedOrigins, stamperStore)
apiService.SetProbe(probe)
apiService.SetRedistributionAgent(agent)
}
Expand Down
15 changes: 3 additions & 12 deletions pkg/settlement/swap/chequebook/chequebook.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ type service struct {
lock sync.Mutex
transactionService transaction.Service

address common.Address
withdrawalAddress common.Address
address common.Address

contract *chequebookContract
ownerAddress common.Address
Expand All @@ -83,13 +82,12 @@ type service struct {
}

// New creates a new chequebook service for the provided chequebook contract.
func New(transactionService transaction.Service, address, ownerAddress, withdrawalAddress common.Address, store storage.StateStorer, chequeSigner ChequeSigner, erc20Service erc20.Service) (Service, error) {
func New(transactionService transaction.Service, address, ownerAddress common.Address, store storage.StateStorer, chequeSigner ChequeSigner, erc20Service erc20.Service) (Service, error) {
return &service{
transactionService: transactionService,
address: address,
contract: newChequebookContract(address, transactionService),
ownerAddress: ownerAddress,
withdrawalAddress: withdrawalAddress,
erc20Service: erc20Service,
store: store,
chequeSigner: chequeSigner,
Expand Down Expand Up @@ -329,15 +327,8 @@ func (s *service) Withdraw(ctx context.Context, amount *big.Int) (hash common.Ha
return common.Hash{}, err
}

var zeroAddress common.Address

address := s.address
if s.withdrawalAddress != zeroAddress {
address = s.withdrawalAddress
}

request := &transaction.TxRequest{
To: &address,
To: &s.address,
Data: callData,
GasPrice: sctx.GetGasPrice(ctx),
GasLimit: 95000,
Expand Down
Loading

0 comments on commit d41d269

Please sign in to comment.