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

eth: max gas price #1727

Merged
merged 3 commits into from
Mar 10, 2021
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
9 changes: 4 additions & 5 deletions cmd/devtool/devtool.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,16 +159,15 @@ func ethSetup(ethAcctAddr, keystoreDir string, isBroadcaster bool) {
}
glog.Infof("Using controller address %s", ethController)

client, err := eth.NewClient(ethcommon.HexToAddress(ethAcctAddr), keystoreDir, backend,
ethcommon.HexToAddress(ethController), ethTxTimeout)
client, err := eth.NewClient(ethcommon.HexToAddress(ethAcctAddr), keystoreDir, passphrase, backend,
ethcommon.HexToAddress(ethController), ethTxTimeout, nil)
if err != nil {
glog.Errorf("Failed to create client: %v", err)
return
}

err = client.Setup(passphrase, uint64(0), nil)
if err != nil {
glog.Fatalf("Failed to setup client: %v", err)
if err := client.SetGasInfo(0, nil); err != nil {
glog.Errorf("Failed to set gas info on Livepeer Ethereum Client: %v", err)
return
}

Expand Down
18 changes: 12 additions & 6 deletions cmd/livepeer/livepeer.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,10 @@ func main() {
ethKeystorePath := flag.String("ethKeystorePath", "", "Path for the Eth Key")
ethOrchAddr := flag.String("ethOrchAddr", "", "ETH address of an on-chain registered orchestrator")
ethUrl := flag.String("ethUrl", "", "Ethereum node JSON-RPC URL")
ethController := flag.String("ethController", "", "Protocol smart contract address")
gasLimit := flag.Int("gasLimit", 0, "Gas limit for ETH transactions")
yondonfu marked this conversation as resolved.
Show resolved Hide resolved
gasPrice := flag.Int("gasPrice", 0, "Gas price for ETH transactions")
yondonfu marked this conversation as resolved.
Show resolved Hide resolved
maxGasPrice := flag.Int("maxGasPrice", 0, "Maximum gas price for ETH transactions")
ethController := flag.String("ethController", "", "Protocol smart contract address")
initializeRound := flag.Bool("initializeRound", false, "Set to true if running as a transcoder and the node should automatically initialize new rounds")
ticketEV := flag.String("ticketEV", "1000000000000", "The expected value for PM tickets")
// Broadcaster max acceptable ticket EV
Expand Down Expand Up @@ -378,20 +379,25 @@ func main() {
return
}

client, err := eth.NewClient(ethcommon.HexToAddress(*ethAcctAddr), keystoreDir, backend, ethcommon.HexToAddress(*ethController), EthTxTimeout)
var bigMaxGasPrice *big.Int
if *maxGasPrice > 0 {
bigMaxGasPrice = big.NewInt(int64(*maxGasPrice))
}

client, err := eth.NewClient(ethcommon.HexToAddress(*ethAcctAddr), keystoreDir, *ethPassword, backend, ethcommon.HexToAddress(*ethController), EthTxTimeout, bigMaxGasPrice)
if err != nil {
glog.Errorf("Failed to create client: %v", err)
glog.Errorf("Failed to create Livepeer Ethereum client: %v", err)
return
}

var bigGasPrice *big.Int
if *gasPrice > 0 {
glog.Warning("-gasPrice is deprecated, you can use -maxGasPrice instead")
bigGasPrice = big.NewInt(int64(*gasPrice))
}

err = client.Setup(*ethPassword, uint64(*gasLimit), bigGasPrice)
if err != nil {
glog.Errorf("Failed to setup client: %v", err)
if err := client.SetGasInfo(uint64(*gasLimit), bigGasPrice); err != nil {
glog.Errorf("Failed to set gas info on Livepeer Ethereum Client: %v", err)
return
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/livepeer_cli/livepeer_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func (w *wizard) initializeOptions() []wizardOpt {
{desc: "Invoke \"cancel unlock of broadcasting funds\"", invoke: w.cancelUnlock, notOrchestrator: true},
{desc: "Invoke \"withdraw broadcasting funds\"", invoke: w.withdraw, notOrchestrator: true},
{desc: "Set broadcast config", invoke: w.setBroadcastConfig, notOrchestrator: true},
{desc: "Set Eth gas price", invoke: w.setGasPrice},
{desc: "Set maximum Ethereum gas price", invoke: w.setMaxGasPrice},
{desc: "Get test LPT", invoke: w.requestTokens, testnet: true},
{desc: "Get test ETH", invoke: func() {
fmt.Print("For Rinkeby Eth, go to the Rinkeby faucet (https://faucet.rinkeby.io/).")
Expand Down
2 changes: 1 addition & 1 deletion cmd/livepeer_cli/wizard.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (w *wizard) readDefaultString(def string) string {
func (w *wizard) readBaseAmountAndValidate(validate func(in *big.Int) error) *big.Int {
for {
text := w.readString()
val, err := eth.ToBaseAmount(text)
val, err := eth.ToBaseAmount(text, eth.DefaultMaxDecimals)
if err != nil {
log.Error("Error parsing user input", "err", err)
continue
Expand Down
8 changes: 4 additions & 4 deletions cmd/livepeer_cli/wizard_eth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import (
"net/url"
)

func (w *wizard) setGasPrice() {
fmt.Printf("Current gas price: %v\n", w.getGasPrice())
fmt.Printf("Enter new gas price in Wei (enter \"0\" for automatic)")
func (w *wizard) setMaxGasPrice() {
fmt.Printf("Current maximum gas price: %v\n", w.maxGasPrice())
fmt.Printf("Enter new maximum gas price in Wei (enter \"0\" for no maximum gas price)")
amount := w.readBigInt()

val := url.Values{
"amount": {fmt.Sprintf("%v", amount.String())},
}

httpPostWithParams(fmt.Sprintf("http://%v:%v/setGasPrice", w.host, w.httpPort), val)
httpPostWithParams(fmt.Sprintf("http://%v:%v/setMaxGasPrice", w.host, w.httpPort), val)
}

func (w *wizard) signMessage() {
Expand Down
101 changes: 51 additions & 50 deletions cmd/livepeer_cli/wizard_stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"strconv"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/params"
"github.com/golang/glog"
"github.com/livepeer/go-livepeer/eth"
lpTypes "github.com/livepeer/go-livepeer/eth/types"
Expand Down Expand Up @@ -44,20 +45,22 @@ func (w *wizard) stats(showOrchestrator bool) {

lptBal, _ := new(big.Int).SetString(w.getTokenBalance(), 10)
ethBal, _ := new(big.Int).SetString(w.getEthBalance(), 10)
maxGasPrice, _ := new(big.Int).SetString(w.maxGasPrice(), 10)

table := tablewriter.NewWriter(os.Stdout)
data := [][]string{
[]string{"Node's version", status.Version},
[]string{"Node's GO runtime version", status.GolangRuntimeVersion},
[]string{"Node's architecture", status.GOArch},
[]string{"Node's operating system", status.GOOS},
[]string{"HTTP Port", w.httpPort},
[]string{"Controller Address", addrMap["Controller"].Hex()},
[]string{"LivepeerToken Address", addrMap["LivepeerToken"].Hex()},
[]string{"LivepeerTokenFaucet Address", addrMap["LivepeerTokenFaucet"].Hex()},
[]string{"ETH Account", w.getEthAddr()},
[]string{"LPT Balance", eth.FormatUnits(lptBal, "LPT")},
[]string{"ETH Balance", eth.FormatUnits(ethBal, "ETH")},
{"Node's version", status.Version},
{"Node's GO runtime version", status.GolangRuntimeVersion},
{"Node's architecture", status.GOArch},
{"Node's operating system", status.GOOS},
{"HTTP Port", w.httpPort},
{"Controller Address", addrMap["Controller"].Hex()},
{"LivepeerToken Address", addrMap["LivepeerToken"].Hex()},
{"LivepeerTokenFaucet Address", addrMap["LivepeerTokenFaucet"].Hex()},
{"ETH Account", w.getEthAddr()},
{"LPT Balance", eth.FormatUnits(lptBal, "LPT")},
{"ETH Balance", eth.FormatUnits(ethBal, "ETH")},
{"Max Gas Price", fmt.Sprintf("%v GWei", eth.FromWei(maxGasPrice, params.GWei))},
}

for _, v := range data {
Expand Down Expand Up @@ -113,17 +116,17 @@ func (w *wizard) protocolStats() {

table := tablewriter.NewWriter(os.Stdout)
data := [][]string{
[]string{"Protocol Paused", fmt.Sprintf("%t", params.Paused)},
[]string{"Max # Active Orchestrators", params.NumActiveTranscoders.String()},
[]string{"RoundLength (Blocks)", params.RoundLength.String()},
[]string{"RoundLockAmount (%)", eth.FormatPerc(params.RoundLockAmount)},
[]string{"UnbondingPeriod (Rounds)", strconv.Itoa(int(params.UnbondingPeriod))},
[]string{"Inflation (%)", eth.FormatPercMinter(params.Inflation)},
[]string{"InflationChange (%)", eth.FormatPercMinter(params.InflationChange)},
[]string{"TargetBondingRate (%)", eth.FormatPercMinter(params.TargetBondingRate)},
[]string{"Total Bonded", eth.FormatUnits(params.TotalBonded, "LPT")},
[]string{"Total Supply", eth.FormatUnits(params.TotalSupply, "LPT")},
[]string{"Current Participation Rate (%)", currentParticipationRate.String()},
{"Protocol Paused", fmt.Sprintf("%t", params.Paused)},
{"Max # Active Orchestrators", params.NumActiveTranscoders.String()},
{"RoundLength (Blocks)", params.RoundLength.String()},
{"RoundLockAmount (%)", eth.FormatPerc(params.RoundLockAmount)},
{"UnbondingPeriod (Rounds)", strconv.Itoa(int(params.UnbondingPeriod))},
{"Inflation (%)", eth.FormatPercMinter(params.Inflation)},
{"InflationChange (%)", eth.FormatPercMinter(params.InflationChange)},
{"TargetBondingRate (%)", eth.FormatPercMinter(params.TargetBondingRate)},
{"Total Bonded", eth.FormatUnits(params.TotalBonded, "LPT")},
{"Total Supply", eth.FormatUnits(params.TotalSupply, "LPT")},
{"Current Participation Rate (%)", currentParticipationRate.String()},
}

for _, v := range data {
Expand Down Expand Up @@ -156,10 +159,10 @@ func (w *wizard) broadcastStats() {

table := tablewriter.NewWriter(os.Stdout)
data := [][]string{
[]string{"Max Price Per Pixel", priceString},
[]string{"Broadcast Transcoding Options", transcodingOptions},
[]string{"Deposit", eth.FormatUnits(sender.Deposit, "ETH")},
[]string{"Reserve", eth.FormatUnits(sender.Reserve.FundsRemaining, "ETH")},
{"Max Price Per Pixel", priceString},
{"Broadcast Transcoding Options", transcodingOptions},
{"Deposit", eth.FormatUnits(sender.Deposit, "ETH")},
{"Reserve", eth.FormatUnits(sender.Reserve.FundsRemaining, "ETH")},
}

for _, v := range data {
Expand Down Expand Up @@ -193,14 +196,14 @@ func (w *wizard) orchestratorStats() {

table := tablewriter.NewWriter(os.Stdout)
data := [][]string{
[]string{"Status", t.Status},
[]string{"Active", strconv.FormatBool(t.Active)},
[]string{"Service URI", t.ServiceURI},
[]string{"Delegated Stake", eth.FormatUnits(t.DelegatedStake, "LPT")},
[]string{"Reward Cut (%)", eth.FormatPerc(t.RewardCut)},
[]string{"Fee Share (%)", eth.FormatPerc(t.FeeShare)},
[]string{"Last Reward Round", t.LastRewardRound.String()},
[]string{"Base price per pixel", fmt.Sprintf("%v wei / %v pixels", priceInfo.Num(), priceInfo.Denom())},
{"Status", t.Status},
{"Active", strconv.FormatBool(t.Active)},
{"Service URI", t.ServiceURI},
{"Delegated Stake", eth.FormatUnits(t.DelegatedStake, "LPT")},
{"Reward Cut (%)", eth.FormatPerc(t.RewardCut)},
{"Fee Share (%)", eth.FormatPerc(t.FeeShare)},
{"Last Reward Round", t.LastRewardRound.String()},
{"Base price per pixel", fmt.Sprintf("%v wei / %v pixels", priceInfo.Num(), priceInfo.Denom())},
}

for _, v := range data {
Expand Down Expand Up @@ -244,15 +247,15 @@ func (w *wizard) delegatorStats() {

table := tablewriter.NewWriter(os.Stdout)
data := [][]string{
[]string{"Status", d.Status},
[]string{"Stake", eth.FormatUnits(d.BondedAmount, "LPT")},
[]string{"Collected Fees", eth.FormatUnits(d.Fees, "ETH")},
[]string{"Pending Stake", pendingStake},
[]string{"Pending Fees", pendingFees},
[]string{"Delegated Stake", eth.FormatUnits(d.DelegatedAmount, "LPT")},
[]string{"Delegate Address", d.DelegateAddress.Hex()},
[]string{"Last Claim Round", d.LastClaimRound.String()},
[]string{"Start Round", d.StartRound.String()},
{"Status", d.Status},
{"Stake", eth.FormatUnits(d.BondedAmount, "LPT")},
{"Collected Fees", eth.FormatUnits(d.Fees, "ETH")},
{"Pending Stake", pendingStake},
{"Pending Fees", pendingFees},
{"Delegated Stake", eth.FormatUnits(d.DelegatedAmount, "LPT")},
{"Delegate Address", d.DelegateAddress.Hex()},
{"Last Claim Round", d.LastClaimRound.String()},
{"Start Round", d.StartRound.String()},
}

for _, v := range data {
Expand Down Expand Up @@ -407,14 +410,12 @@ func (w *wizard) getDelegatorInfo() (lpTypes.Delegator, error) {
return dInfo, nil
}

func (w *wizard) getGasPrice() string {
g := httpGet(fmt.Sprintf("http://%v:%v/gasPrice", w.host, w.httpPort))
if g == "" {
g = "Unknown"
} else if g == "0" {
g = "automatic"
func (w *wizard) maxGasPrice() string {
max := httpGet(fmt.Sprintf("http://%v:%v/maxGasPrice", w.host, w.httpPort))
if max == "" {
max = "n/a"
}
return g
return max
}

func (w *wizard) currentBlock() (*big.Int, error) {
Expand Down
43 changes: 39 additions & 4 deletions eth/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ import (
"fmt"
"math/big"
"strings"
"sync"

ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/params"
"github.com/golang/glog"
"github.com/livepeer/go-livepeer/eth/contracts"
)
Expand Down Expand Up @@ -40,13 +42,18 @@ type Backend interface {
ethereum.LogFilterer
ethereum.ChainReader
ChainID(ctx context.Context) (*big.Int, error)
MaxGasPrice() *big.Int
SetMaxGasPrice(gp *big.Int)
}

type backend struct {
*ethclient.Client
abiMap map[string]*abi.ABI
nonceManager *NonceManager
signer types.Signer

sync.RWMutex
maxGasPrice *big.Int
}

func NewBackend(client *ethclient.Client, signer types.Signer) (Backend, error) {
Expand All @@ -56,10 +63,10 @@ func NewBackend(client *ethclient.Client, signer types.Signer) (Backend, error)
}

return &backend{
client,
abiMap,
NewNonceManager(client),
signer,
Client: client,
abiMap: abiMap,
nonceManager: NewNonceManager(client),
signer: signer,
}, nil
}

Expand Down Expand Up @@ -99,6 +106,34 @@ func (b *backend) SendTransaction(ctx context.Context, tx *types.Transaction) er
return nil
}

func (b *backend) SuggestGasPrice(ctx context.Context) (*big.Int, error) {
gp, err := b.Client.SuggestGasPrice(ctx)
if err != nil {
return nil, err
}

if b.maxGasPrice != nil && gp.Cmp(b.maxGasPrice) > 0 {
return nil, fmt.Errorf("current gas price exceeds maximum gas price max=%v GWei current=%v GWei",
FromWei(b.maxGasPrice, params.GWei),
FromWei(gp, params.GWei),
)
}

return gp, nil
}

func (b *backend) SetMaxGasPrice(gp *big.Int) {
b.Lock()
defer b.Unlock()
b.maxGasPrice = gp
}

func (b *backend) MaxGasPrice() *big.Int {
b.RLock()
defer b.RUnlock()
return b.maxGasPrice
}

type txLog struct {
method string
inputs string
Expand Down
7 changes: 7 additions & 0 deletions eth/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,10 @@ func TestSendTransaction_SendErr_DontUpdateNonce(t *testing.T) {

assert.Equal(t, nonceLockBefore.nonce, nonceLockAfter.nonce)
}

func TestBackend_SetMaxGasPrice(t *testing.T) {
gp := big.NewInt(10)
backend := &backend{}
backend.SetMaxGasPrice(gp)
assert.Equal(t, gp, backend.MaxGasPrice())
}
Loading