Skip to content

Commit 5c8fe28

Browse files
fjlobscuren
authored andcommitted
common: move big integer math to common/math (bnb-chain#3699)
* common: remove CurrencyToString Move denomination values to params instead. * common: delete dead code * common: move big integer operations to common/math This commit consolidates all big integer operations into common/math and adds tests and documentation. There should be no change in semantics for BigPow, BigMin, BigMax, S256, U256, Exp and their behaviour is now locked in by tests. The BigD, BytesToBig and Bytes2Big functions don't provide additional value, all uses are replaced by new(big.Int).SetBytes(). BigToBytes is now called PaddedBigBytes, its minimum output size parameter is now specified as the number of bytes instead of bits. The single use of this function is in the EVM's MSTORE instruction. Big and String2Big are replaced by ParseBig, which is slightly stricter. It previously accepted leading zeros for hexadecimal inputs but treated decimal inputs as octal if a leading zero digit was present. ParseUint64 is used in places where String2Big was used to decode a uint64. The new functions MustParseBig and MustParseUint64 are now used in many places where parsing errors were previously ignored. * common: delete unused big integer variables * accounts/abi: replace uses of BytesToBig with use of encoding/binary * common: remove BytesToBig * common: remove Bytes2Big * common: remove BigTrue * cmd/utils: add BigFlag and use it for error-checked integer flags While here, remove environment variable processing for DirectoryFlag because we don't use it. * core: add missing error checks in genesis block parser * common: remove String2Big * cmd/evm: use utils.BigFlag * common/math: check for 256 bit overflow in ParseBig This is supposed to prevent silent overflow/truncation of values in the genesis block JSON. Without this check, a genesis block that set a balance larger than 256 bits would lead to weird behaviour in the VM. * cmd/utils: fixup import
1 parent 50ee279 commit 5c8fe28

54 files changed

Lines changed: 821 additions & 1569 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎accounts/abi/abi.go‎

Lines changed: 42 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package abi
1818

1919
import (
20+
"encoding/binary"
2021
"encoding/json"
2122
"fmt"
2223
"io"
@@ -129,16 +130,15 @@ func toGoSlice(i int, t Argument, output []byte) (interface{}, error) {
129130
var size int
130131
var offset int
131132
if t.Type.IsSlice {
132-
133133
// get the offset which determines the start of this array ...
134-
offset = int(common.BytesToBig(output[index : index+32]).Uint64())
134+
offset = int(binary.BigEndian.Uint64(output[index+24 : index+32]))
135135
if offset+32 > len(output) {
136136
return nil, fmt.Errorf("abi: cannot marshal in to go slice: offset %d would go over slice boundary (len=%d)", len(output), offset+32)
137137
}
138138

139139
slice = output[offset:]
140140
// ... starting with the size of the array in elements ...
141-
size = int(common.BytesToBig(slice[:32]).Uint64())
141+
size = int(binary.BigEndian.Uint64(slice[24:32]))
142142
slice = slice[32:]
143143
// ... and make sure that we've at the very least the amount of bytes
144144
// available in the buffer.
@@ -147,7 +147,7 @@ func toGoSlice(i int, t Argument, output []byte) (interface{}, error) {
147147
}
148148

149149
// reslice to match the required size
150-
slice = slice[:(size * 32)]
150+
slice = slice[:size*32]
151151
} else if t.Type.IsArray {
152152
//get the number of elements in the array
153153
size = t.Type.SliceSize
@@ -165,33 +165,12 @@ func toGoSlice(i int, t Argument, output []byte) (interface{}, error) {
165165
inter interface{} // interface type
166166
returnOutput = slice[i*32 : i*32+32] // the return output
167167
)
168-
169168
// set inter to the correct type (cast)
170169
switch elem.T {
171170
case IntTy, UintTy:
172-
bigNum := common.BytesToBig(returnOutput)
173-
switch t.Type.Kind {
174-
case reflect.Uint8:
175-
inter = uint8(bigNum.Uint64())
176-
case reflect.Uint16:
177-
inter = uint16(bigNum.Uint64())
178-
case reflect.Uint32:
179-
inter = uint32(bigNum.Uint64())
180-
case reflect.Uint64:
181-
inter = bigNum.Uint64()
182-
case reflect.Int8:
183-
inter = int8(bigNum.Int64())
184-
case reflect.Int16:
185-
inter = int16(bigNum.Int64())
186-
case reflect.Int32:
187-
inter = int32(bigNum.Int64())
188-
case reflect.Int64:
189-
inter = bigNum.Int64()
190-
default:
191-
inter = common.BytesToBig(returnOutput)
192-
}
171+
inter = readInteger(t.Type.Kind, returnOutput)
193172
case BoolTy:
194-
inter = common.BytesToBig(returnOutput).Uint64() > 0
173+
inter = !allZero(returnOutput)
195174
case AddressTy:
196175
inter = common.BytesToAddress(returnOutput)
197176
case HashTy:
@@ -207,6 +186,38 @@ func toGoSlice(i int, t Argument, output []byte) (interface{}, error) {
207186
return refSlice.Interface(), nil
208187
}
209188

189+
func readInteger(kind reflect.Kind, b []byte) interface{} {
190+
switch kind {
191+
case reflect.Uint8:
192+
return uint8(b[len(b)-1])
193+
case reflect.Uint16:
194+
return binary.BigEndian.Uint16(b[len(b)-2:])
195+
case reflect.Uint32:
196+
return binary.BigEndian.Uint32(b[len(b)-4:])
197+
case reflect.Uint64:
198+
return binary.BigEndian.Uint64(b[len(b)-8:])
199+
case reflect.Int8:
200+
return int8(b[len(b)-1])
201+
case reflect.Int16:
202+
return int16(binary.BigEndian.Uint16(b[len(b)-2:]))
203+
case reflect.Int32:
204+
return int32(binary.BigEndian.Uint32(b[len(b)-4:]))
205+
case reflect.Int64:
206+
return int64(binary.BigEndian.Uint64(b[len(b)-8:]))
207+
default:
208+
return new(big.Int).SetBytes(b)
209+
}
210+
}
211+
212+
func allZero(b []byte) bool {
213+
for _, byte := range b {
214+
if byte != 0 {
215+
return false
216+
}
217+
}
218+
return true
219+
}
220+
210221
// toGoType parses the input and casts it to the proper type defined by the ABI
211222
// argument in T.
212223
func toGoType(i int, t Argument, output []byte) (interface{}, error) {
@@ -226,12 +237,12 @@ func toGoType(i int, t Argument, output []byte) (interface{}, error) {
226237
switch t.Type.T {
227238
case StringTy, BytesTy: // variable arrays are written at the end of the return bytes
228239
// parse offset from which we should start reading
229-
offset := int(common.BytesToBig(output[index : index+32]).Uint64())
240+
offset := int(binary.BigEndian.Uint64(output[index+24 : index+32]))
230241
if offset+32 > len(output) {
231242
return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), offset+32)
232243
}
233244
// parse the size up until we should be reading
234-
size := int(common.BytesToBig(output[offset : offset+32]).Uint64())
245+
size := int(binary.BigEndian.Uint64(output[offset+24 : offset+32]))
235246
if offset+32+size > len(output) {
236247
return nil, fmt.Errorf("abi: cannot marshal in to go type: length insufficient %d require %d", len(output), offset+32+size)
237248
}
@@ -245,32 +256,9 @@ func toGoType(i int, t Argument, output []byte) (interface{}, error) {
245256
// convert the bytes to whatever is specified by the ABI.
246257
switch t.Type.T {
247258
case IntTy, UintTy:
248-
bigNum := common.BytesToBig(returnOutput)
249-
250-
// If the type is a integer convert to the integer type
251-
// specified by the ABI.
252-
switch t.Type.Kind {
253-
case reflect.Uint8:
254-
return uint8(bigNum.Uint64()), nil
255-
case reflect.Uint16:
256-
return uint16(bigNum.Uint64()), nil
257-
case reflect.Uint32:
258-
return uint32(bigNum.Uint64()), nil
259-
case reflect.Uint64:
260-
return uint64(bigNum.Uint64()), nil
261-
case reflect.Int8:
262-
return int8(bigNum.Int64()), nil
263-
case reflect.Int16:
264-
return int16(bigNum.Int64()), nil
265-
case reflect.Int32:
266-
return int32(bigNum.Int64()), nil
267-
case reflect.Int64:
268-
return int64(bigNum.Int64()), nil
269-
case reflect.Ptr:
270-
return bigNum, nil
271-
}
259+
return readInteger(t.Type.Kind, returnOutput), nil
272260
case BoolTy:
273-
return common.BytesToBig(returnOutput).Uint64() > 0, nil
261+
return !allZero(returnOutput), nil
274262
case AddressTy:
275263
return common.BytesToAddress(returnOutput), nil
276264
case HashTy:

‎accounts/abi/bind/backends/simulated.go‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"github.com/ethereum/go-ethereum"
2626
"github.com/ethereum/go-ethereum/accounts/abi/bind"
2727
"github.com/ethereum/go-ethereum/common"
28+
"github.com/ethereum/go-ethereum/common/math"
2829
"github.com/ethereum/go-ethereum/core"
2930
"github.com/ethereum/go-ethereum/core/state"
3031
"github.com/ethereum/go-ethereum/core/types"
@@ -244,15 +245,15 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
244245
}
245246
// Set infinite balance to the fake caller account.
246247
from := statedb.GetOrNewStateObject(call.From)
247-
from.SetBalance(common.MaxBig)
248+
from.SetBalance(math.MaxBig256)
248249
// Execute the call.
249250
msg := callmsg{call}
250251

251252
evmContext := core.NewEVMContext(msg, block.Header(), b.blockchain)
252253
// Create a new environment which holds all relevant information
253254
// about the transaction and calling mechanisms.
254255
vmenv := vm.NewEVM(evmContext, statedb, chainConfig, vm.Config{})
255-
gaspool := new(core.GasPool).AddGas(common.MaxBig)
256+
gaspool := new(core.GasPool).AddGas(math.MaxBig256)
256257
ret, gasUsed, _, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb()
257258
return ret, gasUsed, err
258259
}

‎accounts/abi/numbers.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"reflect"
2222

2323
"github.com/ethereum/go-ethereum/common"
24+
"github.com/ethereum/go-ethereum/common/math"
2425
)
2526

2627
var (
@@ -58,7 +59,7 @@ var (
5859

5960
// U256 converts a big Int into a 256bit EVM number.
6061
func U256(n *big.Int) []byte {
61-
return common.LeftPadBytes(common.U256(n).Bytes(), 32)
62+
return common.LeftPadBytes(math.U256(n).Bytes(), 32)
6263
}
6364

6465
// packNum packs the given number (using the reflect value) and will cast it to appropriate number representation

‎cmd/evm/main.go‎

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ package main
2020
import (
2121
"fmt"
2222
"io/ioutil"
23+
"math/big"
2324
"os"
2425
goruntime "runtime"
2526
"time"
@@ -51,20 +52,20 @@ var (
5152
Name: "codefile",
5253
Usage: "file containing EVM code",
5354
}
54-
GasFlag = cli.StringFlag{
55+
GasFlag = cli.Uint64Flag{
5556
Name: "gas",
5657
Usage: "gas limit for the evm",
57-
Value: "10000000000",
58+
Value: 10000000000,
5859
}
59-
PriceFlag = cli.StringFlag{
60+
PriceFlag = utils.BigFlag{
6061
Name: "price",
6162
Usage: "price set for the evm",
62-
Value: "0",
63+
Value: new(big.Int),
6364
}
64-
ValueFlag = cli.StringFlag{
65+
ValueFlag = utils.BigFlag{
6566
Name: "value",
6667
Usage: "value set for the evm",
67-
Value: "0",
68+
Value: new(big.Int),
6869
}
6970
DumpFlag = cli.BoolFlag{
7071
Name: "dump",
@@ -160,9 +161,9 @@ func run(ctx *cli.Context) error {
160161
ret, _, err = runtime.Create(input, &runtime.Config{
161162
Origin: sender.Address(),
162163
State: statedb,
163-
GasLimit: common.Big(ctx.GlobalString(GasFlag.Name)).Uint64(),
164-
GasPrice: common.Big(ctx.GlobalString(PriceFlag.Name)),
165-
Value: common.Big(ctx.GlobalString(ValueFlag.Name)),
164+
GasLimit: ctx.GlobalUint64(GasFlag.Name),
165+
GasPrice: utils.GlobalBig(ctx, PriceFlag.Name),
166+
Value: utils.GlobalBig(ctx, ValueFlag.Name),
166167
EVMConfig: vm.Config{
167168
Tracer: logger,
168169
Debug: ctx.GlobalBool(DebugFlag.Name),
@@ -177,9 +178,9 @@ func run(ctx *cli.Context) error {
177178
ret, err = runtime.Call(receiverAddress, common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)), &runtime.Config{
178179
Origin: sender.Address(),
179180
State: statedb,
180-
GasLimit: common.Big(ctx.GlobalString(GasFlag.Name)).Uint64(),
181-
GasPrice: common.Big(ctx.GlobalString(PriceFlag.Name)),
182-
Value: common.Big(ctx.GlobalString(ValueFlag.Name)),
181+
GasLimit: ctx.GlobalUint64(GasFlag.Name),
182+
GasPrice: utils.GlobalBig(ctx, PriceFlag.Name),
183+
Value: utils.GlobalBig(ctx, ValueFlag.Name),
183184
EVMConfig: vm.Config{
184185
Tracer: logger,
185186
Debug: ctx.GlobalBool(DebugFlag.Name),

‎cmd/utils/cmd.go‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,9 @@ import (
2323
"io"
2424
"os"
2525
"os/signal"
26-
"regexp"
2726
"runtime"
2827
"strings"
2928

30-
"github.com/ethereum/go-ethereum/common"
3129
"github.com/ethereum/go-ethereum/core"
3230
"github.com/ethereum/go-ethereum/core/types"
3331
"github.com/ethereum/go-ethereum/internal/debug"
@@ -82,19 +80,6 @@ func StartNode(stack *node.Node) {
8280
}()
8381
}
8482

85-
func FormatTransactionData(data string) []byte {
86-
d := common.StringToByteFunc(data, func(s string) (ret []byte) {
87-
slice := regexp.MustCompile(`\n|\s`).Split(s, 1000000000)
88-
for _, dataItem := range slice {
89-
d := common.FormatData(dataItem)
90-
ret = append(ret, d...)
91-
}
92-
return
93-
})
94-
95-
return d
96-
}
97-
9883
func ImportChain(chain *core.BlockChain, fn string) error {
9984
// Watch for Ctrl-C while the import is running.
10085
// If a signal is received, the import will stop at the next batch.

0 commit comments

Comments
 (0)