本文整理匯總了Golang中github.com/ethereum/go-ethereum/common.LeftPadBytes函數的典型用法代碼示例。如果您正苦於以下問題:Golang LeftPadBytes函數的具體用法?Golang LeftPadBytes怎麽用?Golang LeftPadBytes使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了LeftPadBytes函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestLargeData
func TestLargeData(t *testing.T) {
trie := NewEmpty()
vals := make(map[string]*kv)
for i := byte(0); i < 255; i++ {
value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
value2 := &kv{common.LeftPadBytes([]byte{10, i}, 32), []byte{i}, false}
trie.Update(value.k, value.v)
trie.Update(value2.k, value2.v)
vals[string(value.k)] = value
vals[string(value2.k)] = value2
}
it := trie.Iterator()
for it.Next() {
vals[string(it.Key)].t = true
}
var untouched []*kv
for _, value := range vals {
if !value.t {
untouched = append(untouched, value)
}
}
if len(untouched) > 0 {
t.Errorf("Missed %d nodes", len(untouched))
for _, value := range untouched {
t.Error(value)
}
}
}
示例2: packElement
// packElement packs the given reflect value according to the abi specification in
// t.
func packElement(t Type, reflectValue reflect.Value) []byte {
switch t.T {
case IntTy, UintTy:
return packNum(reflectValue, t.T)
case StringTy:
return packBytesSlice([]byte(reflectValue.String()), reflectValue.Len())
case AddressTy:
if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue)
}
return common.LeftPadBytes(reflectValue.Bytes(), 32)
case BoolTy:
if reflectValue.Bool() {
return common.LeftPadBytes(common.Big1.Bytes(), 32)
} else {
return common.LeftPadBytes(common.Big0.Bytes(), 32)
}
case BytesTy:
if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue)
}
return packBytesSlice(reflectValue.Bytes(), reflectValue.Len())
case FixedBytesTy:
if reflectValue.Kind() == reflect.Array {
reflectValue = mustArrayToByteSlice(reflectValue)
}
return common.RightPadBytes(reflectValue.Bytes(), 32)
}
panic("abi: fatal error")
}
示例3: makeTestTrie
// makeTestTrie create a sample test trie to test node-wise reconstruction.
func makeTestTrie() (ethdb.Database, *Trie, map[string][]byte) {
// Create an empty trie
db, _ := ethdb.NewMemDatabase()
trie, _ := New(common.Hash{}, db)
// Fill it with some arbitrary data
content := make(map[string][]byte)
for i := byte(0); i < 255; i++ {
// Map the same data under multiple keys
key, val := common.LeftPadBytes([]byte{1, i}, 32), []byte{i}
content[string(key)] = val
trie.Update(key, val)
key, val = common.LeftPadBytes([]byte{2, i}, 32), []byte{i}
content[string(key)] = val
trie.Update(key, val)
// Add some other data to inflate th trie
for j := byte(3); j < 13; j++ {
key, val = common.LeftPadBytes([]byte{j, i}, 32), []byte{j, i}
content[string(key)] = val
trie.Update(key, val)
}
}
trie.Commit()
// Remove any potentially cached data from the test trie creation
globalCache.Clear()
// Return the generated trie
return db, trie, content
}
示例4: PrecompiledContracts
// XXX Could set directly. Testing requires resetting and setting of pre compiled contracts.
func PrecompiledContracts() map[string]*PrecompiledAccount {
return map[string]*PrecompiledAccount{
// ECRECOVER
string(common.LeftPadBytes([]byte{1}, 20)): &PrecompiledAccount{func(l int) *big.Int {
return params.EcrecoverGas
}, ecrecoverFunc},
// SHA256
string(common.LeftPadBytes([]byte{2}, 20)): &PrecompiledAccount{func(l int) *big.Int {
n := big.NewInt(int64(l+31) / 32)
n.Mul(n, params.Sha256WordGas)
return n.Add(n, params.Sha256Gas)
}, sha256Func},
// RIPEMD160
string(common.LeftPadBytes([]byte{3}, 20)): &PrecompiledAccount{func(l int) *big.Int {
n := big.NewInt(int64(l+31) / 32)
n.Mul(n, params.Ripemd160WordGas)
return n.Add(n, params.Ripemd160Gas)
}, ripemd160Func},
string(common.LeftPadBytes([]byte{4}, 20)): &PrecompiledAccount{func(l int) *big.Int {
n := big.NewInt(int64(l+31) / 32)
n.Mul(n, params.IdentityWordGas)
return n.Add(n, params.IdentityGas)
}, memCpy},
}
}
示例5: pack
// Test the given input parameter `v` and checks if it matches certain
// criteria
// * Big integers are checks for ptr types and if the given value is
// assignable
// * Integer are checked for size
// * Strings, addresses and bytes are checks for type and size
func (t Type) pack(v interface{}) ([]byte, error) {
value := reflect.ValueOf(v)
switch kind := value.Kind(); kind {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if t.Type != ubig_t {
return nil, fmt.Errorf("type mismatch: %s for %T", t.Type, v)
}
return packNum(value, t.T), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if t.Type != ubig_t {
return nil, fmt.Errorf("type mismatch: %s for %T", t.Type, v)
}
return packNum(value, t.T), nil
case reflect.Ptr:
// If the value is a ptr do a assign check (only used by
// big.Int for now)
if t.Type == ubig_t && value.Type() != ubig_t {
return nil, fmt.Errorf("type mismatch: %s for %T", t.Type, v)
}
return packNum(value, t.T), nil
case reflect.String:
if t.Size > -1 && value.Len() > t.Size {
return nil, fmt.Errorf("%v out of bound. %d for %d", value.Kind(), value.Len(), t.Size)
}
return []byte(common.LeftPadString(t.String(), 32)), nil
case reflect.Slice:
if t.Size > -1 && value.Len() > t.Size {
return nil, fmt.Errorf("%v out of bound. %d for %d", value.Kind(), value.Len(), t.Size)
}
// Address is a special slice. The slice acts as one rather than a list of elements.
if t.T == AddressTy {
return common.LeftPadBytes(v.([]byte), 32), nil
}
// Signed / Unsigned check
if (t.T != IntTy && isSigned(value)) || (t.T == UintTy && isSigned(value)) {
return nil, fmt.Errorf("slice of incompatible types.")
}
var packed []byte
for i := 0; i < value.Len(); i++ {
packed = append(packed, packNum(value.Index(i), t.T)...)
}
return packed, nil
case reflect.Bool:
if value.Bool() {
return common.LeftPadBytes(common.Big1.Bytes(), 32), nil
} else {
return common.LeftPadBytes(common.Big0.Bytes(), 32), nil
}
}
panic("unreached")
}
示例6: sha3
// sha3 returns the canonical sha3 of the 32byte (padded) input
func sha3(in ...[]byte) []byte {
out := make([]byte, len(in)*32)
for i, input := range in {
copy(out[i*32:i*32+32], common.LeftPadBytes(input, 32))
}
return crypto.Sha3(out)
}
示例7: ecrecoverFunc
func ecrecoverFunc(in []byte) []byte {
in = common.RightPadBytes(in, 128)
// "in" is (hash, v, r, s), each 32 bytes
// but for ecrecover we want (r, s, v)
r := common.BytesToBig(in[64:96])
s := common.BytesToBig(in[96:128])
// Treat V as a 256bit integer
vbig := common.Bytes2Big(in[32:64])
v := byte(vbig.Uint64())
if !crypto.ValidateSignatureValues(v, r, s) {
glog.V(logger.Error).Infof("EC RECOVER FAIL: v, r or s value invalid")
return nil
}
// v needs to be at the end and normalized for libsecp256k1
vbignormal := new(big.Int).Sub(vbig, big.NewInt(27))
vnormal := byte(vbignormal.Uint64())
rsv := append(in[64:128], vnormal)
pubKey, err := crypto.Ecrecover(in[:32], rsv)
// make sure the public key is a valid one
if err != nil {
glog.V(logger.Error).Infof("EC RECOVER FAIL: ", err)
return nil
}
// the first byte of pubkey is bitcoin heritage
return common.LeftPadBytes(crypto.Sha3(pubKey[1:])[12:], 32)
}
示例8: ecrecoverFunc
func ecrecoverFunc(in []byte) []byte {
// "in" is (hash, v, r, s), each 32 bytes
// but for ecrecover we want (r, s, v)
if len(in) < ecRecoverInputLength {
return nil
}
// Treat V as a 256bit integer
v := new(big.Int).Sub(common.Bytes2Big(in[32:64]), big.NewInt(27))
// Ethereum requires V to be either 0 or 1 => (27 || 28)
if !(v.Cmp(Zero) == 0 || v.Cmp(One) == 0) {
return nil
}
// v needs to be moved to the end
rsv := append(in[64:128], byte(v.Uint64()))
pubKey, err := crypto.Ecrecover(in[:32], rsv)
// make sure the public key is a valid one
if err != nil {
glog.V(logger.Error).Infof("EC RECOVER FAIL: ", err)
return nil
}
// the first byte of pubkey is bitcoin heritage
return common.LeftPadBytes(crypto.Sha3(pubKey[1:])[12:], 32)
}
示例9: checkLogs
func checkLogs(tlog []Log, logs state.Logs) error {
if len(tlog) != len(logs) {
return fmt.Errorf("log length mismatch. Expected %d, got %d", len(tlog), len(logs))
} else {
for i, log := range tlog {
if common.HexToAddress(log.AddressF) != logs[i].Address {
return fmt.Errorf("log address expected %v got %x", log.AddressF, logs[i].Address)
}
if !bytes.Equal(logs[i].Data, common.FromHex(log.DataF)) {
return fmt.Errorf("log data expected %v got %x", log.DataF, logs[i].Data)
}
if len(log.TopicsF) != len(logs[i].Topics) {
return fmt.Errorf("log topics length expected %d got %d", len(log.TopicsF), logs[i].Topics)
} else {
for j, topic := range log.TopicsF {
if common.HexToHash(topic) != logs[i].Topics[j] {
return fmt.Errorf("log topic[%d] expected %v got %x", j, topic, logs[i].Topics[j])
}
}
}
genBloom := common.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256)
if !bytes.Equal(genBloom, common.Hex2Bytes(log.BloomF)) {
return fmt.Errorf("bloom mismatch")
}
}
}
return nil
}
示例10: Sign
func Sign(hash []byte, prv *ecdsa.PrivateKey) (sig []byte, err error) {
if len(hash) != 32 {
return nil, fmt.Errorf("hash is required to be exactly 32 bytes (%d)", len(hash))
}
sig, err = secp256k1.Sign(hash, common.LeftPadBytes(prv.D.Bytes(), prv.Params().BitSize/8))
return
}
示例11: TestMarshalArrays
func TestMarshalArrays(t *testing.T) {
const definition = `[
{ "name" : "bytes32", "constant" : false, "outputs": [ { "type": "bytes32" } ] },
{ "name" : "bytes10", "constant" : false, "outputs": [ { "type": "bytes10" } ] }
]`
abi, err := JSON(strings.NewReader(definition))
if err != nil {
t.Fatal(err)
}
output := common.LeftPadBytes([]byte{1}, 32)
var bytes10 [10]byte
err = abi.Unpack(&bytes10, "bytes32", output)
if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
t.Error("expected error or bytes32 not be assignable to bytes10:", err)
}
var bytes32 [32]byte
err = abi.Unpack(&bytes32, "bytes32", output)
if err != nil {
t.Error("didn't expect error:", err)
}
if !bytes.Equal(bytes32[:], output) {
t.Error("expected bytes32[31] to be 1 got", bytes32[31])
}
type (
B10 [10]byte
B32 [32]byte
)
var b10 B10
err = abi.Unpack(&b10, "bytes32", output)
if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
t.Error("expected error or bytes32 not be assignable to bytes10:", err)
}
var b32 B32
err = abi.Unpack(&b32, "bytes32", output)
if err != nil {
t.Error("didn't expect error:", err)
}
if !bytes.Equal(b32[:], output) {
t.Error("expected bytes32[31] to be 1 got", bytes32[31])
}
output[10] = 1
var shortAssignLong [32]byte
err = abi.Unpack(&shortAssignLong, "bytes10", output)
if err != nil {
t.Error("didn't expect error:", err)
}
if !bytes.Equal(output, shortAssignLong[:]) {
t.Errorf("expected %x to be %x", shortAssignLong, output)
}
}
示例12: randomTrie
func randomTrie(n int) (*Trie, map[string]*kv) {
trie := new(Trie)
vals := make(map[string]*kv)
for i := byte(0); i < 100; i++ {
value := &kv{common.LeftPadBytes([]byte{i}, 32), []byte{i}, false}
value2 := &kv{common.LeftPadBytes([]byte{i + 10}, 32), []byte{i}, false}
trie.Update(value.k, value.v)
trie.Update(value2.k, value2.v)
vals[string(value.k)] = value
vals[string(value2.k)] = value2
}
for i := 0; i < n; i++ {
value := &kv{randBytes(32), randBytes(20), false}
trie.Update(value.k, value.v)
vals[string(value.k)] = value
}
return trie, vals
}
示例13: opByte
func opByte(instr instruction, env Environment, context *Context, memory *Memory, stack *stack) {
th, val := stack.pop(), stack.pop()
if th.Cmp(big.NewInt(32)) < 0 {
byte := big.NewInt(int64(common.LeftPadBytes(val.Bytes(), 32)[th.Int64()]))
stack.push(byte)
} else {
stack.push(new(big.Int))
}
}
示例14: StdErrFormat
func StdErrFormat(logs []StructLog) {
fmt.Fprintf(os.Stderr, "VM STAT %d OPs\n", len(logs))
for _, log := range logs {
fmt.Fprintf(os.Stderr, "PC %08d: %s GAS: %v COST: %v", log.Pc, log.Op, log.Gas, log.GasCost)
if log.Err != nil {
fmt.Fprintf(os.Stderr, " ERROR: %v", log.Err)
}
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintln(os.Stderr, "STACK =", len(log.Stack))
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))
}
const maxMem = 10
addr := 0
fmt.Fprintln(os.Stderr, "MEM =", len(log.Memory))
for i := 0; i+16 <= len(log.Memory) && addr < maxMem; i += 16 {
data := log.Memory[i : i+16]
str := fmt.Sprintf("%04d: % x ", addr*16, data)
for _, r := range data {
if r == 0 {
str += "."
} else if unicode.IsPrint(rune(r)) {
str += fmt.Sprintf("%s", string(r))
} else {
str += "?"
}
}
addr++
fmt.Fprintln(os.Stderr, str)
}
fmt.Fprintln(os.Stderr, "STORAGE =", len(log.Storage))
for h, item := range log.Storage {
fmt.Fprintf(os.Stderr, "%x: %x\n", h, common.LeftPadBytes(item, 32))
}
fmt.Fprintln(os.Stderr)
}
}
示例15: makeTestTrie
// makeTestTrie create a sample test trie to test node-wise reconstruction.
func makeTestTrie() (ethdb.Database, *Trie, map[string][]byte) {
// Create an empty trie
db, _ := ethdb.NewMemDatabase()
trie, _ := New(common.Hash{}, db)
// Fill it with some arbitrary data
content := make(map[string][]byte)
for i := byte(0); i < 255; i++ {
key, val := common.LeftPadBytes([]byte{1, i}, 32), []byte{i}
content[string(key)] = val
trie.Update(key, val)
key, val = common.LeftPadBytes([]byte{2, i}, 32), []byte{i}
content[string(key)] = val
trie.Update(key, val)
}
trie.Commit()
// Return the generated trie
return db, trie, content
}