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

Return FP strings for getunclaimedgas #1572

Merged
merged 3 commits into from
Dec 9, 2020
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
10 changes: 5 additions & 5 deletions cli/flags/fixed8.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import (
"flag"
"strings"

"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/urfave/cli"
)

// Fixed8 is a wrapper for Uint160 with flag.Value methods.
type Fixed8 struct {
Value util.Fixed8
Value fixedn.Fixed8
}

// Fixed8Flag is a flag with type string.
Expand All @@ -32,7 +32,7 @@ func (a Fixed8) String() string {

// Set implements flag.Value interface.
func (a *Fixed8) Set(s string) error {
f, err := util.Fixed8FromString(s)
f, err := fixedn.Fixed8FromString(s)
if err != nil {
return cli.NewExitError(err, 1)
}
Expand All @@ -41,7 +41,7 @@ func (a *Fixed8) Set(s string) error {
}

// Fixed8 casts address to util.Fixed8.
func (a *Fixed8) Fixed8() util.Fixed8 {
func (a *Fixed8) Fixed8() fixedn.Fixed8 {
return a.Value
}

Expand Down Expand Up @@ -70,6 +70,6 @@ func (f Fixed8Flag) Apply(set *flag.FlagSet) {
}

// Fixed8FromContext returns parsed util.Fixed8 value provided flag name.
func Fixed8FromContext(ctx *cli.Context, name string) util.Fixed8 {
func Fixed8FromContext(ctx *cli.Context, name string) fixedn.Fixed8 {
return ctx.Generic(name).(*Fixed8).Value
}
10 changes: 5 additions & 5 deletions cli/flags/fixed8_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ import (
"io/ioutil"
"testing"

"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/stretchr/testify/require"
)

func TestFixed8_String(t *testing.T) {
value := util.Fixed8(123)
value := fixedn.Fixed8(123)
f := Fixed8{
Value: value,
}
Expand All @@ -19,7 +19,7 @@ func TestFixed8_String(t *testing.T) {
}

func TestFixed8_Set(t *testing.T) {
value := util.Fixed8(123)
value := fixedn.Fixed8(123)
f := Fixed8{}

require.Error(t, f.Set("not-a-fixed8"))
Expand All @@ -30,10 +30,10 @@ func TestFixed8_Set(t *testing.T) {

func TestFixed8_Fixed8(t *testing.T) {
f := Fixed8{
Value: util.Fixed8(123),
Value: fixedn.Fixed8(123),
}

require.Equal(t, util.Fixed8(123), f.Fixed8())
require.Equal(t, fixedn.Fixed8(123), f.Fixed8())
}

func TestFixed8Flag_String(t *testing.T) {
Expand Down
10 changes: 5 additions & 5 deletions cli/nep17_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"testing"

"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/wallet"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -47,7 +47,7 @@ func TestNEP17Balance(t *testing.T) {
e.checkNextLine(t, "^\\s*Account\\s+"+validatorAddr)
e.checkNextLine(t, "^\\s*GAS:\\s+GAS \\("+e.Chain.UtilityTokenHash().StringLE()+"\\)")
b := e.Chain.GetUtilityTokenBalance(validatorHash)
e.checkNextLine(t, "^\\s*Amount\\s*:\\s*"+util.Fixed8(b.Int64()).String())
e.checkNextLine(t, "^\\s*Amount\\s*:\\s*"+fixedn.Fixed8(b.Int64()).String())
})
t.Run("all accounts", func(t *testing.T) {
e.Run(t, cmdbase...)
Expand All @@ -56,7 +56,7 @@ func TestNEP17Balance(t *testing.T) {
e.checkNextLine(t, "^Account "+address.Uint160ToString(addr1))
e.checkNextLine(t, "^\\s*GAS:\\s+GAS \\("+e.Chain.UtilityTokenHash().StringLE()+"\\)")
balance := e.Chain.GetUtilityTokenBalance(addr1)
e.checkNextLine(t, "^\\s*Amount\\s*:\\s*"+util.Fixed8(balance.Int64()).String())
e.checkNextLine(t, "^\\s*Amount\\s*:\\s*"+fixedn.Fixed8(balance.Int64()).String())
e.checkNextLine(t, "^\\s*Updated:")
e.checkNextLine(t, "^\\s*$")

Expand All @@ -74,7 +74,7 @@ func TestNEP17Balance(t *testing.T) {
if strings.Contains(line, "GAS") {
e.checkLine(t, line, "^\\s*GAS:\\s+GAS \\("+e.Chain.UtilityTokenHash().StringLE()+"\\)")
balance = e.Chain.GetUtilityTokenBalance(addr3)
e.checkNextLine(t, "^\\s*Amount\\s*:\\s*"+util.Fixed8(balance.Int64()).String())
e.checkNextLine(t, "^\\s*Amount\\s*:\\s*"+fixedn.Fixed8(balance.Int64()).String())
e.checkNextLine(t, "^\\s*Updated:")
} else {
balance, index := e.Chain.GetGoverningTokenBalance(validatorHash)
Expand Down Expand Up @@ -156,7 +156,7 @@ func TestNEP17MultiTransfer(t *testing.T) {
b, _ := e.Chain.GetGoverningTokenBalance(privs[0].GetScriptHash())
require.Equal(t, big.NewInt(42), b)
b = e.Chain.GetUtilityTokenBalance(privs[1].GetScriptHash())
require.Equal(t, big.NewInt(int64(util.Fixed8FromInt64(7))), b)
require.Equal(t, big.NewInt(int64(fixedn.Fixed8FromInt64(7))), b)
b, _ = e.Chain.GetGoverningTokenBalance(privs[2].GetScriptHash())
require.Equal(t, big.NewInt(13), b)
}
Expand Down
3 changes: 2 additions & 1 deletion cli/smartcontract/smart_contract.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/state"
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/rpc/request"
"github.com/nspcc-dev/neo-go/pkg/rpc/response/result"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
Expand Down Expand Up @@ -446,7 +447,7 @@ func invokeFunction(ctx *cli.Context) error {
func invokeInternal(ctx *cli.Context, signAndPush bool) error {
var (
err error
gas util.Fixed8
gas fixedn.Fixed8
operation string
params = make([]smartcontract.Parameter, 0)
paramsStart = 1
Expand Down
9 changes: 5 additions & 4 deletions cli/wallet/nep17.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/nspcc-dev/neo-go/cli/options"
"github.com/nspcc-dev/neo-go/cli/paramcontext"
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/rpc/client"
"github.com/nspcc-dev/neo-go/pkg/util"
"github.com/nspcc-dev/neo-go/pkg/wallet"
Expand Down Expand Up @@ -390,14 +391,14 @@ func multiTransferNEP17(ctx *cli.Context) error {
if err != nil {
return cli.NewExitError(fmt.Errorf("invalid address: '%s'", ss[1]), 1)
}
amount, err := util.FixedNFromString(ss[2], int(token.Decimals))
amount, err := fixedn.FromString(ss[2], int(token.Decimals))
if err != nil {
return cli.NewExitError(fmt.Errorf("invalid amount: %w", err), 1)
}
recipients = append(recipients, client.TransferTarget{
Token: token.Hash,
Address: addr,
Amount: amount,
Amount: amount.Int64(),
})
}

Expand Down Expand Up @@ -437,15 +438,15 @@ func transferNEP17(ctx *cli.Context) error {
}
}

amount, err := util.FixedNFromString(ctx.String("amount"), int(token.Decimals))
amount, err := fixedn.FromString(ctx.String("amount"), int(token.Decimals))
if err != nil {
return cli.NewExitError(fmt.Errorf("invalid amount: %w", err), 1)
}

return signAndSendTransfer(ctx, c, acc, []client.TransferTarget{{
Token: token.Hash,
Address: to,
Amount: amount,
Amount: amount.Int64(),
}})
}

Expand Down
5 changes: 3 additions & 2 deletions pkg/core/helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"github.com/nspcc-dev/neo-go/pkg/core/storage"
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
Expand Down Expand Up @@ -198,7 +199,7 @@ func TestCreateBasicChain(t *testing.T) {
acc0 := wallet.NewAccountFromPrivateKey(priv0)

// Prepare some transaction for future submission.
txSendRaw := newNEP17Transfer(bc.contracts.NEO.Hash, priv0ScriptHash, priv1.GetScriptHash(), int64(util.Fixed8FromInt64(1000)))
txSendRaw := newNEP17Transfer(bc.contracts.NEO.Hash, priv0ScriptHash, priv1.GetScriptHash(), int64(fixedn.Fixed8FromInt64(1000)))
txSendRaw.ValidUntilBlock = transaction.MaxValidUntilBlockIncrement
txSendRaw.Nonce = 0x1234
txSendRaw.Signers = []transaction.Signer{{
Expand Down Expand Up @@ -245,7 +246,7 @@ func initBasicChain(t *testing.T, bc *Blockchain) {
txMoveNeo, err := testchain.NewTransferFromOwner(bc, neoHash, priv0ScriptHash, neoAmount, getNextNonce(), validUntilBlock)
require.NoError(t, err)
// Move some GAS to one simple account.
txMoveGas, err := testchain.NewTransferFromOwner(bc, gasHash, priv0ScriptHash, int64(util.Fixed8FromInt64(1000)),
txMoveGas, err := testchain.NewTransferFromOwner(bc, gasHash, priv0ScriptHash, int64(fixedn.Fixed8FromInt64(1000)),
getNextNonce(), validUntilBlock)
require.NoError(t, err)

Expand Down
5 changes: 3 additions & 2 deletions pkg/core/state/notification_event.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"

"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
"github.com/nspcc-dev/neo-go/pkg/util"
Expand Down Expand Up @@ -173,7 +174,7 @@ type Execution struct {
type executionAux struct {
Trigger string `json:"trigger"`
VMState string `json:"vmstate"`
GasConsumed util.Fixed8 `json:"gasconsumed,string"`
GasConsumed fixedn.Fixed8 `json:"gasconsumed,string"`
Stack json.RawMessage `json:"stack"`
Events []NotificationEvent `json:"notifications"`
FaultException string `json:"exception,omitempty"`
Expand Down Expand Up @@ -202,7 +203,7 @@ func (e Execution) MarshalJSON() ([]byte, error) {
return json.Marshal(&executionAux{
Trigger: e.Trigger.String(),
VMState: e.VMState.String(),
GasConsumed: util.Fixed8(e.GasConsumed),
GasConsumed: fixedn.Fixed8(e.GasConsumed),
Stack: st,
Events: e.Events,
FaultException: e.FaultException,
Expand Down
29 changes: 15 additions & 14 deletions pkg/core/transaction/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/nspcc-dev/neo-go/pkg/config/netmode"
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/nspcc-dev/neo-go/pkg/io"
"github.com/nspcc-dev/neo-go/pkg/util"
)
Expand Down Expand Up @@ -301,18 +302,18 @@ func (t *Transaction) Sender() util.Uint160 {
// transactionJSON is a wrapper for Transaction and
// used for correct marhalling of transaction.Data
type transactionJSON struct {
TxID util.Uint256 `json:"hash"`
Size int `json:"size"`
Version uint8 `json:"version"`
Nonce uint32 `json:"nonce"`
Sender string `json:"sender"`
SystemFee util.Fixed8 `json:"sysfee,string"`
NetworkFee util.Fixed8 `json:"netfee,string"`
ValidUntilBlock uint32 `json:"validuntilblock"`
Attributes []Attribute `json:"attributes"`
Signers []Signer `json:"signers"`
Script []byte `json:"script"`
Scripts []Witness `json:"witnesses"`
TxID util.Uint256 `json:"hash"`
Size int `json:"size"`
Version uint8 `json:"version"`
Nonce uint32 `json:"nonce"`
Sender string `json:"sender"`
SystemFee fixedn.Fixed8 `json:"sysfee,string"`
NetworkFee fixedn.Fixed8 `json:"netfee,string"`
ValidUntilBlock uint32 `json:"validuntilblock"`
Attributes []Attribute `json:"attributes"`
Signers []Signer `json:"signers"`
Script []byte `json:"script"`
Scripts []Witness `json:"witnesses"`
}

// MarshalJSON implements json.Marshaler interface.
Expand All @@ -328,8 +329,8 @@ func (t *Transaction) MarshalJSON() ([]byte, error) {
Signers: t.Signers,
Script: t.Script,
Scripts: t.Scripts,
SystemFee: util.Fixed8(t.SystemFee),
NetworkFee: util.Fixed8(t.NetworkFee),
SystemFee: fixedn.Fixed8(t.SystemFee),
NetworkFee: fixedn.Fixed8(t.NetworkFee),
}
return json.Marshal(tx)
}
Expand Down
5 changes: 3 additions & 2 deletions pkg/core/transaction/transaction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"math"
"testing"

"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -119,8 +120,8 @@ func TestMarshalUnmarshalJSONInvocationTX(t *testing.T) {
Script: []byte{1, 2, 3, 4},
Attributes: []Attribute{{Type: HighPriority}},
Scripts: []Witness{},
SystemFee: int64(util.Fixed8FromFloat(123.45)),
NetworkFee: int64(util.Fixed8FromFloat(0.123)),
SystemFee: int64(fixedn.Fixed8FromFloat(123.45)),
NetworkFee: int64(fixedn.Fixed8FromFloat(0.123)),
Trimmed: false,
}

Expand Down
80 changes: 80 additions & 0 deletions pkg/encoding/fixedn/decimal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package fixedn

import (
"errors"
"fmt"
"math/big"
"strconv"
"strings"
)

const maxAllowedPrecision = 16

// ErrInvalidFormat is returned when decimal format is invalid.
var ErrInvalidFormat = errors.New("invalid decimal format")

var _pow10 []*big.Int

func init() {
var p = int64(1)
for i := 0; i <= maxAllowedPrecision; i++ {
_pow10 = append(_pow10, big.NewInt(p))
p *= 10
}
}

func pow10(n int) *big.Int {
last := len(_pow10) - 1
if n <= last {
return _pow10[n]
}
p := new(big.Int)
p.Mul(_pow10[last], _pow10[1])
for i := last + 1; i < n; i++ {
p.Mul(p, _pow10[1])
}
return p
}

// ToString converts big decimal with specified precision to string.
func ToString(bi *big.Int, precision int) string {
var dp, fp big.Int
dp.QuoRem(bi, pow10(precision), &fp)

var s = dp.String()
if fp.Sign() == 0 {
return s
}
frac := fp.Uint64()
trimmed := 0
for ; frac%10 == 0; frac /= 10 {
trimmed++
}
return s + "." + fmt.Sprintf("%0"+strconv.FormatUint(uint64(precision-trimmed), 10)+"d", frac)
}

// FromString converts string to a big decimal with specified precision.
func FromString(s string, precision int) (*big.Int, error) {
parts := strings.SplitN(s, ".", 2)
bi, ok := new(big.Int).SetString(parts[0], 10)
if !ok {
return nil, ErrInvalidFormat
}
bi.Mul(bi, pow10(precision))
if len(parts) == 1 {
return bi, nil
}

if len(parts[1]) > precision {
return nil, ErrInvalidFormat
}
fp, ok := new(big.Int).SetString(parts[1], 10)
if !ok {
return nil, ErrInvalidFormat
}
fp.Mul(fp, pow10(precision-len(parts[1])))
if bi.Sign() == -1 {
return bi.Sub(bi, fp), nil
}
return bi.Add(bi, fp), nil
}
Loading