Skip to content

Commit

Permalink
all: unify big.Int zero checks, use common/math in more places (ether…
Browse files Browse the repository at this point in the history
…eum#3716)

* common/math: optimize PaddedBigBytes, use it more

name              old time/op    new time/op    delta
PaddedBigBytes-8    71.1ns ± 5%    46.1ns ± 1%  -35.15%  (p=0.000 n=20+19)

name              old alloc/op   new alloc/op   delta
PaddedBigBytes-8     48.0B ± 0%     32.0B ± 0%  -33.33%  (p=0.000 n=20+20)

* all: unify big.Int zero checks

Various checks were in use. This commit replaces them all with Int.Sign,
which is cheaper and less code.

eg templates:

    func before(x *big.Int) bool { return x.BitLen() == 0 }
    func after(x *big.Int) bool  { return x.Sign() == 0 }

    func before(x *big.Int) bool { return x.BitLen() > 0 }
    func after(x *big.Int) bool  { return x.Sign() != 0 }

    func before(x *big.Int) int { return x.Cmp(common.Big0) }
    func after(x *big.Int) int  { return x.Sign() }

* common/math, crypto/secp256k1: make ReadBits public in package math
  • Loading branch information
fjl authored and obscuren committed Feb 28, 2017
1 parent d4f60d3 commit 5f78262
Show file tree
Hide file tree
Showing 30 changed files with 104 additions and 114 deletions.
2 changes: 1 addition & 1 deletion accounts/abi/bind/backends/simulated.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM
if call.GasPrice == nil {
call.GasPrice = big.NewInt(1)
}
if call.Gas == nil || call.Gas.BitLen() == 0 {
if call.Gas == nil || call.Gas.Sign() == 0 {
call.Gas = big.NewInt(50000000)
}
if call.Value == nil {
Expand Down
2 changes: 1 addition & 1 deletion accounts/abi/numbers.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ var (

// U256 converts a big Int into a 256bit EVM number.
func U256(n *big.Int) []byte {
return common.LeftPadBytes(math.U256(n).Bytes(), 32)
return math.PaddedBigBytes(math.U256(n), 32)
}

// packNum packs the given number (using the reflect value) and will cast it to appropriate number representation
Expand Down
5 changes: 3 additions & 2 deletions accounts/abi/packing.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"reflect"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
)

// packBytesSlice packs the given bytes as [L, V] as the canonical representation
Expand All @@ -45,9 +46,9 @@ func packElement(t Type, reflectValue reflect.Value) []byte {
return common.LeftPadBytes(reflectValue.Bytes(), 32)
case BoolTy:
if reflectValue.Bool() {
return common.LeftPadBytes(common.Big1.Bytes(), 32)
return math.PaddedBigBytes(common.Big1, 32)
} else {
return common.LeftPadBytes(common.Big0.Bytes(), 32)
return math.PaddedBigBytes(common.Big0, 32)
}
case BytesTy:
if reflectValue.Kind() == reflect.Array {
Expand Down
4 changes: 2 additions & 2 deletions accounts/keystore/keystore_passphrase.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import (
"path/filepath"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/crypto/randentropy"
"github.com/pborman/uuid"
Expand Down Expand Up @@ -115,8 +116,7 @@ func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) {
return nil, err
}
encryptKey := derivedKey[:16]
keyBytes0 := crypto.FromECDSA(key.PrivateKey)
keyBytes := common.LeftPadBytes(keyBytes0, 32)
keyBytes := math.PaddedBigBytes(key.PrivateKey.D, 32)

iv := randentropy.GetEntropyCSPRNG(aes.BlockSize) // 16
cipherText, err := aesCTRXOR(encryptKey, keyBytes, iv)
Expand Down
2 changes: 1 addition & 1 deletion accounts/usbwallet/ledger_wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ func (w *ledgerWallet) selfDerive() {
break
}
// If the next account is empty, stop self-derivation, but add it nonetheless
if balance.BitLen() == 0 && nonce == 0 {
if balance.Sign() == 0 && nonce == 0 {
empty = true
}
// We've just self-derived a new account, start tracking it locally
Expand Down
33 changes: 25 additions & 8 deletions common/math/big.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ var (
MaxBig256 = new(big.Int).Set(tt256m1)
)

const (
// number of bits in a big.Word
wordBits = 32 << (uint64(^big.Word(0)) >> 63)
// number of bytes in a big.Word
wordBytes = wordBits / 8
)

// ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
// Leading zeros are accepted. The empty string parses as zero.
func ParseBig256(s string) (*big.Int, bool) {
Expand Down Expand Up @@ -91,12 +98,25 @@ func FirstBitSet(v *big.Int) int {
// PaddedBigBytes encodes a big integer as a big-endian byte slice. The length
// of the slice is at least n bytes.
func PaddedBigBytes(bigint *big.Int, n int) []byte {
bytes := bigint.Bytes()
if len(bytes) >= n {
return bytes
if bigint.BitLen()/8 >= n {
return bigint.Bytes()
}
ret := make([]byte, n)
return append(ret[:len(ret)-len(bytes)], bytes...)
ReadBits(bigint, ret)
return ret
}

// ReadBits encodes the absolute value of bigint as big-endian bytes. Callers must ensure
// that buf has enough space. If buf is too short the result will be incomplete.
func ReadBits(bigint *big.Int, buf []byte) {
i := len(buf)
for _, d := range bigint.Bits() {
for j := 0; j < wordBytes && i > 0; j++ {
i--
buf[i] = byte(d)
d >>= 8
}
}
}

// U256 encodes as a 256 bit two's complement number. This operation is destructive.
Expand All @@ -119,9 +139,6 @@ func S256(x *big.Int) *big.Int {
}
}

// wordSize is the size number of bits in a big.Word.
const wordSize = 32 << (uint64(^big.Word(0)) >> 63)

// Exp implements exponentiation by squaring.
// Exp returns a newly-allocated big integer and does not change
// base or exponent. The result is truncated to 256 bits.
Expand All @@ -131,7 +148,7 @@ func Exp(base, exponent *big.Int) *big.Int {
result := big.NewInt(1)

for _, word := range exponent.Bits() {
for i := 0; i < wordSize; i++ {
for i := 0; i < wordBits; i++ {
if word&1 == 1 {
U256(result.Mul(result, base))
}
Expand Down
23 changes: 23 additions & 0 deletions common/math/big_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package math

import (
"bytes"
"encoding/hex"
"math/big"
"testing"
)
Expand Down Expand Up @@ -131,6 +132,28 @@ func TestPaddedBigBytes(t *testing.T) {
}
}

func BenchmarkPaddedBigBytes(b *testing.B) {
bigint := MustParseBig256("123456789123456789123456789123456789")
for i := 0; i < b.N; i++ {
PaddedBigBytes(bigint, 32)
}
}

func TestReadBits(t *testing.T) {
check := func(input string) {
want, _ := hex.DecodeString(input)
int, _ := new(big.Int).SetString(input, 16)
buf := make([]byte, len(want))
ReadBits(int, buf)
if !bytes.Equal(buf, want) {
t.Errorf("have: %x\nwant: %x", buf, want)
}
}
check("000000000000000000000000000000000000000000000000000000FEFCF3F8F0")
check("0000000000012345000000000000000000000000000000000000FEFCF3F8F0")
check("18F8F8F1000111000110011100222004330052300000000000000000FEFCF3F8F0")
}

func TestU256(t *testing.T) {
tests := []struct{ x, y *big.Int }{
{x: big.NewInt(0), y: big.NewInt(0)},
Expand Down
6 changes: 3 additions & 3 deletions contracts/chequebook/cheque.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ func (self *Chequebook) Issue(beneficiary common.Address, amount *big.Int) (ch *
defer self.lock.Unlock()
self.lock.Lock()

if amount.Cmp(common.Big0) <= 0 {
if amount.Sign() <= 0 {
return nil, fmt.Errorf("amount must be greater than zero (%v)", amount)
}
if self.balance.Cmp(amount) < 0 {
Expand Down Expand Up @@ -515,7 +515,7 @@ func (self *Inbox) autoCash(cashInterval time.Duration) {
self.quit = nil
}
// if maxUncashed is set to 0, then autocash on receipt
if cashInterval == time.Duration(0) || self.maxUncashed != nil && self.maxUncashed.Cmp(common.Big0) == 0 {
if cashInterval == time.Duration(0) || self.maxUncashed != nil && self.maxUncashed.Sign() == 0 {
return
}

Expand Down Expand Up @@ -597,7 +597,7 @@ func (self *Cheque) Verify(signerKey *ecdsa.PublicKey, contract, beneficiary com
amount := new(big.Int).Set(self.Amount)
if sum != nil {
amount.Sub(amount, sum)
if amount.Cmp(common.Big0) <= 0 {
if amount.Sign() <= 0 {
return nil, fmt.Errorf("incorrect amount: %v <= 0", amount)
}
}
Expand Down
2 changes: 1 addition & 1 deletion contracts/chequebook/cheque_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func TestIssueAndReceive(t *testing.T) {
t.Fatalf("expected no error, got %v", err)
}

if chbook.Balance().Cmp(common.Big0) != 0 {
if chbook.Balance().Sign() != 0 {
t.Errorf("expected: %v, got %v", "0", chbook.Balance())
}

Expand Down
2 changes: 1 addition & 1 deletion core/headerchain.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,7 @@ func (hc *HeaderChain) GetBlockHashesFromHash(hash common.Hash, max uint64) []co
break
}
chain = append(chain, next)
if header.Number.Cmp(common.Big0) == 0 {
if header.Number.Sign() == 0 {
break
}
}
Expand Down
6 changes: 3 additions & 3 deletions core/state/state_object.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ type stateObject struct {

// empty returns whether the account is considered empty.
func (s *stateObject) empty() bool {
return s.data.Nonce == 0 && s.data.Balance.BitLen() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
}

// Account is the Ethereum consensus representation of accounts.
Expand Down Expand Up @@ -243,7 +243,7 @@ func (self *stateObject) CommitTrie(db trie.Database, dbw trie.DatabaseWriter) e
func (c *stateObject) AddBalance(amount *big.Int) {
// EIP158: We must check emptiness for the objects such that the account
// clearing (0,0,0 objects) can take effect.
if amount.Cmp(common.Big0) == 0 {
if amount.Sign() == 0 {
if c.empty() {
c.touch()
}
Expand All @@ -260,7 +260,7 @@ func (c *stateObject) AddBalance(amount *big.Int) {
// SubBalance removes amount from c's balance.
// It is used to remove funds from the origin account of a transfer.
func (c *stateObject) SubBalance(amount *big.Int) {
if amount.Cmp(common.Big0) == 0 {
if amount.Sign() == 0 {
return
}
c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
Expand Down
2 changes: 1 addition & 1 deletion core/tx_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ func (pool *TxPool) validateTx(tx *types.Transaction) error {
// Transactions can't be negative. This may never happen
// using RLP decoded transactions but may occur if you create
// a transaction using the RPC for example.
if tx.Value().Cmp(common.Big0) < 0 {
if tx.Value().Sign() < 0 {
return ErrNegativeValue
}

Expand Down
2 changes: 1 addition & 1 deletion core/types/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ var (

// deriveSigner makes a *best* guess about which signer to use.
func deriveSigner(V *big.Int) Signer {
if V.BitLen() > 0 && isProtectedV(V) {
if V.Sign() != 0 && isProtectedV(V) {
return EIP155Signer{chainId: deriveChainId(V)}
} else {
return HomesteadSigner{}
Expand Down
2 changes: 1 addition & 1 deletion core/types/transaction_signing.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func (s EIP155Signer) WithSignature(tx *Transaction, sig []byte) (*Transaction,
cpy.data.R = new(big.Int).SetBytes(sig[:32])
cpy.data.S = new(big.Int).SetBytes(sig[32:64])
cpy.data.V = new(big.Int).SetBytes([]byte{sig[64]})
if s.chainId.BitLen() > 0 {
if s.chainId.Sign() != 0 {
cpy.data.V = big.NewInt(int64(sig[64] + 35))
cpy.data.V.Add(cpy.data.V, s.chainIdMul)
}
Expand Down
2 changes: 1 addition & 1 deletion core/types/transaction_signing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestEIP155ChainId(t *testing.T) {
t.Error("didn't expect tx to be protected")
}

if tx.ChainId().BitLen() > 0 {
if tx.ChainId().Sign() != 0 {
t.Error("expected chain id to be 0 got", tx.ChainId())
}
}
Expand Down
2 changes: 1 addition & 1 deletion core/vm/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (

// calculates the memory size required for a step
func calcMemSize(off, l *big.Int) *big.Int {
if l.Cmp(common.Big0) == 0 {
if l.Sign() == 0 {
return common.Big0
}

Expand Down
2 changes: 1 addition & 1 deletion core/vm/evm.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas
snapshot = evm.StateDB.Snapshot()
)
if !evm.StateDB.Exist(addr) {
if PrecompiledContracts[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.BitLen() == 0 {
if PrecompiledContracts[addr] == nil && evm.ChainConfig().IsEIP158(evm.BlockNumber) && value.Sign() == 0 {
return nil, gas, nil
}

Expand Down
6 changes: 3 additions & 3 deletions core/vm/gas_table.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ func gasExp(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem
func gasCall(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
var (
gas = gt.Calls
transfersValue = stack.Back(2).BitLen() > 0
transfersValue = stack.Back(2).Sign() != 0
address = common.BigToAddress(stack.Back(1))
eip158 = evm.ChainConfig().IsEIP158(evm.BlockNumber)
)
Expand Down Expand Up @@ -316,7 +316,7 @@ func gasCall(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem

func gasCallCode(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {
gas := gt.Calls
if stack.Back(2).BitLen() > 0 {
if stack.Back(2).Sign() != 0 {
gas += params.CallValueTransferGas
}
memoryGas, err := memoryGasCost(mem, memorySize)
Expand Down Expand Up @@ -362,7 +362,7 @@ func gasSuicide(gt params.GasTable, evm *EVM, contract *Contract, stack *Stack,

if eip158 {
// if empty and transfers value
if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).BitLen() > 0 {
if evm.StateDB.Empty(address) && evm.StateDB.GetBalance(contract.Address()).Sign() != 0 {
gas += gt.CreateBySuicide
}
} else if !evm.StateDB.Exist(address) {
Expand Down
Loading

0 comments on commit 5f78262

Please sign in to comment.