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)
This commit is contained in:
Felix Lange 2017-02-27 00:32:24 +01:00
parent 5c8fe28b72
commit 32deb62ca8
10 changed files with 45 additions and 19 deletions

View file

@ -59,7 +59,7 @@ var (
// U256 converts a big Int into a 256bit EVM number. // U256 converts a big Int into a 256bit EVM number.
func U256(n *big.Int) []byte { 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 // packNum packs the given number (using the reflect value) and will cast it to appropriate number representation

View file

@ -20,6 +20,7 @@ import (
"reflect" "reflect"
"github.com/ethereum/go-ethereum/common" "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 // packBytesSlice packs the given bytes as [L, V] as the canonical representation
@ -45,9 +46,9 @@ func packElement(t Type, reflectValue reflect.Value) []byte {
return common.LeftPadBytes(reflectValue.Bytes(), 32) return common.LeftPadBytes(reflectValue.Bytes(), 32)
case BoolTy: case BoolTy:
if reflectValue.Bool() { if reflectValue.Bool() {
return common.LeftPadBytes(common.Big1.Bytes(), 32) return math.PaddedBigBytes(common.Big1, 32)
} else { } else {
return common.LeftPadBytes(common.Big0.Bytes(), 32) return math.PaddedBigBytes(common.Big0, 32)
} }
case BytesTy: case BytesTy:
if reflectValue.Kind() == reflect.Array { if reflectValue.Kind() == reflect.Array {

View file

@ -36,6 +36,7 @@ import (
"path/filepath" "path/filepath"
"github.com/ethereum/go-ethereum/common" "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"
"github.com/ethereum/go-ethereum/crypto/randentropy" "github.com/ethereum/go-ethereum/crypto/randentropy"
"github.com/pborman/uuid" "github.com/pborman/uuid"
@ -115,8 +116,7 @@ func EncryptKey(key *Key, auth string, scryptN, scryptP int) ([]byte, error) {
return nil, err return nil, err
} }
encryptKey := derivedKey[:16] encryptKey := derivedKey[:16]
keyBytes0 := crypto.FromECDSA(key.PrivateKey) keyBytes := math.PaddedBigBytes(key.PrivateKey.D, 32)
keyBytes := common.LeftPadBytes(keyBytes0, 32)
iv := randentropy.GetEntropyCSPRNG(aes.BlockSize) // 16 iv := randentropy.GetEntropyCSPRNG(aes.BlockSize) // 16
cipherText, err := aesCTRXOR(encryptKey, keyBytes, iv) cipherText, err := aesCTRXOR(encryptKey, keyBytes, iv)

View file

@ -28,6 +28,13 @@ var (
MaxBig256 = new(big.Int).Set(tt256m1) 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. // ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
// Leading zeros are accepted. The empty string parses as zero. // Leading zeros are accepted. The empty string parses as zero.
func ParseBig256(s string) (*big.Int, bool) { func ParseBig256(s string) (*big.Int, bool) {
@ -91,12 +98,24 @@ func FirstBitSet(v *big.Int) int {
// PaddedBigBytes encodes a big integer as a big-endian byte slice. The length // PaddedBigBytes encodes a big integer as a big-endian byte slice. The length
// of the slice is at least n bytes. // of the slice is at least n bytes.
func PaddedBigBytes(bigint *big.Int, n int) []byte { func PaddedBigBytes(bigint *big.Int, n int) []byte {
bytes := bigint.Bytes() if bigint.BitLen()/8 >= n {
if len(bytes) >= n { return bigint.Bytes()
return bytes
} }
ret := make([]byte, n) ret := make([]byte, n)
return append(ret[:len(ret)-len(bytes)], bytes...) readBits(ret, bigint.Bits())
return ret
}
// reads little-endian words as big-endian bytes into buf.
func readBits(buf []byte, words []big.Word) {
i := len(buf)
for _, d := range words {
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. // U256 encodes as a 256 bit two's complement number. This operation is destructive.
@ -119,9 +138,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 implements exponentiation by squaring.
// Exp returns a newly-allocated big integer and does not change // Exp returns a newly-allocated big integer and does not change
// base or exponent. The result is truncated to 256 bits. // base or exponent. The result is truncated to 256 bits.
@ -131,7 +147,7 @@ func Exp(base, exponent *big.Int) *big.Int {
result := big.NewInt(1) result := big.NewInt(1)
for _, word := range exponent.Bits() { for _, word := range exponent.Bits() {
for i := 0; i < wordSize; i++ { for i := 0; i < wordBits; i++ {
if word&1 == 1 { if word&1 == 1 {
U256(result.Mul(result, base)) U256(result.Mul(result, base))
} }

View file

@ -131,6 +131,13 @@ func TestPaddedBigBytes(t *testing.T) {
} }
} }
func BenchmarkPaddedBigBytes(b *testing.B) {
bigint := MustParseBig256("123456789123456789123456789123456789")
for i := 0; i < b.N; i++ {
PaddedBigBytes(bigint, 32)
}
}
func TestU256(t *testing.T) { func TestU256(t *testing.T) {
tests := []struct{ x, y *big.Int }{ tests := []struct{ x, y *big.Int }{
{x: big.NewInt(0), y: big.NewInt(0)}, {x: big.NewInt(0), y: big.NewInt(0)},

View file

@ -252,10 +252,11 @@ func opXor(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stac
evm.interpreter.intPool.put(y) evm.interpreter.intPool.put(y)
return nil, nil return nil, nil
} }
func opByte(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) { func opByte(pc *uint64, evm *EVM, contract *Contract, memory *Memory, stack *Stack) ([]byte, error) {
th, val := stack.pop(), stack.pop() th, val := stack.pop(), stack.pop()
if th.Cmp(big.NewInt(32)) < 0 { if th.Cmp(big.NewInt(32)) < 0 {
byte := evm.interpreter.intPool.get().SetInt64(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()])) byte := evm.interpreter.intPool.get().SetInt64(int64(math.PaddedBigBytes(val, 32)[th.Int64()]))
stack.push(byte) stack.push(byte)
} else { } else {
stack.push(new(big.Int)) stack.push(new(big.Int))

View file

@ -23,6 +23,7 @@ import (
"unicode" "unicode"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/math"
) )
type Storage map[common.Hash]common.Hash type Storage map[common.Hash]common.Hash
@ -180,7 +181,7 @@ func StdErrFormat(logs []StructLog) {
fmt.Fprintln(os.Stderr, "STACK =", len(log.Stack)) fmt.Fprintln(os.Stderr, "STACK =", len(log.Stack))
for i := len(log.Stack) - 1; i >= 0; i-- { for i := len(log.Stack) - 1; i >= 0; i-- {
fmt.Fprintf(os.Stderr, "%04d: %x\n", len(log.Stack)-i-1, common.LeftPadBytes(log.Stack[i].Bytes(), 32)) fmt.Fprintf(os.Stderr, "%04d: %x\n", len(log.Stack)-i-1, math.PaddedBigBytes(log.Stack[i], 32))
} }
const maxMem = 10 const maxMem = 10

View file

@ -23,7 +23,7 @@ import (
"crypto/elliptic" "crypto/elliptic"
"fmt" "fmt"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/crypto/secp256k1" "github.com/ethereum/go-ethereum/crypto/secp256k1"
) )
@ -53,7 +53,7 @@ func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
if len(hash) != 32 { if len(hash) != 32 {
return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash)) return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
} }
seckey := common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8) seckey := math.PaddedBigBytes(prv.D, prv.Params().BitSize/8)
defer zeroBytes(seckey) defer zeroBytes(seckey)
return secp256k1.Sign(hash, seckey) return secp256k1.Sign(hash, seckey)
} }

View file

@ -720,7 +720,7 @@ func FormatLogs(structLogs []vm.StructLog) []StructLogRes {
} }
for i, stackValue := range trace.Stack { for i, stackValue := range trace.Stack {
formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", common.LeftPadBytes(stackValue.Bytes(), 32)) formattedStructLogs[index].Stack[i] = fmt.Sprintf("%x", math.PaddedBigBytes(stackValue, 32))
} }
for i := 0; i+32 <= len(trace.Memory); i += 32 { for i := 0; i+32 <= len(trace.Memory); i += 32 {

View file

@ -71,7 +71,7 @@ func checkLogs(tlog []Log, logs []*types.Log) error {
} }
} }
} }
genBloom := common.LeftPadBytes(types.LogsBloom([]*types.Log{logs[i]}).Bytes(), 256) genBloom := math.PaddedBigBytes(types.LogsBloom([]*types.Log{logs[i]}), 256)
if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) { if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
return fmt.Errorf("bloom mismatch") return fmt.Errorf("bloom mismatch")