diff options
Diffstat (limited to 'accounts')
25 files changed, 2064 insertions, 457 deletions
diff --git a/accounts/abi/abi.go b/accounts/abi/abi.go index 205dc300b..abcb403db 100644 --- a/accounts/abi/abi.go +++ b/accounts/abi/abi.go @@ -17,6 +17,7 @@ package abi import ( + "bytes" "encoding/json" "fmt" "io" @@ -50,57 +51,52 @@ func JSON(reader io.Reader) (ABI, error) { // methods string signature. (signature = baz(uint32,string32)) func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { // Fetch the ABI of the requested method - var method Method - if name == "" { - method = abi.Constructor - } else { - m, exist := abi.Methods[name] - if !exist { - return nil, fmt.Errorf("method '%s' not found", name) + // constructor + arguments, err := abi.Constructor.Inputs.Pack(args...) + if err != nil { + return nil, err } - method = m + return arguments, nil + } - arguments, err := method.pack(args...) + method, exist := abi.Methods[name] + if !exist { + return nil, fmt.Errorf("method '%s' not found", name) + } + + arguments, err := method.Inputs.Pack(args...) if err != nil { return nil, err } // Pack up the method ID too if not a constructor and return - if name == "" { - return arguments, nil - } return append(method.Id(), arguments...), nil } // Unpack output in v according to the abi specification func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error) { - if err = bytesAreProper(output); err != nil { - return err + if len(output) == 0 { + return fmt.Errorf("abi: unmarshalling empty output") } // since there can't be naming collisions with contracts and events, // we need to decide whether we're calling a method or an event - var unpack unpacker if method, ok := abi.Methods[name]; ok { - unpack = method + if len(output)%32 != 0 { + return fmt.Errorf("abi: improperly formatted output") + } + return method.Outputs.Unpack(v, output) } else if event, ok := abi.Events[name]; ok { - unpack = event - } else { - return fmt.Errorf("abi: could not locate named method or event.") - } - - // requires a struct to unpack into for a tuple return... - if unpack.isTupleReturn() { - return unpack.tupleUnpack(v, output) + return event.Inputs.Unpack(v, output) } - return unpack.singleUnpack(v, output) + return fmt.Errorf("abi: could not locate named method or event") } +// UnmarshalJSON implements json.Unmarshaler interface func (abi *ABI) UnmarshalJSON(data []byte) error { var fields []struct { Type string Name string Constant bool - Indexed bool Anonymous bool Inputs []Argument Outputs []Argument @@ -137,3 +133,14 @@ func (abi *ABI) UnmarshalJSON(data []byte) error { return nil } + +// MethodById looks up a method by the 4-byte id +// returns nil if none found +func (abi *ABI) MethodById(sigdata []byte) *Method { + for _, method := range abi.Methods { + if bytes.Equal(method.Id(), sigdata[:4]) { + return &method + } + } + return nil +} diff --git a/accounts/abi/abi_test.go b/accounts/abi/abi_test.go index 79c4d4a16..2d43b631c 100644 --- a/accounts/abi/abi_test.go +++ b/accounts/abi/abi_test.go @@ -18,13 +18,15 @@ package abi import ( "bytes" + "encoding/hex" "fmt" "log" "math/big" - "reflect" "strings" "testing" + "reflect" + "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" ) @@ -74,9 +76,24 @@ func TestReader(t *testing.T) { } // deep equal fails for some reason - t.Skip() - if !reflect.DeepEqual(abi, exp) { - t.Errorf("\nabi: %v\ndoes not match exp: %v", abi, exp) + for name, expM := range exp.Methods { + gotM, exist := abi.Methods[name] + if !exist { + t.Errorf("Missing expected method %v", name) + } + if !reflect.DeepEqual(gotM, expM) { + t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM) + } + } + + for name, gotM := range abi.Methods { + expM, exist := exp.Methods[name] + if !exist { + t.Errorf("Found extra method %v", name) + } + if !reflect.DeepEqual(gotM, expM) { + t.Errorf("\nGot abi method: \n%v\ndoes not match expected method\n%v", gotM, expM) + } } } @@ -348,6 +365,188 @@ func TestInputVariableInputLength(t *testing.T) { } } +func TestInputFixedArrayAndVariableInputLength(t *testing.T) { + const definition = `[ + { "type" : "function", "name" : "fixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] }, + { "type" : "function", "name" : "fixedArrBytes", "constant" : true, "inputs" : [ { "name" : "str", "type" : "bytes" }, { "name" : "fixedArr", "type" : "uint256[2]" } ] }, + { "type" : "function", "name" : "mixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr", "type": "uint256[2]" }, { "name" : "dynArr", "type": "uint256[]" } ] }, + { "type" : "function", "name" : "doubleFixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type": "uint256[2]" }, { "name" : "fixedArr2", "type": "uint256[3]" } ] }, + { "type" : "function", "name" : "multipleMixedArrStr", "constant" : true, "inputs" : [ { "name" : "str", "type" : "string" }, { "name" : "fixedArr1", "type": "uint256[2]" }, { "name" : "dynArr", "type" : "uint256[]" }, { "name" : "fixedArr2", "type" : "uint256[3]" } ] } + ]` + + abi, err := JSON(strings.NewReader(definition)) + if err != nil { + t.Error(err) + } + + // test string, fixed array uint256[2] + strin := "hello world" + arrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)} + fixedArrStrPack, err := abi.Pack("fixedArrStr", strin, arrin) + if err != nil { + t.Error(err) + } + + // generate expected output + offset := make([]byte, 32) + offset[31] = 96 + length := make([]byte, 32) + length[31] = byte(len(strin)) + strvalue := common.RightPadBytes([]byte(strin), 32) + arrinvalue1 := common.LeftPadBytes(arrin[0].Bytes(), 32) + arrinvalue2 := common.LeftPadBytes(arrin[1].Bytes(), 32) + exp := append(offset, arrinvalue1...) + exp = append(exp, arrinvalue2...) + exp = append(exp, append(length, strvalue...)...) + + // ignore first 4 bytes of the output. This is the function identifier + fixedArrStrPack = fixedArrStrPack[4:] + if !bytes.Equal(fixedArrStrPack, exp) { + t.Errorf("expected %x, got %x\n", exp, fixedArrStrPack) + } + + // test byte array, fixed array uint256[2] + bytesin := []byte(strin) + arrin = [2]*big.Int{big.NewInt(1), big.NewInt(2)} + fixedArrBytesPack, err := abi.Pack("fixedArrBytes", bytesin, arrin) + if err != nil { + t.Error(err) + } + + // generate expected output + offset = make([]byte, 32) + offset[31] = 96 + length = make([]byte, 32) + length[31] = byte(len(strin)) + strvalue = common.RightPadBytes([]byte(strin), 32) + arrinvalue1 = common.LeftPadBytes(arrin[0].Bytes(), 32) + arrinvalue2 = common.LeftPadBytes(arrin[1].Bytes(), 32) + exp = append(offset, arrinvalue1...) + exp = append(exp, arrinvalue2...) + exp = append(exp, append(length, strvalue...)...) + + // ignore first 4 bytes of the output. This is the function identifier + fixedArrBytesPack = fixedArrBytesPack[4:] + if !bytes.Equal(fixedArrBytesPack, exp) { + t.Errorf("expected %x, got %x\n", exp, fixedArrBytesPack) + } + + // test string, fixed array uint256[2], dynamic array uint256[] + strin = "hello world" + fixedarrin := [2]*big.Int{big.NewInt(1), big.NewInt(2)} + dynarrin := []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)} + mixedArrStrPack, err := abi.Pack("mixedArrStr", strin, fixedarrin, dynarrin) + if err != nil { + t.Error(err) + } + + // generate expected output + stroffset := make([]byte, 32) + stroffset[31] = 128 + strlength := make([]byte, 32) + strlength[31] = byte(len(strin)) + strvalue = common.RightPadBytes([]byte(strin), 32) + fixedarrinvalue1 := common.LeftPadBytes(fixedarrin[0].Bytes(), 32) + fixedarrinvalue2 := common.LeftPadBytes(fixedarrin[1].Bytes(), 32) + dynarroffset := make([]byte, 32) + dynarroffset[31] = byte(160 + ((len(strin)/32)+1)*32) + dynarrlength := make([]byte, 32) + dynarrlength[31] = byte(len(dynarrin)) + dynarrinvalue1 := common.LeftPadBytes(dynarrin[0].Bytes(), 32) + dynarrinvalue2 := common.LeftPadBytes(dynarrin[1].Bytes(), 32) + dynarrinvalue3 := common.LeftPadBytes(dynarrin[2].Bytes(), 32) + exp = append(stroffset, fixedarrinvalue1...) + exp = append(exp, fixedarrinvalue2...) + exp = append(exp, dynarroffset...) + exp = append(exp, append(strlength, strvalue...)...) + dynarrarg := append(dynarrlength, dynarrinvalue1...) + dynarrarg = append(dynarrarg, dynarrinvalue2...) + dynarrarg = append(dynarrarg, dynarrinvalue3...) + exp = append(exp, dynarrarg...) + + // ignore first 4 bytes of the output. This is the function identifier + mixedArrStrPack = mixedArrStrPack[4:] + if !bytes.Equal(mixedArrStrPack, exp) { + t.Errorf("expected %x, got %x\n", exp, mixedArrStrPack) + } + + // test string, fixed array uint256[2], fixed array uint256[3] + strin = "hello world" + fixedarrin1 := [2]*big.Int{big.NewInt(1), big.NewInt(2)} + fixedarrin2 := [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)} + doubleFixedArrStrPack, err := abi.Pack("doubleFixedArrStr", strin, fixedarrin1, fixedarrin2) + if err != nil { + t.Error(err) + } + + // generate expected output + stroffset = make([]byte, 32) + stroffset[31] = 192 + strlength = make([]byte, 32) + strlength[31] = byte(len(strin)) + strvalue = common.RightPadBytes([]byte(strin), 32) + fixedarrin1value1 := common.LeftPadBytes(fixedarrin1[0].Bytes(), 32) + fixedarrin1value2 := common.LeftPadBytes(fixedarrin1[1].Bytes(), 32) + fixedarrin2value1 := common.LeftPadBytes(fixedarrin2[0].Bytes(), 32) + fixedarrin2value2 := common.LeftPadBytes(fixedarrin2[1].Bytes(), 32) + fixedarrin2value3 := common.LeftPadBytes(fixedarrin2[2].Bytes(), 32) + exp = append(stroffset, fixedarrin1value1...) + exp = append(exp, fixedarrin1value2...) + exp = append(exp, fixedarrin2value1...) + exp = append(exp, fixedarrin2value2...) + exp = append(exp, fixedarrin2value3...) + exp = append(exp, append(strlength, strvalue...)...) + + // ignore first 4 bytes of the output. This is the function identifier + doubleFixedArrStrPack = doubleFixedArrStrPack[4:] + if !bytes.Equal(doubleFixedArrStrPack, exp) { + t.Errorf("expected %x, got %x\n", exp, doubleFixedArrStrPack) + } + + // test string, fixed array uint256[2], dynamic array uint256[], fixed array uint256[3] + strin = "hello world" + fixedarrin1 = [2]*big.Int{big.NewInt(1), big.NewInt(2)} + dynarrin = []*big.Int{big.NewInt(1), big.NewInt(2)} + fixedarrin2 = [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)} + multipleMixedArrStrPack, err := abi.Pack("multipleMixedArrStr", strin, fixedarrin1, dynarrin, fixedarrin2) + if err != nil { + t.Error(err) + } + + // generate expected output + stroffset = make([]byte, 32) + stroffset[31] = 224 + strlength = make([]byte, 32) + strlength[31] = byte(len(strin)) + strvalue = common.RightPadBytes([]byte(strin), 32) + fixedarrin1value1 = common.LeftPadBytes(fixedarrin1[0].Bytes(), 32) + fixedarrin1value2 = common.LeftPadBytes(fixedarrin1[1].Bytes(), 32) + dynarroffset = U256(big.NewInt(int64(256 + ((len(strin)/32)+1)*32))) + dynarrlength = make([]byte, 32) + dynarrlength[31] = byte(len(dynarrin)) + dynarrinvalue1 = common.LeftPadBytes(dynarrin[0].Bytes(), 32) + dynarrinvalue2 = common.LeftPadBytes(dynarrin[1].Bytes(), 32) + fixedarrin2value1 = common.LeftPadBytes(fixedarrin2[0].Bytes(), 32) + fixedarrin2value2 = common.LeftPadBytes(fixedarrin2[1].Bytes(), 32) + fixedarrin2value3 = common.LeftPadBytes(fixedarrin2[2].Bytes(), 32) + exp = append(stroffset, fixedarrin1value1...) + exp = append(exp, fixedarrin1value2...) + exp = append(exp, dynarroffset...) + exp = append(exp, fixedarrin2value1...) + exp = append(exp, fixedarrin2value2...) + exp = append(exp, fixedarrin2value3...) + exp = append(exp, append(strlength, strvalue...)...) + dynarrarg = append(dynarrlength, dynarrinvalue1...) + dynarrarg = append(dynarrarg, dynarrinvalue2...) + exp = append(exp, dynarrarg...) + + // ignore first 4 bytes of the output. This is the function identifier + multipleMixedArrStrPack = multipleMixedArrStrPack[4:] + if !bytes.Equal(multipleMixedArrStrPack, exp) { + t.Errorf("expected %x, got %x\n", exp, multipleMixedArrStrPack) + } +} + func TestDefaultFunctionParsing(t *testing.T) { const definition = `[{ "name" : "balance" }]` @@ -418,3 +617,82 @@ func TestBareEvents(t *testing.T) { } } } + +// TestUnpackEvent is based on this contract: +// contract T { +// event received(address sender, uint amount, bytes memo); +// function receive(bytes memo) external payable { +// received(msg.sender, msg.value, memo); +// } +// } +// When receive("X") is called with sender 0x00... and value 1, it produces this tx receipt: +// receipt{status=1 cgas=23949 bloom=00000000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000040200000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 logs=[log: b6818c8064f645cd82d99b59a1a267d6d61117ef [75fd880d39c1daf53b6547ab6cb59451fc6452d27caa90e5b6649dd8293b9eed] 000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158 9ae378b6d4409eada347a5dc0c180f186cb62dc68fcc0f043425eb917335aa28 0 95d429d309bb9d753954195fe2d69bd140b4ae731b9b5b605c34323de162cf00 0]} +func TestUnpackEvent(t *testing.T) { + const abiJSON = `[{"constant":false,"inputs":[{"name":"memo","type":"bytes"}],"name":"receive","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}],"name":"received","type":"event"}]` + abi, err := JSON(strings.NewReader(abiJSON)) + if err != nil { + t.Fatal(err) + } + + const hexdata = `000000000000000000000000376c47978271565f56deb45495afa69e59c16ab200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000158` + data, err := hex.DecodeString(hexdata) + if err != nil { + t.Fatal(err) + } + if len(data)%32 == 0 { + t.Errorf("len(data) is %d, want a non-multiple of 32", len(data)) + } + + type ReceivedEvent struct { + Address common.Address + Amount *big.Int + Memo []byte + } + var ev ReceivedEvent + + err = abi.Unpack(&ev, "received", data) + if err != nil { + t.Error(err) + } else { + t.Logf("len(data): %d; received event: %+v", len(data), ev) + } +} + +func TestABI_MethodById(t *testing.T) { + const abiJSON = `[ + {"type":"function","name":"receive","constant":false,"inputs":[{"name":"memo","type":"bytes"}],"outputs":[],"payable":true,"stateMutability":"payable"}, + {"type":"event","name":"received","anonymous":false,"inputs":[{"indexed":false,"name":"sender","type":"address"},{"indexed":false,"name":"amount","type":"uint256"},{"indexed":false,"name":"memo","type":"bytes"}]}, + {"type":"function","name":"fixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr","type":"uint256[2]"}]}, + {"type":"function","name":"fixedArrBytes","constant":true,"inputs":[{"name":"str","type":"bytes"},{"name":"fixedArr","type":"uint256[2]"}]}, + {"type":"function","name":"mixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr","type":"uint256[2]"},{"name":"dynArr","type":"uint256[]"}]}, + {"type":"function","name":"doubleFixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr1","type":"uint256[2]"},{"name":"fixedArr2","type":"uint256[3]"}]}, + {"type":"function","name":"multipleMixedArrStr","constant":true,"inputs":[{"name":"str","type":"string"},{"name":"fixedArr1","type":"uint256[2]"},{"name":"dynArr","type":"uint256[]"},{"name":"fixedArr2","type":"uint256[3]"}]}, + {"type":"function","name":"balance","constant":true}, + {"type":"function","name":"send","constant":false,"inputs":[{"name":"amount","type":"uint256"}]}, + {"type":"function","name":"test","constant":false,"inputs":[{"name":"number","type":"uint32"}]}, + {"type":"function","name":"string","constant":false,"inputs":[{"name":"inputs","type":"string"}]}, + {"type":"function","name":"bool","constant":false,"inputs":[{"name":"inputs","type":"bool"}]}, + {"type":"function","name":"address","constant":false,"inputs":[{"name":"inputs","type":"address"}]}, + {"type":"function","name":"uint64[2]","constant":false,"inputs":[{"name":"inputs","type":"uint64[2]"}]}, + {"type":"function","name":"uint64[]","constant":false,"inputs":[{"name":"inputs","type":"uint64[]"}]}, + {"type":"function","name":"foo","constant":false,"inputs":[{"name":"inputs","type":"uint32"}]}, + {"type":"function","name":"bar","constant":false,"inputs":[{"name":"inputs","type":"uint32"},{"name":"string","type":"uint16"}]}, + {"type":"function","name":"_slice","constant":false,"inputs":[{"name":"inputs","type":"uint32[2]"}]}, + {"type":"function","name":"__slice256","constant":false,"inputs":[{"name":"inputs","type":"uint256[2]"}]}, + {"type":"function","name":"sliceAddress","constant":false,"inputs":[{"name":"inputs","type":"address[]"}]}, + {"type":"function","name":"sliceMultiAddress","constant":false,"inputs":[{"name":"a","type":"address[]"},{"name":"b","type":"address[]"}]} + ] +` + abi, err := JSON(strings.NewReader(abiJSON)) + if err != nil { + t.Fatal(err) + } + for name, m := range abi.Methods { + a := fmt.Sprintf("%v", m) + b := fmt.Sprintf("%v", abi.MethodById(m.Id())) + if a != b { + t.Errorf("Method %v (id %v) not 'findable' by id in ABI", name, common.ToHex(m.Id())) + } + } + +} diff --git a/accounts/abi/argument.go b/accounts/abi/argument.go index 4691318ce..04ca6150a 100644 --- a/accounts/abi/argument.go +++ b/accounts/abi/argument.go @@ -19,6 +19,8 @@ package abi import ( "encoding/json" "fmt" + "reflect" + "strings" ) // Argument holds the name of the argument and the corresponding type. @@ -29,7 +31,10 @@ type Argument struct { Indexed bool // indexed is only used by events } -func (a *Argument) UnmarshalJSON(data []byte) error { +type Arguments []Argument + +// UnmarshalJSON implements json.Unmarshaler interface +func (argument *Argument) UnmarshalJSON(data []byte) error { var extarg struct { Name string Type string @@ -40,12 +45,206 @@ func (a *Argument) UnmarshalJSON(data []byte) error { return fmt.Errorf("argument json err: %v", err) } - a.Type, err = NewType(extarg.Type) + argument.Type, err = NewType(extarg.Type) if err != nil { return err } - a.Name = extarg.Name - a.Indexed = extarg.Indexed + argument.Name = extarg.Name + argument.Indexed = extarg.Indexed + + return nil +} + +// LengthNonIndexed returns the number of arguments when not counting 'indexed' ones. Only events +// can ever have 'indexed' arguments, it should always be false on arguments for method input/output +func (arguments Arguments) LengthNonIndexed() int { + out := 0 + for _, arg := range arguments { + if !arg.Indexed { + out++ + } + } + return out +} + +// isTuple returns true for non-atomic constructs, like (uint,uint) or uint[] +func (arguments Arguments) isTuple() bool { + return len(arguments) > 1 +} + +// Unpack performs the operation hexdata -> Go format +func (arguments Arguments) Unpack(v interface{}, data []byte) error { + if arguments.isTuple() { + return arguments.unpackTuple(v, data) + } + return arguments.unpackAtomic(v, data) +} + +func (arguments Arguments) unpackTuple(v interface{}, output []byte) error { + // make sure the passed value is arguments pointer + valueOf := reflect.ValueOf(v) + if reflect.Ptr != valueOf.Kind() { + return fmt.Errorf("abi: Unpack(non-pointer %T)", v) + } + + var ( + value = valueOf.Elem() + typ = value.Type() + kind = value.Kind() + ) + + if err := requireUnpackKind(value, typ, kind, arguments); err != nil { + return err + } + // If the output interface is a struct, make sure names don't collide + if kind == reflect.Struct { + exists := make(map[string]bool) + for _, arg := range arguments { + field := capitalise(arg.Name) + if field == "" { + return fmt.Errorf("abi: purely underscored output cannot unpack to struct") + } + if exists[field] { + return fmt.Errorf("abi: multiple outputs mapping to the same struct field '%s'", field) + } + exists[field] = true + } + } + // `i` counts the nonindexed arguments. + // `j` counts the number of complex types. + // both `i` and `j` are used to to correctly compute `data` offset. + + i, j := -1, 0 + for _, arg := range arguments { + + if arg.Indexed { + // can't read, continue + continue + } + i++ + marshalledValue, err := toGoType((i+j)*32, arg.Type, output) + if err != nil { + return err + } + + if arg.Type.T == ArrayTy { + // combined index ('i' + 'j') need to be adjusted only by size of array, thus + // we need to decrement 'j' because 'i' was incremented + j += arg.Type.Size - 1 + } + + reflectValue := reflect.ValueOf(marshalledValue) + + switch kind { + case reflect.Struct: + name := capitalise(arg.Name) + for j := 0; j < typ.NumField(); j++ { + // TODO read tags: `abi:"fieldName"` + if typ.Field(j).Name == name { + if err := set(value.Field(j), reflectValue, arg); err != nil { + return err + } + } + } + case reflect.Slice, reflect.Array: + if value.Len() < i { + return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(arguments), value.Len()) + } + v := value.Index(i) + if err := requireAssignable(v, reflectValue); err != nil { + return err + } + if err := set(v.Elem(), reflectValue, arg); err != nil { + return err + } + default: + return fmt.Errorf("abi:[2] cannot unmarshal tuple in to %v", typ) + } + } return nil } + +// unpackAtomic unpacks ( hexdata -> go ) a single value +func (arguments Arguments) unpackAtomic(v interface{}, output []byte) error { + // make sure the passed value is arguments pointer + valueOf := reflect.ValueOf(v) + if reflect.Ptr != valueOf.Kind() { + return fmt.Errorf("abi: Unpack(non-pointer %T)", v) + } + arg := arguments[0] + if arg.Indexed { + return fmt.Errorf("abi: attempting to unpack indexed variable into element.") + } + + value := valueOf.Elem() + + marshalledValue, err := toGoType(0, arg.Type, output) + if err != nil { + return err + } + return set(value, reflect.ValueOf(marshalledValue), arg) +} + +// Unpack performs the operation Go format -> Hexdata +func (arguments Arguments) Pack(args ...interface{}) ([]byte, error) { + // Make sure arguments match up and pack them + abiArgs := arguments + if len(args) != len(abiArgs) { + return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(abiArgs)) + } + + // variable input is the output appended at the end of packed + // output. This is used for strings and bytes types input. + var variableInput []byte + + // input offset is the bytes offset for packed output + inputOffset := 0 + for _, abiArg := range abiArgs { + if abiArg.Type.T == ArrayTy { + inputOffset += 32 * abiArg.Type.Size + } else { + inputOffset += 32 + } + } + + var ret []byte + for i, a := range args { + input := abiArgs[i] + // pack the input + packed, err := input.Type.pack(reflect.ValueOf(a)) + if err != nil { + return nil, err + } + + // check for a slice type (string, bytes, slice) + if input.Type.requiresLengthPrefix() { + // calculate the offset + offset := inputOffset + len(variableInput) + // set the offset + ret = append(ret, packNum(reflect.ValueOf(offset))...) + // Append the packed output to the variable input. The variable input + // will be appended at the end of the input. + variableInput = append(variableInput, packed...) + } else { + // append the packed value to the input + ret = append(ret, packed...) + } + } + // append the variable input at the end of the packed input + ret = append(ret, variableInput...) + + return ret, nil +} + +// capitalise makes the first character of a string upper case, also removing any +// prefixing underscores from the variable names. +func capitalise(input string) string { + for len(input) > 0 && input[0] == '_' { + input = input[1:] + } + if len(input) == 0 { + return "" + } + return strings.ToUpper(input[:1]) + input[1:] +} diff --git a/accounts/abi/bind/backend.go b/accounts/abi/bind/backend.go index 25b61928e..ca60cc1b4 100644 --- a/accounts/abi/bind/backend.go +++ b/accounts/abi/bind/backend.go @@ -52,12 +52,6 @@ type ContractCaller interface { CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) } -// DeployBackend wraps the operations needed by WaitMined and WaitDeployed. -type DeployBackend interface { - TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) - CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) -} - // PendingContractCaller defines methods to perform contract calls on the pending state. // Call will try to discover this interface when access to the pending state is requested. // If the backend does not support the pending state, Call returns ErrNoPendingState. @@ -85,13 +79,34 @@ type ContractTransactor interface { // There is no guarantee that this is the true gas limit requirement as other // transactions may be added or removed by miners, but it should provide a basis // for setting a reasonable default. - EstimateGas(ctx context.Context, call ethereum.CallMsg) (usedGas *big.Int, err error) + EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) // SendTransaction injects the transaction into the pending pool for execution. SendTransaction(ctx context.Context, tx *types.Transaction) error } +// ContractFilterer defines the methods needed to access log events using one-off +// queries or continuous event subscriptions. +type ContractFilterer interface { + // FilterLogs executes a log filter operation, blocking during execution and + // returning all the results in one batch. + // + // TODO(karalabe): Deprecate when the subscription one can return past data too. + FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) + + // SubscribeFilterLogs creates a background log filtering operation, returning + // a subscription immediately, which can be used to stream the found events. + SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) +} + +// DeployBackend wraps the operations needed by WaitMined and WaitDeployed. +type DeployBackend interface { + TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) + CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) +} + // ContractBackend defines the methods needed to work with contracts on a read-write basis. type ContractBackend interface { ContractCaller ContractTransactor + ContractFilterer } diff --git a/accounts/abi/bind/backends/simulated.go b/accounts/abi/bind/backends/simulated.go index 09288d401..bd342a8cb 100644 --- a/accounts/abi/bind/backends/simulated.go +++ b/accounts/abi/bind/backends/simulated.go @@ -30,11 +30,15 @@ import ( "github.com/ethereum/go-ethereum/common/math" "github.com/ethereum/go-ethereum/consensus/ethash" "github.com/ethereum/go-ethereum/core" + "github.com/ethereum/go-ethereum/core/bloombits" "github.com/ethereum/go-ethereum/core/state" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/core/vm" + "github.com/ethereum/go-ethereum/eth/filters" "github.com/ethereum/go-ethereum/ethdb" + "github.com/ethereum/go-ethereum/event" "github.com/ethereum/go-ethereum/params" + "github.com/ethereum/go-ethereum/rpc" ) // This nil assignment ensures compile time that SimulatedBackend implements bind.ContractBackend. @@ -53,6 +57,8 @@ type SimulatedBackend struct { pendingBlock *types.Block // Currently pending block that will be imported on request pendingState *state.StateDB // Currently pending state that will be the active on on request + events *filters.EventSystem // Event system for filtering log events live + config *params.ChainConfig } @@ -62,8 +68,14 @@ func NewSimulatedBackend(alloc core.GenesisAlloc) *SimulatedBackend { database, _ := ethdb.NewMemDatabase() genesis := core.Genesis{Config: params.AllEthashProtocolChanges, Alloc: alloc} genesis.MustCommit(database) - blockchain, _ := core.NewBlockChain(database, genesis.Config, ethash.NewFaker(), vm.Config{}) - backend := &SimulatedBackend{database: database, blockchain: blockchain, config: genesis.Config} + blockchain, _ := core.NewBlockChain(database, nil, genesis.Config, ethash.NewFaker(), vm.Config{}) + + backend := &SimulatedBackend{ + database: database, + blockchain: blockchain, + config: genesis.Config, + events: filters.NewEventSystem(new(event.TypeMux), &filterBackend{database, blockchain}, false), + } backend.rollback() return backend } @@ -89,9 +101,11 @@ func (b *SimulatedBackend) Rollback() { } func (b *SimulatedBackend) rollback() { - blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(int, *core.BlockGen) {}) + blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(int, *core.BlockGen) {}) + statedb, _ := b.blockchain.State() + b.pendingBlock = blocks[0] - b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database)) + b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database()) } // CodeAt returns the code associated with a certain account in the blockchain. @@ -200,7 +214,7 @@ func (b *SimulatedBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error // EstimateGas executes the requested code against the currently pending block/state and // returns the used amount of gas. -func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (*big.Int, error) { +func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { b.mu.Lock() defer b.mu.Unlock() @@ -210,16 +224,16 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs hi uint64 cap uint64 ) - if call.Gas != nil && call.Gas.Uint64() >= params.TxGas { - hi = call.Gas.Uint64() + if call.Gas >= params.TxGas { + hi = call.Gas } else { - hi = b.pendingBlock.GasLimit().Uint64() + hi = b.pendingBlock.GasLimit() } cap = hi // Create a helper to check if a gas allowance results in an executable transaction executable := func(gas uint64) bool { - call.Gas = new(big.Int).SetUint64(gas) + call.Gas = gas snapshot := b.pendingState.Snapshot() _, _, failed, err := b.callContract(ctx, call, b.pendingBlock, b.pendingState) @@ -242,21 +256,21 @@ func (b *SimulatedBackend) EstimateGas(ctx context.Context, call ethereum.CallMs // Reject the transaction as invalid if it still fails at the highest allowance if hi == cap { if !executable(hi) { - return nil, errGasEstimationFailed + return 0, errGasEstimationFailed } } - return new(big.Int).SetUint64(hi), nil + return hi, nil } -// callContract implemens common code between normal and pending contract calls. +// callContract implements common code between normal and pending contract calls. // state is modified during execution, make sure to copy it if necessary. -func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, *big.Int, bool, error) { +func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallMsg, block *types.Block, statedb *state.StateDB) ([]byte, uint64, bool, error) { // Ensure message is initialized properly. if call.GasPrice == nil { call.GasPrice = big.NewInt(1) } - if call.Gas == nil || call.Gas.Sign() == 0 { - call.Gas = big.NewInt(50000000) + if call.Gas == 0 { + call.Gas = 50000000 } if call.Value == nil { call.Value = new(big.Int) @@ -271,9 +285,9 @@ func (b *SimulatedBackend) callContract(ctx context.Context, call ethereum.CallM // Create a new environment which holds all relevant information // about the transaction and calling mechanisms. vmenv := vm.NewEVM(evmContext, statedb, b.config, vm.Config{}) - gaspool := new(core.GasPool).AddGas(math.MaxBig256) - ret, gasUsed, _, failed, err := core.NewStateTransition(vmenv, msg, gaspool).TransitionDb() - return ret, gasUsed, failed, err + gaspool := new(core.GasPool).AddGas(math.MaxUint64) + + return core.NewStateTransition(vmenv, msg, gaspool).TransitionDb() } // SendTransaction updates the pending block to include the given transaction. @@ -291,29 +305,95 @@ func (b *SimulatedBackend) SendTransaction(ctx context.Context, tx *types.Transa panic(fmt.Errorf("invalid transaction nonce: got %d, want %d", tx.Nonce(), nonce)) } - blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) { + blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { for _, tx := range b.pendingBlock.Transactions() { block.AddTx(tx) } block.AddTx(tx) }) + statedb, _ := b.blockchain.State() + b.pendingBlock = blocks[0] - b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database)) + b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database()) return nil } -// JumpTimeInSeconds adds skip seconds to the clock +// FilterLogs executes a log filter operation, blocking during execution and +// returning all the results in one batch. +// +// TODO(karalabe): Deprecate when the subscription one can return past data too. +func (b *SimulatedBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { + // Initialize unset filter boundaried to run from genesis to chain head + from := int64(0) + if query.FromBlock != nil { + from = query.FromBlock.Int64() + } + to := int64(-1) + if query.ToBlock != nil { + to = query.ToBlock.Int64() + } + // Construct and execute the filter + filter := filters.New(&filterBackend{b.database, b.blockchain}, from, to, query.Addresses, query.Topics) + + logs, err := filter.Logs(ctx) + if err != nil { + return nil, err + } + res := make([]types.Log, len(logs)) + for i, log := range logs { + res[i] = *log + } + return res, nil +} + +// SubscribeFilterLogs creates a background log filtering operation, returning a +// subscription immediately, which can be used to stream the found events. +func (b *SimulatedBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { + // Subscribe to contract events + sink := make(chan []*types.Log) + + sub, err := b.events.SubscribeLogs(query, sink) + if err != nil { + return nil, err + } + // Since we're getting logs in batches, we need to flatten them into a plain stream + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case logs := <-sink: + for _, log := range logs { + select { + case ch <- *log: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil +} + +// AdjustTime adds a time shift to the simulated clock. func (b *SimulatedBackend) AdjustTime(adjustment time.Duration) error { b.mu.Lock() defer b.mu.Unlock() - blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), b.database, 1, func(number int, block *core.BlockGen) { + blocks, _ := core.GenerateChain(b.config, b.blockchain.CurrentBlock(), ethash.NewFaker(), b.database, 1, func(number int, block *core.BlockGen) { for _, tx := range b.pendingBlock.Transactions() { block.AddTx(tx) } block.OffsetTime(int64(adjustment.Seconds())) }) + statedb, _ := b.blockchain.State() + b.pendingBlock = blocks[0] - b.pendingState, _ = state.New(b.pendingBlock.Root(), state.NewDatabase(b.database)) + b.pendingState, _ = state.New(b.pendingBlock.Root(), statedb.Database()) return nil } @@ -328,6 +408,47 @@ func (m callmsg) Nonce() uint64 { return 0 } func (m callmsg) CheckNonce() bool { return false } func (m callmsg) To() *common.Address { return m.CallMsg.To } func (m callmsg) GasPrice() *big.Int { return m.CallMsg.GasPrice } -func (m callmsg) Gas() *big.Int { return m.CallMsg.Gas } +func (m callmsg) Gas() uint64 { return m.CallMsg.Gas } func (m callmsg) Value() *big.Int { return m.CallMsg.Value } func (m callmsg) Data() []byte { return m.CallMsg.Data } + +// filterBackend implements filters.Backend to support filtering for logs without +// taking bloom-bits acceleration structures into account. +type filterBackend struct { + db ethdb.Database + bc *core.BlockChain +} + +func (fb *filterBackend) ChainDb() ethdb.Database { return fb.db } +func (fb *filterBackend) EventMux() *event.TypeMux { panic("not supported") } + +func (fb *filterBackend) HeaderByNumber(ctx context.Context, block rpc.BlockNumber) (*types.Header, error) { + if block == rpc.LatestBlockNumber { + return fb.bc.CurrentHeader(), nil + } + return fb.bc.GetHeaderByNumber(uint64(block.Int64())), nil +} +func (fb *filterBackend) GetReceipts(ctx context.Context, hash common.Hash) (types.Receipts, error) { + return core.GetBlockReceipts(fb.db, hash, core.GetBlockNumber(fb.db, hash)), nil +} + +func (fb *filterBackend) SubscribeTxPreEvent(ch chan<- core.TxPreEvent) event.Subscription { + return event.NewSubscription(func(quit <-chan struct{}) error { + <-quit + return nil + }) +} +func (fb *filterBackend) SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription { + return fb.bc.SubscribeChainEvent(ch) +} +func (fb *filterBackend) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription { + return fb.bc.SubscribeRemovedLogsEvent(ch) +} +func (fb *filterBackend) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription { + return fb.bc.SubscribeLogsEvent(ch) +} + +func (fb *filterBackend) BloomStatus() (uint64, uint64) { return 4096, 0 } +func (fb *filterBackend) ServiceFilter(ctx context.Context, ms *bloombits.MatcherSession) { + panic("not supported") +} diff --git a/accounts/abi/bind/base.go b/accounts/abi/bind/base.go index b40bd65e8..83ad1c8ae 100644 --- a/accounts/abi/bind/base.go +++ b/accounts/abi/bind/base.go @@ -27,6 +27,7 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" + "github.com/ethereum/go-ethereum/event" ) // SignerFn is a signer function callback when a contract requires a method to @@ -50,11 +51,27 @@ type TransactOpts struct { Value *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds) GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle) - GasLimit *big.Int // Gas limit to set for the transaction execution (nil = estimate + 10%) + GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate) Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) } +// FilterOpts is the collection of options to fine tune filtering for events +// within a bound contract. +type FilterOpts struct { + Start uint64 // Start of the queried range + End *uint64 // End of the range (nil = latest) + + Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) +} + +// WatchOpts is the collection of options to fine tune subscribing for events +// within a bound contract. +type WatchOpts struct { + Start *uint64 // Start of the queried range (nil = latest) + Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) +} + // BoundContract is the base wrapper object that reflects a contract on the // Ethereum network. It contains a collection of methods that are used by the // higher level contract bindings to operate. @@ -63,16 +80,18 @@ type BoundContract struct { abi abi.ABI // Reflect based ABI to access the correct Ethereum methods caller ContractCaller // Read interface to interact with the blockchain transactor ContractTransactor // Write interface to interact with the blockchain + filterer ContractFilterer // Event filtering to interact with the blockchain } // NewBoundContract creates a low level contract interface through which calls // and transactions may be made through. -func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor) *BoundContract { +func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract { return &BoundContract{ address: address, abi: abi, caller: caller, transactor: transactor, + filterer: filterer, } } @@ -80,7 +99,7 @@ func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller // deployment address with a Go wrapper. func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) { // Otherwise try to deploy the contract - c := NewBoundContract(common.Address{}, abi, backend, backend) + c := NewBoundContract(common.Address{}, abi, backend, backend, backend) input, err := c.abi.Pack("", params...) if err != nil { @@ -189,7 +208,7 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i } } gasLimit := opts.GasLimit - if gasLimit == nil { + if gasLimit == 0 { // Gas estimation cannot succeed without code for method invocations if contract != nil { if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil { @@ -225,6 +244,104 @@ func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, i return signedTx, nil } +// FilterLogs filters contract logs for past blocks, returning the necessary +// channels to construct a strongly typed bound iterator on top of them. +func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { + // Don't crash on a lazy user + if opts == nil { + opts = new(FilterOpts) + } + // Append the event selector to the query parameters and construct the topic set + query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...) + + topics, err := makeTopics(query...) + if err != nil { + return nil, nil, err + } + // Start the background filtering + logs := make(chan types.Log, 128) + + config := ethereum.FilterQuery{ + Addresses: []common.Address{c.address}, + Topics: topics, + FromBlock: new(big.Int).SetUint64(opts.Start), + } + if opts.End != nil { + config.ToBlock = new(big.Int).SetUint64(*opts.End) + } + /* TODO(karalabe): Replace the rest of the method below with this when supported + sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) + */ + buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config) + if err != nil { + return nil, nil, err + } + sub, err := event.NewSubscription(func(quit <-chan struct{}) error { + for _, log := range buff { + select { + case logs <- log: + case <-quit: + return nil + } + } + return nil + }), nil + + if err != nil { + return nil, nil, err + } + return logs, sub, nil +} + +// WatchLogs filters subscribes to contract logs for future blocks, returning a +// subscription object that can be used to tear down the watcher. +func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) { + // Don't crash on a lazy user + if opts == nil { + opts = new(WatchOpts) + } + // Append the event selector to the query parameters and construct the topic set + query = append([][]interface{}{{c.abi.Events[name].Id()}}, query...) + + topics, err := makeTopics(query...) + if err != nil { + return nil, nil, err + } + // Start the background filtering + logs := make(chan types.Log, 128) + + config := ethereum.FilterQuery{ + Addresses: []common.Address{c.address}, + Topics: topics, + } + if opts.Start != nil { + config.FromBlock = new(big.Int).SetUint64(*opts.Start) + } + sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs) + if err != nil { + return nil, nil, err + } + return logs, sub, nil +} + +// UnpackLog unpacks a retrieved log into the provided output structure. +func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error { + if len(log.Data) > 0 { + if err := c.abi.Unpack(out, event, log.Data); err != nil { + return err + } + } + var indexed abi.Arguments + for _, arg := range c.abi.Events[event].Inputs { + if arg.Indexed { + indexed = append(indexed, arg) + } + } + return parseTopics(out, indexed, log.Topics[1:]) +} + +// ensureContext is a helper method to ensure a context is not nil, even if the +// user specified it as such. func ensureContext(ctx context.Context) context.Context { if ctx == nil { return context.TODO() diff --git a/accounts/abi/bind/bind.go b/accounts/abi/bind/bind.go index 4dce79b77..e31b45481 100644 --- a/accounts/abi/bind/bind.go +++ b/accounts/abi/bind/bind.go @@ -63,10 +63,11 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string, lang La return r }, abis[i]) - // Extract the call and transact methods, and sort them alphabetically + // Extract the call and transact methods; events; and sort them alphabetically var ( calls = make(map[string]*tmplMethod) transacts = make(map[string]*tmplMethod) + events = make(map[string]*tmplEvent) ) for _, original := range evmABI.Methods { // Normalize the method for capital cases and non-anonymous inputs/outputs @@ -89,11 +90,33 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string, lang La } // Append the methods to the call or transact lists if original.Const { - calls[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original)} + calls[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original.Outputs)} } else { - transacts[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original)} + transacts[original.Name] = &tmplMethod{Original: original, Normalized: normalized, Structured: structured(original.Outputs)} } } + for _, original := range evmABI.Events { + // Skip anonymous events as they don't support explicit filtering + if original.Anonymous { + continue + } + // Normalize the event for capital cases and non-anonymous outputs + normalized := original + normalized.Name = methodNormalizer[lang](original.Name) + + normalized.Inputs = make([]abi.Argument, len(original.Inputs)) + copy(normalized.Inputs, original.Inputs) + for j, input := range normalized.Inputs { + // Indexed fields are input, non-indexed ones are outputs + if input.Indexed { + if input.Name == "" { + normalized.Inputs[j].Name = fmt.Sprintf("arg%d", j) + } + } + } + // Append the event to the accumulator list + events[original.Name] = &tmplEvent{Original: original, Normalized: normalized} + } contracts[types[i]] = &tmplContract{ Type: capitalise(types[i]), InputABI: strings.Replace(strippedABI, "\"", "\\\"", -1), @@ -101,6 +124,7 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string, lang La Constructor: evmABI.Constructor, Calls: calls, Transacts: transacts, + Events: events, } } // Generate the contract template data content and render it @@ -111,10 +135,11 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string, lang La buffer := new(bytes.Buffer) funcs := map[string]interface{}{ - "bindtype": bindType[lang], - "namedtype": namedType[lang], - "capitalise": capitalise, - "decapitalise": decapitalise, + "bindtype": bindType[lang], + "bindtopictype": bindTopicType[lang], + "namedtype": namedType[lang], + "capitalise": capitalise, + "decapitalise": decapitalise, } tmpl := template.Must(template.New("").Funcs(funcs).Parse(tmplSource[lang])) if err := tmpl.Execute(buffer, data); err != nil { @@ -133,7 +158,7 @@ func Bind(types []string, abis []string, bytecodes []string, pkg string, lang La } // bindType is a set of type binders that convert Solidity types to some supported -// programming language. +// programming language types. var bindType = map[Lang]func(kind abi.Type) string{ LangGo: bindTypeGo, LangJava: bindTypeJava, @@ -254,6 +279,33 @@ func bindTypeJava(kind abi.Type) string { } } +// bindTopicType is a set of type binders that convert Solidity types to some +// supported programming language topic types. +var bindTopicType = map[Lang]func(kind abi.Type) string{ + LangGo: bindTopicTypeGo, + LangJava: bindTopicTypeJava, +} + +// bindTypeGo converts a Solidity topic type to a Go one. It is almost the same +// funcionality as for simple types, but dynamic types get converted to hashes. +func bindTopicTypeGo(kind abi.Type) string { + bound := bindTypeGo(kind) + if bound == "string" || bound == "[]byte" { + bound = "common.Hash" + } + return bound +} + +// bindTypeGo converts a Solidity topic type to a Java one. It is almost the same +// funcionality as for simple types, but dynamic types get converted to hashes. +func bindTopicTypeJava(kind abi.Type) string { + bound := bindTypeJava(kind) + if bound == "String" || bound == "Bytes" { + bound = "Hash" + } + return bound +} + // namedType is a set of functions that transform language specific types to // named versions that my be used inside method names. var namedType = map[Lang]func(string, abi.Type) string{ @@ -304,8 +356,15 @@ var methodNormalizer = map[Lang]func(string) string{ LangJava: decapitalise, } -// capitalise makes the first character of a string upper case. +// capitalise makes the first character of a string upper case, also removing any +// prefixing underscores from the variable names. func capitalise(input string) string { + for len(input) > 0 && input[0] == '_' { + input = input[1:] + } + if len(input) == 0 { + return "" + } return strings.ToUpper(input[:1]) + input[1:] } @@ -314,16 +373,25 @@ func decapitalise(input string) string { return strings.ToLower(input[:1]) + input[1:] } -// structured checks whether a method has enough information to return a proper -// Go struct ot if flat returns are needed. -func structured(method abi.Method) bool { - if len(method.Outputs) < 2 { +// structured checks whether a list of ABI data types has enough information to +// operate through a proper Go struct or if flat returns are needed. +func structured(args abi.Arguments) bool { + if len(args) < 2 { return false } - for _, out := range method.Outputs { + exists := make(map[string]bool) + for _, out := range args { + // If the name is anonymous, we can't organize into a struct if out.Name == "" { return false } + // If the field name is empty when normalized or collides (var, Var, _var, _Var), + // we can't organize into a struct + field := capitalise(out.Name) + if field == "" || exists[field] { + return false + } + exists[field] = true } return true } diff --git a/accounts/abi/bind/bind_test.go b/accounts/abi/bind/bind_test.go index 43ed53b92..c4838e647 100644 --- a/accounts/abi/bind/bind_test.go +++ b/accounts/abi/bind/bind_test.go @@ -126,6 +126,7 @@ var bindTests = []struct { {"type":"function","name":"namedOutput","constant":true,"inputs":[],"outputs":[{"name":"str","type":"string"}]}, {"type":"function","name":"anonOutput","constant":true,"inputs":[],"outputs":[{"name":"","type":"string"}]}, {"type":"function","name":"namedOutputs","constant":true,"inputs":[],"outputs":[{"name":"str1","type":"string"},{"name":"str2","type":"string"}]}, + {"type":"function","name":"collidingOutputs","constant":true,"inputs":[],"outputs":[{"name":"str","type":"string"},{"name":"Str","type":"string"}]}, {"type":"function","name":"anonOutputs","constant":true,"inputs":[],"outputs":[{"name":"","type":"string"},{"name":"","type":"string"}]}, {"type":"function","name":"mixedOutputs","constant":true,"inputs":[],"outputs":[{"name":"","type":"string"},{"name":"str","type":"string"}]} ] @@ -140,12 +141,71 @@ var bindTests = []struct { str1, err = b.NamedOutput(nil) str1, err = b.AnonOutput(nil) res, _ := b.NamedOutputs(nil) + str1, str2, err = b.CollidingOutputs(nil) str1, str2, err = b.AnonOutputs(nil) str1, str2, err = b.MixedOutputs(nil) fmt.Println(str1, str2, res.Str1, res.Str2, err) }`, }, + // Tests that named, anonymous and indexed events are handled correctly + { + `EventChecker`, ``, ``, + ` + [ + {"type":"event","name":"empty","inputs":[]}, + {"type":"event","name":"indexed","inputs":[{"name":"addr","type":"address","indexed":true},{"name":"num","type":"int256","indexed":true}]}, + {"type":"event","name":"mixed","inputs":[{"name":"addr","type":"address","indexed":true},{"name":"num","type":"int256"}]}, + {"type":"event","name":"anonymous","anonymous":true,"inputs":[]}, + {"type":"event","name":"dynamic","inputs":[{"name":"idxStr","type":"string","indexed":true},{"name":"idxDat","type":"bytes","indexed":true},{"name":"str","type":"string"},{"name":"dat","type":"bytes"}]} + ] + `, + `if e, err := NewEventChecker(common.Address{}, nil); e == nil || err != nil { + t.Fatalf("binding (%v) nil or error (%v) not nil", e, nil) + } else if false { // Don't run, just compile and test types + var ( + err error + res bool + str string + dat []byte + hash common.Hash + ) + _, err = e.FilterEmpty(nil) + _, err = e.FilterIndexed(nil, []common.Address{}, []*big.Int{}) + + mit, err := e.FilterMixed(nil, []common.Address{}) + + res = mit.Next() // Make sure the iterator has a Next method + err = mit.Error() // Make sure the iterator has an Error method + err = mit.Close() // Make sure the iterator has a Close method + + fmt.Println(mit.Event.Raw.BlockHash) // Make sure the raw log is contained within the results + fmt.Println(mit.Event.Num) // Make sure the unpacked non-indexed fields are present + fmt.Println(mit.Event.Addr) // Make sure the reconstructed indexed fields are present + + dit, err := e.FilterDynamic(nil, []string{}, [][]byte{}) + + str = dit.Event.Str // Make sure non-indexed strings retain their type + dat = dit.Event.Dat // Make sure non-indexed bytes retain their type + hash = dit.Event.IdxStr // Make sure indexed strings turn into hashes + hash = dit.Event.IdxDat // Make sure indexed bytes turn into hashes + + sink := make(chan *EventCheckerMixed) + sub, err := e.WatchMixed(nil, sink, []common.Address{}) + defer sub.Unsubscribe() + + event := <-sink + fmt.Println(event.Raw.BlockHash) // Make sure the raw log is contained within the results + fmt.Println(event.Num) // Make sure the unpacked non-indexed fields are present + fmt.Println(event.Addr) // Make sure the reconstructed indexed fields are present + + fmt.Println(res, str, dat, hash, err) + } + // Run a tiny reflection test to ensure disallowed methods don't appear + if _, ok := reflect.TypeOf(&EventChecker{}).MethodByName("FilterAnonymous"); ok { + t.Errorf("binding has disallowed method (FilterAnonymous)") + }`, + }, // Test that contract interactions (deploy, transact and call) generate working code { `Interactor`, @@ -397,7 +457,6 @@ var bindTests = []struct { sim.Commit() // Set the field with automatic estimation and check that it succeeds - auth.GasLimit = nil if _, err := limiter.SetField(auth, "automatic"); err != nil { t.Fatalf("Failed to call automatically gased transaction: %v", err) } @@ -447,6 +506,237 @@ var bindTests = []struct { } `, }, + { + `Underscorer`, + ` + contract Underscorer { + function UnderscoredOutput() constant returns (int _int, string _string) { + return (314, "pi"); + } + function LowerLowerCollision() constant returns (int _res, int res) { + return (1, 2); + } + function LowerUpperCollision() constant returns (int _res, int Res) { + return (1, 2); + } + function UpperLowerCollision() constant returns (int _Res, int res) { + return (1, 2); + } + function UpperUpperCollision() constant returns (int _Res, int Res) { + return (1, 2); + } + function PurelyUnderscoredOutput() constant returns (int _, int res) { + return (1, 2); + } + function AllPurelyUnderscoredOutput() constant returns (int _, int __) { + return (1, 2); + } + } + `, `6060604052341561000f57600080fd5b6103498061001e6000396000f300606060405260043610610083576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806303a592131461008857806367e6633d146100b85780639df484851461014d578063af7486ab1461017d578063b564b34d146101ad578063e02ab24d146101dd578063e409ca451461020d575b600080fd5b341561009357600080fd5b61009b61023d565b604051808381526020018281526020019250505060405180910390f35b34156100c357600080fd5b6100cb610252565b6040518083815260200180602001828103825283818151815260200191508051906020019080838360005b838110156101115780820151818401526020810190506100f6565b50505050905090810190601f16801561013e5780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b341561015857600080fd5b6101606102a0565b604051808381526020018281526020019250505060405180910390f35b341561018857600080fd5b6101906102b5565b604051808381526020018281526020019250505060405180910390f35b34156101b857600080fd5b6101c06102ca565b604051808381526020018281526020019250505060405180910390f35b34156101e857600080fd5b6101f06102df565b604051808381526020018281526020019250505060405180910390f35b341561021857600080fd5b6102206102f4565b604051808381526020018281526020019250505060405180910390f35b60008060016002819150809050915091509091565b600061025c610309565b61013a8090506040805190810160405280600281526020017f7069000000000000000000000000000000000000000000000000000000000000815250915091509091565b60008060016002819150809050915091509091565b60008060016002819150809050915091509091565b60008060016002819150809050915091509091565b60008060016002819150809050915091509091565b60008060016002819150809050915091509091565b6020604051908101604052806000815250905600a165627a7a72305820c11dcfa136fc7d182ee4d34f0b12d988496228f7e2d02d2b5376d996ca1743d00029`, + `[{"constant":true,"inputs":[],"name":"LowerUpperCollision","outputs":[{"name":"_res","type":"int256"},{"name":"Res","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"UnderscoredOutput","outputs":[{"name":"_int","type":"int256"},{"name":"_string","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"PurelyUnderscoredOutput","outputs":[{"name":"_","type":"int256"},{"name":"res","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"UpperLowerCollision","outputs":[{"name":"_Res","type":"int256"},{"name":"res","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"AllPurelyUnderscoredOutput","outputs":[{"name":"_","type":"int256"},{"name":"__","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"UpperUpperCollision","outputs":[{"name":"_Res","type":"int256"},{"name":"Res","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"LowerLowerCollision","outputs":[{"name":"_res","type":"int256"},{"name":"res","type":"int256"}],"payable":false,"stateMutability":"view","type":"function"}]`, + ` + // Generate a new random account and a funded simulator + key, _ := crypto.GenerateKey() + auth := bind.NewKeyedTransactor(key) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}) + + // Deploy a underscorer tester contract and execute a structured call on it + _, _, underscorer, err := DeployUnderscorer(auth, sim) + if err != nil { + t.Fatalf("Failed to deploy underscorer contract: %v", err) + } + sim.Commit() + + // Verify that underscored return values correctly parse into structs + if res, err := underscorer.UnderscoredOutput(nil); err != nil { + t.Errorf("Failed to call constant function: %v", err) + } else if res.Int.Cmp(big.NewInt(314)) != 0 || res.String != "pi" { + t.Errorf("Invalid result, want: {314, \"pi\"}, got: %+v", res) + } + // Verify that underscored and non-underscored name collisions force tuple outputs + var a, b *big.Int + + a, b, _ = underscorer.LowerLowerCollision(nil) + a, b, _ = underscorer.LowerUpperCollision(nil) + a, b, _ = underscorer.UpperLowerCollision(nil) + a, b, _ = underscorer.UpperUpperCollision(nil) + a, b, _ = underscorer.PurelyUnderscoredOutput(nil) + a, b, _ = underscorer.AllPurelyUnderscoredOutput(nil) + + fmt.Println(a, b, err) + `, + }, + // Tests that logs can be successfully filtered and decoded. + { + `Eventer`, + ` + contract Eventer { + event SimpleEvent ( + address indexed Addr, + bytes32 indexed Id, + bool indexed Flag, + uint Value + ); + function raiseSimpleEvent(address addr, bytes32 id, bool flag, uint value) { + SimpleEvent(addr, id, flag, value); + } + + event NodataEvent ( + uint indexed Number, + int16 indexed Short, + uint32 indexed Long + ); + function raiseNodataEvent(uint number, int16 short, uint32 long) { + NodataEvent(number, short, long); + } + + event DynamicEvent ( + string indexed IndexedString, + bytes indexed IndexedBytes, + string NonIndexedString, + bytes NonIndexedBytes + ); + function raiseDynamicEvent(string str, bytes blob) { + DynamicEvent(str, blob, str, blob); + } + } + `, + `6060604052341561000f57600080fd5b61042c8061001e6000396000f300606060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063528300ff1461005c578063630c31e2146100fc578063c7d116dd14610156575b600080fd5b341561006757600080fd5b6100fa600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509190803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610194565b005b341561010757600080fd5b610154600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035600019169060200190919080351515906020019091908035906020019091905050610367565b005b341561016157600080fd5b610192600480803590602001909190803560010b90602001909190803563ffffffff169060200190919050506103c3565b005b806040518082805190602001908083835b6020831015156101ca57805182526020820191506020810190506020830392506101a5565b6001836020036101000a0380198251168184511680821785525050505050509050019150506040518091039020826040518082805190602001908083835b60208310151561022d5780518252602082019150602081019050602083039250610208565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405180910390207f3281fd4f5e152dd3385df49104a3f633706e21c9e80672e88d3bcddf33101f008484604051808060200180602001838103835285818151815260200191508051906020019080838360005b838110156102c15780820151818401526020810190506102a6565b50505050905090810190601f1680156102ee5780820380516001836020036101000a031916815260200191505b50838103825284818151815260200191508051906020019080838360005b8381101561032757808201518184015260208101905061030c565b50505050905090810190601f1680156103545780820380516001836020036101000a031916815260200191505b5094505050505060405180910390a35050565b81151583600019168573ffffffffffffffffffffffffffffffffffffffff167f1f097de4289df643bd9c11011cc61367aa12983405c021056e706eb5ba1250c8846040518082815260200191505060405180910390a450505050565b8063ffffffff168260010b847f3ca7f3a77e5e6e15e781850bc82e32adfa378a2a609370db24b4d0fae10da2c960405160405180910390a45050505600a165627a7a72305820d1f8a8bbddbc5bb29f285891d6ae1eef8420c52afdc05e1573f6114d8e1714710029`, + `[{"constant":false,"inputs":[{"name":"str","type":"string"},{"name":"blob","type":"bytes"}],"name":"raiseDynamicEvent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"addr","type":"address"},{"name":"id","type":"bytes32"},{"name":"flag","type":"bool"},{"name":"value","type":"uint256"}],"name":"raiseSimpleEvent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"number","type":"uint256"},{"name":"short","type":"int16"},{"name":"long","type":"uint32"}],"name":"raiseNodataEvent","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"Addr","type":"address"},{"indexed":true,"name":"Id","type":"bytes32"},{"indexed":true,"name":"Flag","type":"bool"},{"indexed":false,"name":"Value","type":"uint256"}],"name":"SimpleEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"Number","type":"uint256"},{"indexed":true,"name":"Short","type":"int16"},{"indexed":true,"name":"Long","type":"uint32"}],"name":"NodataEvent","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"IndexedString","type":"string"},{"indexed":true,"name":"IndexedBytes","type":"bytes"},{"indexed":false,"name":"NonIndexedString","type":"string"},{"indexed":false,"name":"NonIndexedBytes","type":"bytes"}],"name":"DynamicEvent","type":"event"}]`, + ` + // Generate a new random account and a funded simulator + key, _ := crypto.GenerateKey() + auth := bind.NewKeyedTransactor(key) + sim := backends.NewSimulatedBackend(core.GenesisAlloc{auth.From: {Balance: big.NewInt(10000000000)}}) + + // Deploy an eventer contract + _, _, eventer, err := DeployEventer(auth, sim) + if err != nil { + t.Fatalf("Failed to deploy eventer contract: %v", err) + } + sim.Commit() + + // Inject a few events into the contract, gradually more in each block + for i := 1; i <= 3; i++ { + for j := 1; j <= i; j++ { + if _, err := eventer.RaiseSimpleEvent(auth, common.Address{byte(j)}, [32]byte{byte(j)}, true, big.NewInt(int64(10*i+j))); err != nil { + t.Fatalf("block %d, event %d: raise failed: %v", i, j, err) + } + } + sim.Commit() + } + // Test filtering for certain events and ensure they can be found + sit, err := eventer.FilterSimpleEvent(nil, []common.Address{common.Address{1}, common.Address{3}}, [][32]byte{{byte(1)}, {byte(2)}, {byte(3)}}, []bool{true}) + if err != nil { + t.Fatalf("failed to filter for simple events: %v", err) + } + defer sit.Close() + + sit.Next() + if sit.Event.Value.Uint64() != 11 || !sit.Event.Flag { + t.Errorf("simple log content mismatch: have %v, want {11, true}", sit.Event) + } + sit.Next() + if sit.Event.Value.Uint64() != 21 || !sit.Event.Flag { + t.Errorf("simple log content mismatch: have %v, want {21, true}", sit.Event) + } + sit.Next() + if sit.Event.Value.Uint64() != 31 || !sit.Event.Flag { + t.Errorf("simple log content mismatch: have %v, want {31, true}", sit.Event) + } + sit.Next() + if sit.Event.Value.Uint64() != 33 || !sit.Event.Flag { + t.Errorf("simple log content mismatch: have %v, want {33, true}", sit.Event) + } + + if sit.Next() { + t.Errorf("unexpected simple event found: %+v", sit.Event) + } + if err = sit.Error(); err != nil { + t.Fatalf("simple event iteration failed: %v", err) + } + // Test raising and filtering for an event with no data component + if _, err := eventer.RaiseNodataEvent(auth, big.NewInt(314), 141, 271); err != nil { + t.Fatalf("failed to raise nodata event: %v", err) + } + sim.Commit() + + nit, err := eventer.FilterNodataEvent(nil, []*big.Int{big.NewInt(314)}, []int16{140, 141, 142}, []uint32{271}) + if err != nil { + t.Fatalf("failed to filter for nodata events: %v", err) + } + defer nit.Close() + + if !nit.Next() { + t.Fatalf("nodata log not found: %v", nit.Error()) + } + if nit.Event.Number.Uint64() != 314 { + t.Errorf("nodata log content mismatch: have %v, want 314", nit.Event.Number) + } + if nit.Next() { + t.Errorf("unexpected nodata event found: %+v", nit.Event) + } + if err = nit.Error(); err != nil { + t.Fatalf("nodata event iteration failed: %v", err) + } + // Test raising and filtering for events with dynamic indexed components + if _, err := eventer.RaiseDynamicEvent(auth, "Hello", []byte("World")); err != nil { + t.Fatalf("failed to raise dynamic event: %v", err) + } + sim.Commit() + + dit, err := eventer.FilterDynamicEvent(nil, []string{"Hi", "Hello", "Bye"}, [][]byte{[]byte("World")}) + if err != nil { + t.Fatalf("failed to filter for dynamic events: %v", err) + } + defer dit.Close() + + if !dit.Next() { + t.Fatalf("dynamic log not found: %v", dit.Error()) + } + if dit.Event.NonIndexedString != "Hello" || string(dit.Event.NonIndexedBytes) != "World" || dit.Event.IndexedString != common.HexToHash("0x06b3dfaec148fb1bb2b066f10ec285e7c9bf402ab32aa78a5d38e34566810cd2") || dit.Event.IndexedBytes != common.HexToHash("0xf2208c967df089f60420785795c0a9ba8896b0f6f1867fa7f1f12ad6f79c1a18") { + t.Errorf("dynamic log content mismatch: have %v, want {'0x06b3dfaec148fb1bb2b066f10ec285e7c9bf402ab32aa78a5d38e34566810cd2, '0xf2208c967df089f60420785795c0a9ba8896b0f6f1867fa7f1f12ad6f79c1a18', 'Hello', 'World'}", dit.Event) + } + if dit.Next() { + t.Errorf("unexpected dynamic event found: %+v", dit.Event) + } + if err = dit.Error(); err != nil { + t.Fatalf("dynamic event iteration failed: %v", err) + } + // Test subscribing to an event and raising it afterwards + ch := make(chan *EventerSimpleEvent, 16) + sub, err := eventer.WatchSimpleEvent(nil, ch, nil, nil, nil) + if err != nil { + t.Fatalf("failed to subscribe to simple events: %v", err) + } + if _, err := eventer.RaiseSimpleEvent(auth, common.Address{255}, [32]byte{255}, true, big.NewInt(255)); err != nil { + t.Fatalf("failed to raise subscribed simple event: %v", err) + } + sim.Commit() + + select { + case event := <-ch: + if event.Value.Uint64() != 255 { + t.Errorf("simple log content mismatch: have %v, want 255", event) + } + case <-time.After(250 * time.Millisecond): + t.Fatalf("subscribed simple event didn't arrive") + } + // Unsubscribe from the event and make sure we're not delivered more + sub.Unsubscribe() + + if _, err := eventer.RaiseSimpleEvent(auth, common.Address{254}, [32]byte{254}, true, big.NewInt(254)); err != nil { + t.Fatalf("failed to raise subscribed simple event: %v", err) + } + sim.Commit() + + select { + case event := <-ch: + t.Fatalf("unsubscribed simple event arrived: %v", event) + case <-time.After(250 * time.Millisecond): + } + `, + }, } // Tests that packages generated by the binder can be successfully compiled and @@ -498,7 +788,7 @@ func TestBindings(t *testing.T) { } } // Test the entire package and report any failures - cmd := exec.Command(gocmd, "test", "-v") + cmd := exec.Command(gocmd, "test", "-v", "-count", "1") cmd.Dir = pkg if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("failed to run binding test: %v\n%s", err, out) diff --git a/accounts/abi/bind/template.go b/accounts/abi/bind/template.go index d07610e7c..7202ee67a 100644 --- a/accounts/abi/bind/template.go +++ b/accounts/abi/bind/template.go @@ -32,6 +32,7 @@ type tmplContract struct { Constructor abi.Method // Contract constructor for deploy parametrization Calls map[string]*tmplMethod // Contract calls that only read state data Transacts map[string]*tmplMethod // Contract calls that write state data + Events map[string]*tmplEvent // Contract events accessors } // tmplMethod is a wrapper around an abi.Method that contains a few preprocessed @@ -39,7 +40,13 @@ type tmplContract struct { type tmplMethod struct { Original abi.Method // Original method as parsed by the abi package Normalized abi.Method // Normalized version of the parsed method (capitalized names, non-anonymous args/returns) - Structured bool // Whether the returns should be accumulated into a contract + Structured bool // Whether the returns should be accumulated into a struct +} + +// tmplEvent is a wrapper around an a +type tmplEvent struct { + Original abi.Event // Original event as parsed by the abi package + Normalized abi.Event // Normalized version of the parsed fields } // tmplSource is language to template mapping containing all the supported @@ -75,7 +82,7 @@ package {{.Package}} if err != nil { return common.Address{}, nil, nil, err } - return address, tx, &{{.Type}}{ {{.Type}}Caller: {{.Type}}Caller{contract: contract}, {{.Type}}Transactor: {{.Type}}Transactor{contract: contract} }, nil + return address, tx, &{{.Type}}{ {{.Type}}Caller: {{.Type}}Caller{contract: contract}, {{.Type}}Transactor: {{.Type}}Transactor{contract: contract}, {{.Type}}Filterer: {{.Type}}Filterer{contract: contract} }, nil } {{end}} @@ -83,6 +90,7 @@ package {{.Package}} type {{.Type}} struct { {{.Type}}Caller // Read-only binding to the contract {{.Type}}Transactor // Write-only binding to the contract + {{.Type}}Filterer // Log filterer for contract events } // {{.Type}}Caller is an auto generated read-only Go binding around an Ethereum contract. @@ -95,6 +103,11 @@ package {{.Package}} contract *bind.BoundContract // Generic contract wrapper for the low level calls } + // {{.Type}}Filterer is an auto generated log filtering Go binding around an Ethereum contract events. + type {{.Type}}Filterer struct { + contract *bind.BoundContract // Generic contract wrapper for the low level calls + } + // {{.Type}}Session is an auto generated Go binding around an Ethereum contract, // with pre-set call and transact options. type {{.Type}}Session struct { @@ -134,16 +147,16 @@ package {{.Package}} // New{{.Type}} creates a new instance of {{.Type}}, bound to a specific deployed contract. func New{{.Type}}(address common.Address, backend bind.ContractBackend) (*{{.Type}}, error) { - contract, err := bind{{.Type}}(address, backend, backend) + contract, err := bind{{.Type}}(address, backend, backend, backend) if err != nil { return nil, err } - return &{{.Type}}{ {{.Type}}Caller: {{.Type}}Caller{contract: contract}, {{.Type}}Transactor: {{.Type}}Transactor{contract: contract} }, nil + return &{{.Type}}{ {{.Type}}Caller: {{.Type}}Caller{contract: contract}, {{.Type}}Transactor: {{.Type}}Transactor{contract: contract}, {{.Type}}Filterer: {{.Type}}Filterer{contract: contract} }, nil } // New{{.Type}}Caller creates a new read-only instance of {{.Type}}, bound to a specific deployed contract. func New{{.Type}}Caller(address common.Address, caller bind.ContractCaller) (*{{.Type}}Caller, error) { - contract, err := bind{{.Type}}(address, caller, nil) + contract, err := bind{{.Type}}(address, caller, nil, nil) if err != nil { return nil, err } @@ -152,20 +165,29 @@ package {{.Package}} // New{{.Type}}Transactor creates a new write-only instance of {{.Type}}, bound to a specific deployed contract. func New{{.Type}}Transactor(address common.Address, transactor bind.ContractTransactor) (*{{.Type}}Transactor, error) { - contract, err := bind{{.Type}}(address, nil, transactor) + contract, err := bind{{.Type}}(address, nil, transactor, nil) if err != nil { return nil, err } return &{{.Type}}Transactor{contract: contract}, nil } + // New{{.Type}}Filterer creates a new log filterer instance of {{.Type}}, bound to a specific deployed contract. + func New{{.Type}}Filterer(address common.Address, filterer bind.ContractFilterer) (*{{.Type}}Filterer, error) { + contract, err := bind{{.Type}}(address, nil, nil, filterer) + if err != nil { + return nil, err + } + return &{{.Type}}Filterer{contract: contract}, nil + } + // bind{{.Type}} binds a generic wrapper to an already deployed contract. - func bind{{.Type}}(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor) (*bind.BoundContract, error) { + func bind{{.Type}}(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { parsed, err := abi.JSON(strings.NewReader({{.Type}}ABI)) if err != nil { return nil, err } - return bind.NewBoundContract(address, parsed, caller, transactor), nil + return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil } // Call invokes the (constant) contract method with params as input values and @@ -263,6 +285,137 @@ package {{.Package}} return _{{$contract.Type}}.Contract.{{.Normalized.Name}}(&_{{$contract.Type}}.TransactOpts {{range $i, $_ := .Normalized.Inputs}}, {{.Name}}{{end}}) } {{end}} + + {{range .Events}} + // {{$contract.Type}}{{.Normalized.Name}}Iterator is returned from Filter{{.Normalized.Name}} and is used to iterate over the raw logs and unpacked data for {{.Normalized.Name}} events raised by the {{$contract.Type}} contract. + type {{$contract.Type}}{{.Normalized.Name}}Iterator struct { + Event *{{$contract.Type}}{{.Normalized.Name}} // Event containing the contract specifics and raw log + + contract *bind.BoundContract // Generic contract to use for unpacking event data + event string // Event name to use for unpacking event data + + logs chan types.Log // Log channel receiving the found contract events + sub ethereum.Subscription // Subscription for errors, completion and termination + done bool // Whether the subscription completed delivering logs + fail error // Occurred error to stop iteration + } + // Next advances the iterator to the subsequent event, returning whether there + // are any more events found. In case of a retrieval or parsing error, false is + // returned and Error() can be queried for the exact failure. + func (it *{{$contract.Type}}{{.Normalized.Name}}Iterator) Next() bool { + // If the iterator failed, stop iterating + if (it.fail != nil) { + return false + } + // If the iterator completed, deliver directly whatever's available + if (it.done) { + select { + case log := <-it.logs: + it.Event = new({{$contract.Type}}{{.Normalized.Name}}) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + default: + return false + } + } + // Iterator still in progress, wait for either a data or an error event + select { + case log := <-it.logs: + it.Event = new({{$contract.Type}}{{.Normalized.Name}}) + if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { + it.fail = err + return false + } + it.Event.Raw = log + return true + + case err := <-it.sub.Err(): + it.done = true + it.fail = err + return it.Next() + } + } + // Error returns any retrieval or parsing error occurred during filtering. + func (it *{{$contract.Type}}{{.Normalized.Name}}Iterator) Error() error { + return it.fail + } + // Close terminates the iteration process, releasing any pending underlying + // resources. + func (it *{{$contract.Type}}{{.Normalized.Name}}Iterator) Close() error { + it.sub.Unsubscribe() + return nil + } + + // {{$contract.Type}}{{.Normalized.Name}} represents a {{.Normalized.Name}} event raised by the {{$contract.Type}} contract. + type {{$contract.Type}}{{.Normalized.Name}} struct { {{range .Normalized.Inputs}} + {{capitalise .Name}} {{if .Indexed}}{{bindtopictype .Type}}{{else}}{{bindtype .Type}}{{end}}; {{end}} + Raw types.Log // Blockchain specific contextual infos + } + + // Filter{{.Normalized.Name}} is a free log retrieval operation binding the contract event 0x{{printf "%x" .Original.Id}}. + // + // Solidity: {{.Original.String}} + func (_{{$contract.Type}} *{{$contract.Type}}Filterer) Filter{{.Normalized.Name}}(opts *bind.FilterOpts{{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}} []{{bindtype .Type}}{{end}}{{end}}) (*{{$contract.Type}}{{.Normalized.Name}}Iterator, error) { + {{range .Normalized.Inputs}} + {{if .Indexed}}var {{.Name}}Rule []interface{} + for _, {{.Name}}Item := range {{.Name}} { + {{.Name}}Rule = append({{.Name}}Rule, {{.Name}}Item) + }{{end}}{{end}} + + logs, sub, err := _{{$contract.Type}}.contract.FilterLogs(opts, "{{.Original.Name}}"{{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}}Rule{{end}}{{end}}) + if err != nil { + return nil, err + } + return &{{$contract.Type}}{{.Normalized.Name}}Iterator{contract: _{{$contract.Type}}.contract, event: "{{.Original.Name}}", logs: logs, sub: sub}, nil + } + + // Watch{{.Normalized.Name}} is a free log subscription operation binding the contract event 0x{{printf "%x" .Original.Id}}. + // + // Solidity: {{.Original.String}} + func (_{{$contract.Type}} *{{$contract.Type}}Filterer) Watch{{.Normalized.Name}}(opts *bind.WatchOpts, sink chan<- *{{$contract.Type}}{{.Normalized.Name}}{{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}} []{{bindtype .Type}}{{end}}{{end}}) (event.Subscription, error) { + {{range .Normalized.Inputs}} + {{if .Indexed}}var {{.Name}}Rule []interface{} + for _, {{.Name}}Item := range {{.Name}} { + {{.Name}}Rule = append({{.Name}}Rule, {{.Name}}Item) + }{{end}}{{end}} + + logs, sub, err := _{{$contract.Type}}.contract.WatchLogs(opts, "{{.Original.Name}}"{{range .Normalized.Inputs}}{{if .Indexed}}, {{.Name}}Rule{{end}}{{end}}) + if err != nil { + return nil, err + } + return event.NewSubscription(func(quit <-chan struct{}) error { + defer sub.Unsubscribe() + for { + select { + case log := <-logs: + // New log arrived, parse the event and forward to the user + event := new({{$contract.Type}}{{.Normalized.Name}}) + if err := _{{$contract.Type}}.contract.UnpackLog(event, "{{.Original.Name}}", log); err != nil { + return err + } + event.Raw = log + + select { + case sink <- event: + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + case err := <-sub.Err(): + return err + case <-quit: + return nil + } + } + }), nil + } + {{end}} {{end}} ` diff --git a/accounts/abi/bind/topics.go b/accounts/abi/bind/topics.go new file mode 100644 index 000000000..600dfcda9 --- /dev/null +++ b/accounts/abi/bind/topics.go @@ -0,0 +1,189 @@ +// Copyright 2018 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. + +package bind + +import ( + "errors" + "fmt" + "math/big" + "reflect" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" +) + +// makeTopics converts a filter query argument list into a filter topic set. +func makeTopics(query ...[]interface{}) ([][]common.Hash, error) { + topics := make([][]common.Hash, len(query)) + for i, filter := range query { + for _, rule := range filter { + var topic common.Hash + + // Try to generate the topic based on simple types + switch rule := rule.(type) { + case common.Hash: + copy(topic[:], rule[:]) + case common.Address: + copy(topic[common.HashLength-common.AddressLength:], rule[:]) + case *big.Int: + blob := rule.Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case bool: + if rule { + topic[common.HashLength-1] = 1 + } + case int8: + blob := big.NewInt(int64(rule)).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case int16: + blob := big.NewInt(int64(rule)).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case int32: + blob := big.NewInt(int64(rule)).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case int64: + blob := big.NewInt(rule).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case uint8: + blob := new(big.Int).SetUint64(uint64(rule)).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case uint16: + blob := new(big.Int).SetUint64(uint64(rule)).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case uint32: + blob := new(big.Int).SetUint64(uint64(rule)).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case uint64: + blob := new(big.Int).SetUint64(rule).Bytes() + copy(topic[common.HashLength-len(blob):], blob) + case string: + hash := crypto.Keccak256Hash([]byte(rule)) + copy(topic[:], hash[:]) + case []byte: + hash := crypto.Keccak256Hash(rule) + copy(topic[:], hash[:]) + + default: + // Attempt to generate the topic from funky types + val := reflect.ValueOf(rule) + + switch { + case val.Kind() == reflect.Array && reflect.TypeOf(rule).Elem().Kind() == reflect.Uint8: + reflect.Copy(reflect.ValueOf(topic[common.HashLength-val.Len():]), val) + + default: + return nil, fmt.Errorf("unsupported indexed type: %T", rule) + } + } + topics[i] = append(topics[i], topic) + } + } + return topics, nil +} + +// Big batch of reflect types for topic reconstruction. +var ( + reflectHash = reflect.TypeOf(common.Hash{}) + reflectAddress = reflect.TypeOf(common.Address{}) + reflectBigInt = reflect.TypeOf(new(big.Int)) +) + +// parseTopics converts the indexed topic fields into actual log field values. +// +// Note, dynamic types cannot be reconstructed since they get mapped to Keccak256 +// hashes as the topic value! +func parseTopics(out interface{}, fields abi.Arguments, topics []common.Hash) error { + // Sanity check that the fields and topics match up + if len(fields) != len(topics) { + return errors.New("topic/field count mismatch") + } + // Iterate over all the fields and reconstruct them from topics + for _, arg := range fields { + if !arg.Indexed { + return errors.New("non-indexed field in topic reconstruction") + } + field := reflect.ValueOf(out).Elem().FieldByName(capitalise(arg.Name)) + + // Try to parse the topic back into the fields based on primitive types + switch field.Kind() { + case reflect.Bool: + if topics[0][common.HashLength-1] == 1 { + field.Set(reflect.ValueOf(true)) + } + case reflect.Int8: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(int8(num.Int64()))) + + case reflect.Int16: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(int16(num.Int64()))) + + case reflect.Int32: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(int32(num.Int64()))) + + case reflect.Int64: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(num.Int64())) + + case reflect.Uint8: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(uint8(num.Uint64()))) + + case reflect.Uint16: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(uint16(num.Uint64()))) + + case reflect.Uint32: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(uint32(num.Uint64()))) + + case reflect.Uint64: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(num.Uint64())) + + default: + // Ran out of plain primitive types, try custom types + switch field.Type() { + case reflectHash: // Also covers all dynamic types + field.Set(reflect.ValueOf(topics[0])) + + case reflectAddress: + var addr common.Address + copy(addr[:], topics[0][common.HashLength-common.AddressLength:]) + field.Set(reflect.ValueOf(addr)) + + case reflectBigInt: + num := new(big.Int).SetBytes(topics[0][:]) + field.Set(reflect.ValueOf(num)) + + default: + // Ran out of custom types, try the crazies + switch { + case arg.Type.T == abi.FixedBytesTy: + reflect.Copy(field, reflect.ValueOf(topics[0][common.HashLength-arg.Type.Size:])) + + default: + return fmt.Errorf("unsupported indexed type: %v", arg.Type) + } + } + } + topics = topics[1:] + } + return nil +} diff --git a/accounts/abi/bind/util_test.go b/accounts/abi/bind/util_test.go index d24aa721e..49e6dc813 100644 --- a/accounts/abi/bind/util_test.go +++ b/accounts/abi/bind/util_test.go @@ -34,18 +34,18 @@ var testKey, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d var waitDeployedTests = map[string]struct { code string - gas *big.Int + gas uint64 wantAddress common.Address wantErr error }{ "successful deploy": { code: `6060604052600a8060106000396000f360606040526008565b00`, - gas: big.NewInt(3000000), + gas: 3000000, wantAddress: common.HexToAddress("0x3a220f351252089d385b29beca14e27f204c296a"), }, "empty code": { code: ``, - gas: big.NewInt(300000), + gas: 300000, wantErr: bind.ErrNoCodeAfterDeploy, wantAddress: common.HexToAddress("0x3a220f351252089d385b29beca14e27f204c296a"), }, diff --git a/accounts/abi/event.go b/accounts/abi/event.go index 44ed7b8df..595f169f3 100644 --- a/accounts/abi/event.go +++ b/accounts/abi/event.go @@ -18,7 +18,6 @@ package abi import ( "fmt" - "reflect" "strings" "github.com/ethereum/go-ethereum/common" @@ -31,7 +30,18 @@ import ( type Event struct { Name string Anonymous bool - Inputs []Argument + Inputs Arguments +} + +func (event Event) String() string { + inputs := make([]string, len(event.Inputs)) + for i, input := range event.Inputs { + inputs[i] = fmt.Sprintf("%v %v", input.Name, input.Type) + if input.Indexed { + inputs[i] = fmt.Sprintf("%v indexed %v", input.Name, input.Type) + } + } + return fmt.Sprintf("event %v(%v)", event.Name, strings.Join(inputs, ", ")) } // Id returns the canonical representation of the event's signature used by the @@ -45,93 +55,3 @@ func (e Event) Id() common.Hash { } return common.BytesToHash(crypto.Keccak256([]byte(fmt.Sprintf("%v(%v)", e.Name, strings.Join(types, ","))))) } - -// unpacks an event return tuple into a struct of corresponding go types -// -// Unpacking can be done into a struct or a slice/array. -func (e Event) tupleUnpack(v interface{}, output []byte) error { - // make sure the passed value is a pointer - valueOf := reflect.ValueOf(v) - if reflect.Ptr != valueOf.Kind() { - return fmt.Errorf("abi: Unpack(non-pointer %T)", v) - } - - var ( - value = valueOf.Elem() - typ = value.Type() - ) - - if value.Kind() != reflect.Struct { - return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ) - } - - j := 0 - for i := 0; i < len(e.Inputs); i++ { - input := e.Inputs[i] - if input.Indexed { - // can't read, continue - continue - } else if input.Type.T == ArrayTy { - // need to move this up because they read sequentially - j += input.Type.Size - } - marshalledValue, err := toGoType((i+j)*32, input.Type, output) - if err != nil { - return err - } - reflectValue := reflect.ValueOf(marshalledValue) - - switch value.Kind() { - case reflect.Struct: - for j := 0; j < typ.NumField(); j++ { - field := typ.Field(j) - // TODO read tags: `abi:"fieldName"` - if field.Name == strings.ToUpper(e.Inputs[i].Name[:1])+e.Inputs[i].Name[1:] { - if err := set(value.Field(j), reflectValue, e.Inputs[i]); err != nil { - return err - } - } - } - case reflect.Slice, reflect.Array: - if value.Len() < i { - return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(e.Inputs), value.Len()) - } - v := value.Index(i) - if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { - return fmt.Errorf("abi: cannot unmarshal %v in to %v", v.Type(), reflectValue.Type()) - } - reflectValue := reflect.ValueOf(marshalledValue) - if err := set(v.Elem(), reflectValue, e.Inputs[i]); err != nil { - return err - } - default: - return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ) - } - } - return nil -} - -func (e Event) isTupleReturn() bool { return len(e.Inputs) > 1 } - -func (e Event) singleUnpack(v interface{}, output []byte) error { - // make sure the passed value is a pointer - valueOf := reflect.ValueOf(v) - if reflect.Ptr != valueOf.Kind() { - return fmt.Errorf("abi: Unpack(non-pointer %T)", v) - } - - if e.Inputs[0].Indexed { - return fmt.Errorf("abi: attempting to unpack indexed variable into element.") - } - - value := valueOf.Elem() - - marshalledValue, err := toGoType(0, e.Inputs[0].Type, output) - if err != nil { - return err - } - if err := set(value, reflect.ValueOf(marshalledValue), e.Inputs[0]); err != nil { - return err - } - return nil -} diff --git a/accounts/abi/event_test.go b/accounts/abi/event_test.go index 7e2f13f76..cca61e433 100644 --- a/accounts/abi/event_test.go +++ b/accounts/abi/event_test.go @@ -17,13 +17,53 @@ package abi import ( + "bytes" + "encoding/hex" + "encoding/json" + "math/big" + "reflect" "strings" "testing" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +var jsonEventTransfer = []byte(`{ + "anonymous": false, + "inputs": [ + { + "indexed": true, "name": "from", "type": "address" + }, { + "indexed": true, "name": "to", "type": "address" + }, { + "indexed": false, "name": "value", "type": "uint256" + }], + "name": "Transfer", + "type": "event" +}`) + +var jsonEventPledge = []byte(`{ + "anonymous": false, + "inputs": [{ + "indexed": false, "name": "who", "type": "address" + }, { + "indexed": false, "name": "wad", "type": "uint128" + }, { + "indexed": false, "name": "currency", "type": "bytes3" + }], + "name": "Pledge", + "type": "event" +}`) + +// 1000000 +var transferData1 = "00000000000000000000000000000000000000000000000000000000000f4240" + +// "0x00Ce0d46d924CC8437c806721496599FC3FFA268", 2218516807680, "usd" +var pledgeData1 = "00000000000000000000000000ce0d46d924cc8437c806721496599fc3ffa2680000000000000000000000000000000000000000000000000000020489e800007573640000000000000000000000000000000000000000000000000000000000" + func TestEventId(t *testing.T) { var table = []struct { definition string @@ -54,3 +94,223 @@ func TestEventId(t *testing.T) { } } } + +// TestEventMultiValueWithArrayUnpack verifies that array fields will be counted after parsing array. +func TestEventMultiValueWithArrayUnpack(t *testing.T) { + definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": false, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"uint8"}]}]` + type testStruct struct { + Value1 [2]uint8 + Value2 uint8 + } + abi, err := JSON(strings.NewReader(definition)) + require.NoError(t, err) + var b bytes.Buffer + var i uint8 = 1 + for ; i <= 3; i++ { + b.Write(packNum(reflect.ValueOf(i))) + } + var rst testStruct + require.NoError(t, abi.Unpack(&rst, "test", b.Bytes())) + require.Equal(t, [2]uint8{1, 2}, rst.Value1) + require.Equal(t, uint8(3), rst.Value2) +} + +func TestEventTupleUnpack(t *testing.T) { + + type EventTransfer struct { + Value *big.Int + } + + type EventPledge struct { + Who common.Address + Wad *big.Int + Currency [3]byte + } + + type BadEventPledge struct { + Who string + Wad int + Currency [3]byte + } + + bigint := new(big.Int) + bigintExpected := big.NewInt(1000000) + bigintExpected2 := big.NewInt(2218516807680) + addr := common.HexToAddress("0x00Ce0d46d924CC8437c806721496599FC3FFA268") + var testCases = []struct { + data string + dest interface{} + expected interface{} + jsonLog []byte + error string + name string + }{{ + transferData1, + &EventTransfer{}, + &EventTransfer{Value: bigintExpected}, + jsonEventTransfer, + "", + "Can unpack ERC20 Transfer event into structure", + }, { + transferData1, + &[]interface{}{&bigint}, + &[]interface{}{&bigintExpected}, + jsonEventTransfer, + "", + "Can unpack ERC20 Transfer event into slice", + }, { + pledgeData1, + &EventPledge{}, + &EventPledge{ + addr, + bigintExpected2, + [3]byte{'u', 's', 'd'}}, + jsonEventPledge, + "", + "Can unpack Pledge event into structure", + }, { + pledgeData1, + &[]interface{}{&common.Address{}, &bigint, &[3]byte{}}, + &[]interface{}{ + &addr, + &bigintExpected2, + &[3]byte{'u', 's', 'd'}}, + jsonEventPledge, + "", + "Can unpack Pledge event into slice", + }, { + pledgeData1, + &[3]interface{}{&common.Address{}, &bigint, &[3]byte{}}, + &[3]interface{}{ + &addr, + &bigintExpected2, + &[3]byte{'u', 's', 'd'}}, + jsonEventPledge, + "", + "Can unpack Pledge event into an array", + }, { + pledgeData1, + &[]interface{}{new(int), 0, 0}, + &[]interface{}{}, + jsonEventPledge, + "abi: cannot unmarshal common.Address in to int", + "Can not unpack Pledge event into slice with wrong types", + }, { + pledgeData1, + &BadEventPledge{}, + &BadEventPledge{}, + jsonEventPledge, + "abi: cannot unmarshal common.Address in to string", + "Can not unpack Pledge event into struct with wrong filed types", + }, { + pledgeData1, + &[]interface{}{common.Address{}, new(big.Int)}, + &[]interface{}{}, + jsonEventPledge, + "abi: insufficient number of elements in the list/array for unpack, want 3, got 2", + "Can not unpack Pledge event into too short slice", + }, { + pledgeData1, + new(map[string]interface{}), + &[]interface{}{}, + jsonEventPledge, + "abi: cannot unmarshal tuple into map[string]interface {}", + "Can not unpack Pledge event into map", + }} + + for _, tc := range testCases { + assert := assert.New(t) + tc := tc + t.Run(tc.name, func(t *testing.T) { + err := unpackTestEventData(tc.dest, tc.data, tc.jsonLog, assert) + if tc.error == "" { + assert.Nil(err, "Should be able to unpack event data.") + assert.Equal(tc.expected, tc.dest, tc.name) + } else { + assert.EqualError(err, tc.error) + } + }) + } +} + +func unpackTestEventData(dest interface{}, hexData string, jsonEvent []byte, assert *assert.Assertions) error { + data, err := hex.DecodeString(hexData) + assert.NoError(err, "Hex data should be a correct hex-string") + var e Event + assert.NoError(json.Unmarshal(jsonEvent, &e), "Should be able to unmarshal event ABI") + a := ABI{Events: map[string]Event{"e": e}} + return a.Unpack(dest, "e", data) +} + +/* +Taken from +https://github.com/ethereum/go-ethereum/pull/15568 +*/ + +type testResult struct { + Values [2]*big.Int + Value1 *big.Int + Value2 *big.Int +} + +type testCase struct { + definition string + want testResult +} + +func (tc testCase) encoded(intType, arrayType Type) []byte { + var b bytes.Buffer + if tc.want.Value1 != nil { + val, _ := intType.pack(reflect.ValueOf(tc.want.Value1)) + b.Write(val) + } + + if !reflect.DeepEqual(tc.want.Values, [2]*big.Int{nil, nil}) { + val, _ := arrayType.pack(reflect.ValueOf(tc.want.Values)) + b.Write(val) + } + if tc.want.Value2 != nil { + val, _ := intType.pack(reflect.ValueOf(tc.want.Value2)) + b.Write(val) + } + return b.Bytes() +} + +// TestEventUnpackIndexed verifies that indexed field will be skipped by event decoder. +func TestEventUnpackIndexed(t *testing.T) { + definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8"},{"indexed": false, "name":"value2", "type":"uint8"}]}]` + type testStruct struct { + Value1 uint8 + Value2 uint8 + } + abi, err := JSON(strings.NewReader(definition)) + require.NoError(t, err) + var b bytes.Buffer + b.Write(packNum(reflect.ValueOf(uint8(8)))) + var rst testStruct + require.NoError(t, abi.Unpack(&rst, "test", b.Bytes())) + require.Equal(t, uint8(0), rst.Value1) + require.Equal(t, uint8(8), rst.Value2) +} + +// TestEventIndexedWithArrayUnpack verifies that decoder will not overlow when static array is indexed input. +func TestEventIndexedWithArrayUnpack(t *testing.T) { + definition := `[{"name": "test", "type": "event", "inputs": [{"indexed": true, "name":"value1", "type":"uint8[2]"},{"indexed": false, "name":"value2", "type":"string"}]}]` + type testStruct struct { + Value1 [2]uint8 + Value2 string + } + abi, err := JSON(strings.NewReader(definition)) + require.NoError(t, err) + var b bytes.Buffer + stringOut := "abc" + // number of fields that will be encoded * 32 + b.Write(packNum(reflect.ValueOf(32))) + b.Write(packNum(reflect.ValueOf(len(stringOut)))) + b.Write(common.RightPadBytes([]byte(stringOut), 32)) + + var rst testStruct + require.NoError(t, abi.Unpack(&rst, "test", b.Bytes())) + require.Equal(t, [2]uint8{0, 0}, rst.Value1) + require.Equal(t, stringOut, rst.Value2) +} diff --git a/accounts/abi/method.go b/accounts/abi/method.go index d8838e9ed..f434ffdbe 100644 --- a/accounts/abi/method.go +++ b/accounts/abi/method.go @@ -18,13 +18,12 @@ package abi import ( "fmt" - "reflect" "strings" "github.com/ethereum/go-ethereum/crypto" ) -// Callable method given a `Name` and whether the method is a constant. +// Method represents a callable given a `Name` and whether the method is a constant. // If the method is `Const` no transaction needs to be created for this // particular Method call. It can easily be simulated using a local VM. // For example a `Balance()` method only needs to retrieve something @@ -35,125 +34,8 @@ import ( type Method struct { Name string Const bool - Inputs []Argument - Outputs []Argument -} - -func (method Method) pack(args ...interface{}) ([]byte, error) { - // Make sure arguments match up and pack them - if len(args) != len(method.Inputs) { - return nil, fmt.Errorf("argument count mismatch: %d for %d", len(args), len(method.Inputs)) - } - // variable input is the output appended at the end of packed - // output. This is used for strings and bytes types input. - var variableInput []byte - - var ret []byte - for i, a := range args { - input := method.Inputs[i] - // pack the input - packed, err := input.Type.pack(reflect.ValueOf(a)) - if err != nil { - return nil, fmt.Errorf("`%s` %v", method.Name, err) - } - - // check for a slice type (string, bytes, slice) - if input.Type.requiresLengthPrefix() { - // calculate the offset - offset := len(method.Inputs)*32 + len(variableInput) - // set the offset - ret = append(ret, packNum(reflect.ValueOf(offset))...) - // Append the packed output to the variable input. The variable input - // will be appended at the end of the input. - variableInput = append(variableInput, packed...) - } else { - // append the packed value to the input - ret = append(ret, packed...) - } - } - // append the variable input at the end of the packed input - ret = append(ret, variableInput...) - - return ret, nil -} - -// unpacks a method return tuple into a struct of corresponding go types -// -// Unpacking can be done into a struct or a slice/array. -func (method Method) tupleUnpack(v interface{}, output []byte) error { - // make sure the passed value is a pointer - valueOf := reflect.ValueOf(v) - if reflect.Ptr != valueOf.Kind() { - return fmt.Errorf("abi: Unpack(non-pointer %T)", v) - } - - var ( - value = valueOf.Elem() - typ = value.Type() - ) - - j := 0 - for i := 0; i < len(method.Outputs); i++ { - toUnpack := method.Outputs[i] - if toUnpack.Type.T == ArrayTy { - // need to move this up because they read sequentially - j += toUnpack.Type.Size - } - marshalledValue, err := toGoType((i+j)*32, toUnpack.Type, output) - if err != nil { - return err - } - reflectValue := reflect.ValueOf(marshalledValue) - - switch value.Kind() { - case reflect.Struct: - for j := 0; j < typ.NumField(); j++ { - field := typ.Field(j) - // TODO read tags: `abi:"fieldName"` - if field.Name == strings.ToUpper(method.Outputs[i].Name[:1])+method.Outputs[i].Name[1:] { - if err := set(value.Field(j), reflectValue, method.Outputs[i]); err != nil { - return err - } - } - } - case reflect.Slice, reflect.Array: - if value.Len() < i { - return fmt.Errorf("abi: insufficient number of arguments for unpack, want %d, got %d", len(method.Outputs), value.Len()) - } - v := value.Index(i) - if v.Kind() != reflect.Ptr && v.Kind() != reflect.Interface { - return fmt.Errorf("abi: cannot unmarshal %v in to %v", v.Type(), reflectValue.Type()) - } - reflectValue := reflect.ValueOf(marshalledValue) - if err := set(v.Elem(), reflectValue, method.Outputs[i]); err != nil { - return err - } - default: - return fmt.Errorf("abi: cannot unmarshal tuple in to %v", typ) - } - } - return nil -} - -func (method Method) isTupleReturn() bool { return len(method.Outputs) > 1 } - -func (method Method) singleUnpack(v interface{}, output []byte) error { - // make sure the passed value is a pointer - valueOf := reflect.ValueOf(v) - if reflect.Ptr != valueOf.Kind() { - return fmt.Errorf("abi: Unpack(non-pointer %T)", v) - } - - value := valueOf.Elem() - - marshalledValue, err := toGoType(0, method.Outputs[0].Type, output) - if err != nil { - return err - } - if err := set(value, reflect.ValueOf(marshalledValue), method.Outputs[0]); err != nil { - return err - } - return nil + Inputs Arguments + Outputs Arguments } // Sig returns the methods string signature according to the ABI spec. @@ -163,35 +45,35 @@ func (method Method) singleUnpack(v interface{}, output []byte) error { // function foo(uint32 a, int b) = "foo(uint32,int256)" // // Please note that "int" is substitute for its canonical representation "int256" -func (m Method) Sig() string { - types := make([]string, len(m.Inputs)) +func (method Method) Sig() string { + types := make([]string, len(method.Inputs)) i := 0 - for _, input := range m.Inputs { + for _, input := range method.Inputs { types[i] = input.Type.String() i++ } - return fmt.Sprintf("%v(%v)", m.Name, strings.Join(types, ",")) + return fmt.Sprintf("%v(%v)", method.Name, strings.Join(types, ",")) } -func (m Method) String() string { - inputs := make([]string, len(m.Inputs)) - for i, input := range m.Inputs { +func (method Method) String() string { + inputs := make([]string, len(method.Inputs)) + for i, input := range method.Inputs { inputs[i] = fmt.Sprintf("%v %v", input.Name, input.Type) } - outputs := make([]string, len(m.Outputs)) - for i, output := range m.Outputs { + outputs := make([]string, len(method.Outputs)) + for i, output := range method.Outputs { if len(output.Name) > 0 { outputs[i] = fmt.Sprintf("%v ", output.Name) } outputs[i] += output.Type.String() } constant := "" - if m.Const { + if method.Const { constant = "constant " } - return fmt.Sprintf("function %v(%v) %sreturns(%v)", m.Name, strings.Join(inputs, ", "), constant, strings.Join(outputs, ", ")) + return fmt.Sprintf("function %v(%v) %sreturns(%v)", method.Name, strings.Join(inputs, ", "), constant, strings.Join(outputs, ", ")) } -func (m Method) Id() []byte { - return crypto.Keccak256([]byte(m.Sig()))[:4] +func (method Method) Id() []byte { + return crypto.Keccak256([]byte(method.Sig()))[:4] } diff --git a/accounts/abi/pack.go b/accounts/abi/pack.go index 072e80536..36c58265b 100644 --- a/accounts/abi/pack.go +++ b/accounts/abi/pack.go @@ -48,9 +48,8 @@ func packElement(t Type, reflectValue reflect.Value) []byte { case BoolTy: if reflectValue.Bool() { return math.PaddedBigBytes(common.Big1, 32) - } else { - return math.PaddedBigBytes(common.Big0, 32) } + return math.PaddedBigBytes(common.Big0, 32) case BytesTy: if reflectValue.Kind() == reflect.Array { reflectValue = mustArrayToByteSlice(reflectValue) diff --git a/accounts/abi/reflect.go b/accounts/abi/reflect.go index e953b77c1..7a9cdacd5 100644 --- a/accounts/abi/reflect.go +++ b/accounts/abi/reflect.go @@ -85,3 +85,28 @@ func set(dst, src reflect.Value, output Argument) error { } return nil } + +// requireAssignable assures that `dest` is a pointer and it's not an interface. +func requireAssignable(dst, src reflect.Value) error { + if dst.Kind() != reflect.Ptr && dst.Kind() != reflect.Interface { + return fmt.Errorf("abi: cannot unmarshal %v into %v", src.Type(), dst.Type()) + } + return nil +} + +// requireUnpackKind verifies preconditions for unpacking `args` into `kind` +func requireUnpackKind(v reflect.Value, t reflect.Type, k reflect.Kind, + args Arguments) error { + + switch k { + case reflect.Struct: + case reflect.Slice, reflect.Array: + if minLen := args.LengthNonIndexed(); v.Len() < minLen { + return fmt.Errorf("abi: insufficient number of elements in the list/array for unpack, want %d, got %d", + minLen, v.Len()) + } + default: + return fmt.Errorf("abi: cannot unmarshal tuple into %v", t) + } + return nil +} diff --git a/accounts/abi/type.go b/accounts/abi/type.go index fba10b96d..a1f13ffa2 100644 --- a/accounts/abi/type.go +++ b/accounts/abi/type.go @@ -24,6 +24,7 @@ import ( "strings" ) +// Type enumerator const ( IntTy byte = iota UintTy @@ -100,68 +101,65 @@ func NewType(t string) (typ Type, err error) { return Type{}, fmt.Errorf("invalid formatting of array type") } return typ, err + } + // parse the type and size of the abi-type. + parsedType := typeRegex.FindAllStringSubmatch(t, -1)[0] + // varSize is the size of the variable + var varSize int + if len(parsedType[3]) > 0 { + var err error + varSize, err = strconv.Atoi(parsedType[2]) + if err != nil { + return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) + } } else { - // parse the type and size of the abi-type. - parsedType := typeRegex.FindAllStringSubmatch(t, -1)[0] - // varSize is the size of the variable - var varSize int - if len(parsedType[3]) > 0 { - var err error - varSize, err = strconv.Atoi(parsedType[2]) - if err != nil { - return Type{}, fmt.Errorf("abi: error parsing variable size: %v", err) - } - } else { - if parsedType[0] == "uint" || parsedType[0] == "int" { - // this should fail because it means that there's something wrong with - // the abi type (the compiler should always format it to the size...always) - return Type{}, fmt.Errorf("unsupported arg type: %s", t) - } + if parsedType[0] == "uint" || parsedType[0] == "int" { + // this should fail because it means that there's something wrong with + // the abi type (the compiler should always format it to the size...always) + return Type{}, fmt.Errorf("unsupported arg type: %s", t) } - // varType is the parsed abi type - varType := parsedType[1] - - switch varType { - case "int": - typ.Kind, typ.Type = reflectIntKindAndType(false, varSize) - typ.Size = varSize - typ.T = IntTy - case "uint": - typ.Kind, typ.Type = reflectIntKindAndType(true, varSize) - typ.Size = varSize - typ.T = UintTy - case "bool": - typ.Kind = reflect.Bool - typ.T = BoolTy - typ.Type = reflect.TypeOf(bool(false)) - case "address": - typ.Kind = reflect.Array - typ.Type = address_t - typ.Size = 20 - typ.T = AddressTy - case "string": - typ.Kind = reflect.String - typ.Type = reflect.TypeOf("") - typ.T = StringTy - case "bytes": - if varSize == 0 { - typ.T = BytesTy - typ.Kind = reflect.Slice - typ.Type = reflect.SliceOf(reflect.TypeOf(byte(0))) - } else { - typ.T = FixedBytesTy - typ.Kind = reflect.Array - typ.Size = varSize - typ.Type = reflect.ArrayOf(varSize, reflect.TypeOf(byte(0))) - } - case "function": + } + // varType is the parsed abi type + switch varType := parsedType[1]; varType { + case "int": + typ.Kind, typ.Type = reflectIntKindAndType(false, varSize) + typ.Size = varSize + typ.T = IntTy + case "uint": + typ.Kind, typ.Type = reflectIntKindAndType(true, varSize) + typ.Size = varSize + typ.T = UintTy + case "bool": + typ.Kind = reflect.Bool + typ.T = BoolTy + typ.Type = reflect.TypeOf(bool(false)) + case "address": + typ.Kind = reflect.Array + typ.Type = address_t + typ.Size = 20 + typ.T = AddressTy + case "string": + typ.Kind = reflect.String + typ.Type = reflect.TypeOf("") + typ.T = StringTy + case "bytes": + if varSize == 0 { + typ.T = BytesTy + typ.Kind = reflect.Slice + typ.Type = reflect.SliceOf(reflect.TypeOf(byte(0))) + } else { + typ.T = FixedBytesTy typ.Kind = reflect.Array - typ.T = FunctionTy - typ.Size = 24 - typ.Type = reflect.ArrayOf(24, reflect.TypeOf(byte(0))) - default: - return Type{}, fmt.Errorf("unsupported arg type: %s", t) + typ.Size = varSize + typ.Type = reflect.ArrayOf(varSize, reflect.TypeOf(byte(0))) } + case "function": + typ.Kind = reflect.Array + typ.T = FunctionTy + typ.Size = 24 + typ.Type = reflect.ArrayOf(24, reflect.TypeOf(byte(0))) + default: + return Type{}, fmt.Errorf("unsupported arg type: %s", t) } return diff --git a/accounts/abi/unpack.go b/accounts/abi/unpack.go index 57732797b..80efb3f7e 100644 --- a/accounts/abi/unpack.go +++ b/accounts/abi/unpack.go @@ -25,15 +25,6 @@ import ( "github.com/ethereum/go-ethereum/common" ) -// unpacker is a utility interface that enables us to have -// abstraction between events and methods and also to properly -// "unpack" them; e.g. events use Inputs, methods use Outputs. -type unpacker interface { - tupleUnpack(v interface{}, output []byte) error - singleUnpack(v interface{}, output []byte) error - isTupleReturn() bool -} - // reads the integer based on its kind func readInteger(kind reflect.Kind, b []byte) interface{} { switch kind { @@ -79,7 +70,7 @@ func readBool(word []byte) (bool, error) { // This enforces that standard by always presenting it as a 24-array (address + sig = 24 bytes) func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { if t.T != FunctionTy { - return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array.") + return [24]byte{}, fmt.Errorf("abi: invalid type in call to make function type byte array") } if garbage := binary.BigEndian.Uint64(word[24:32]); garbage != 0 { err = fmt.Errorf("abi: got improperly encoded function type, got %v", word) @@ -92,7 +83,7 @@ func readFunctionType(t Type, word []byte) (funcTy [24]byte, err error) { // through reflection, creates a fixed array to be read from func readFixedBytes(t Type, word []byte) (interface{}, error) { if t.T != FixedBytesTy { - return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array.") + return nil, fmt.Errorf("abi: invalid type in call to make fixed byte array") } // convert array := reflect.New(t.Type).Elem() @@ -203,14 +194,3 @@ func lengthPrefixPointsTo(index int, output []byte) (start int, length int, err //fmt.Printf("LENGTH PREFIX INFO: \nsize: %v\noffset: %v\nstart: %v\n", length, offset, start) return } - -// checks for proper formatting of byte output -func bytesAreProper(output []byte) error { - if len(output) == 0 { - return fmt.Errorf("abi: unmarshalling empty output") - } else if len(output)%32 != 0 { - return fmt.Errorf("abi: improperly formatted output") - } else { - return nil - } -} diff --git a/accounts/abi/unpack_test.go b/accounts/abi/unpack_test.go index 1e21aafc0..4d7fe638c 100644 --- a/accounts/abi/unpack_test.go +++ b/accounts/abi/unpack_test.go @@ -22,10 +22,12 @@ import ( "fmt" "math/big" "reflect" + "strconv" "strings" "testing" "github.com/ethereum/go-ethereum/common" + "github.com/stretchr/testify/require" ) type unpackTest struct { @@ -257,82 +259,179 @@ var unpackTests = []unpackTest{ enc: "000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003", want: [3]*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}, }, + // struct outputs + { + def: `[{"name":"int1","type":"int256"},{"name":"int2","type":"int256"}]`, + enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", + want: struct { + Int1 *big.Int + Int2 *big.Int + }{big.NewInt(1), big.NewInt(2)}, + }, + { + def: `[{"name":"int","type":"int256"},{"name":"Int","type":"int256"}]`, + enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", + want: struct { + Int1 *big.Int + Int2 *big.Int + }{}, + err: "abi: multiple outputs mapping to the same struct field 'Int'", + }, + { + def: `[{"name":"int","type":"int256"},{"name":"_int","type":"int256"}]`, + enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", + want: struct { + Int1 *big.Int + Int2 *big.Int + }{}, + err: "abi: multiple outputs mapping to the same struct field 'Int'", + }, + { + def: `[{"name":"Int","type":"int256"},{"name":"_int","type":"int256"}]`, + enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", + want: struct { + Int1 *big.Int + Int2 *big.Int + }{}, + err: "abi: multiple outputs mapping to the same struct field 'Int'", + }, + { + def: `[{"name":"Int","type":"int256"},{"name":"_","type":"int256"}]`, + enc: "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000002", + want: struct { + Int1 *big.Int + Int2 *big.Int + }{}, + err: "abi: purely underscored output cannot unpack to struct", + }, } func TestUnpack(t *testing.T) { for i, test := range unpackTests { - def := fmt.Sprintf(`[{ "name" : "method", "outputs": %s}]`, test.def) - abi, err := JSON(strings.NewReader(def)) - if err != nil { - t.Fatalf("invalid ABI definition %s: %v", def, err) - } - encb, err := hex.DecodeString(test.enc) - if err != nil { - t.Fatalf("invalid hex: %s" + test.enc) - } - outptr := reflect.New(reflect.TypeOf(test.want)) - err = abi.Unpack(outptr.Interface(), "method", encb) - if err := test.checkError(err); err != nil { - t.Errorf("test %d (%v) failed: %v", i, test.def, err) - continue - } - out := outptr.Elem().Interface() - if !reflect.DeepEqual(test.want, out) { - t.Errorf("test %d (%v) failed: expected %v, got %v", i, test.def, test.want, out) - } + t.Run(strconv.Itoa(i), func(t *testing.T) { + def := fmt.Sprintf(`[{ "name" : "method", "outputs": %s}]`, test.def) + abi, err := JSON(strings.NewReader(def)) + if err != nil { + t.Fatalf("invalid ABI definition %s: %v", def, err) + } + encb, err := hex.DecodeString(test.enc) + if err != nil { + t.Fatalf("invalid hex: %s" + test.enc) + } + outptr := reflect.New(reflect.TypeOf(test.want)) + err = abi.Unpack(outptr.Interface(), "method", encb) + if err := test.checkError(err); err != nil { + t.Errorf("test %d (%v) failed: %v", i, test.def, err) + return + } + out := outptr.Elem().Interface() + if !reflect.DeepEqual(test.want, out) { + t.Errorf("test %d (%v) failed: expected %v, got %v", i, test.def, test.want, out) + } + }) } } -func TestMultiReturnWithStruct(t *testing.T) { +type methodMultiOutput struct { + Int *big.Int + String string +} + +func methodMultiReturn(require *require.Assertions) (ABI, []byte, methodMultiOutput) { const definition = `[ { "name" : "multi", "constant" : false, "outputs": [ { "name": "Int", "type": "uint256" }, { "name": "String", "type": "string" } ] }]` + var expected = methodMultiOutput{big.NewInt(1), "hello"} abi, err := JSON(strings.NewReader(definition)) - if err != nil { - t.Fatal(err) - } - + require.NoError(err) // using buff to make the code readable buff := new(bytes.Buffer) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000040")) buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005")) - stringOut := "hello" - buff.Write(common.RightPadBytes([]byte(stringOut), 32)) + buff.Write(common.RightPadBytes([]byte(expected.String), 32)) + return abi, buff.Bytes(), expected +} - var inter struct { - Int *big.Int +func TestMethodMultiReturn(t *testing.T) { + type reversed struct { String string - } - err = abi.Unpack(&inter, "multi", buff.Bytes()) - if err != nil { - t.Error(err) - } - - if inter.Int == nil || inter.Int.Cmp(big.NewInt(1)) != 0 { - t.Error("expected Int to be 1 got", inter.Int) - } - - if inter.String != stringOut { - t.Error("expected String to be", stringOut, "got", inter.String) + Int *big.Int } - var reversed struct { - String string - Int *big.Int + abi, data, expected := methodMultiReturn(require.New(t)) + bigint := new(big.Int) + var testCases = []struct { + dest interface{} + expected interface{} + error string + name string + }{{ + &methodMultiOutput{}, + &expected, + "", + "Can unpack into structure", + }, { + &reversed{}, + &reversed{expected.String, expected.Int}, + "", + "Can unpack into reversed structure", + }, { + &[]interface{}{&bigint, new(string)}, + &[]interface{}{&expected.Int, &expected.String}, + "", + "Can unpack into a slice", + }, { + &[2]interface{}{&bigint, new(string)}, + &[2]interface{}{&expected.Int, &expected.String}, + "", + "Can unpack into an array", + }, { + &[]interface{}{new(int), new(int)}, + &[]interface{}{&expected.Int, &expected.String}, + "abi: cannot unmarshal *big.Int in to int", + "Can not unpack into a slice with wrong types", + }, { + &[]interface{}{new(int)}, + &[]interface{}{}, + "abi: insufficient number of elements in the list/array for unpack, want 2, got 1", + "Can not unpack into a slice with wrong types", + }} + for _, tc := range testCases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + require := require.New(t) + err := abi.Unpack(tc.dest, "multi", data) + if tc.error == "" { + require.Nil(err, "Should be able to unpack method outputs.") + require.Equal(tc.expected, tc.dest) + } else { + require.EqualError(err, tc.error) + } + }) } +} - err = abi.Unpack(&reversed, "multi", buff.Bytes()) +func TestMultiReturnWithArray(t *testing.T) { + const definition = `[{"name" : "multi", "outputs": [{"type": "uint64[3]"}, {"type": "uint64"}]}]` + abi, err := JSON(strings.NewReader(definition)) if err != nil { - t.Error(err) + t.Fatal(err) } + buff := new(bytes.Buffer) + buff.Write(common.Hex2Bytes("000000000000000000000000000000000000000000000000000000000000000900000000000000000000000000000000000000000000000000000000000000090000000000000000000000000000000000000000000000000000000000000009")) + buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000008")) - if reversed.Int == nil || reversed.Int.Cmp(big.NewInt(1)) != 0 { - t.Error("expected Int to be 1 got", reversed.Int) + ret1, ret1Exp := new([3]uint64), [3]uint64{9, 9, 9} + ret2, ret2Exp := new(uint64), uint64(8) + if err := abi.Unpack(&[]interface{}{ret1, ret2}, "multi", buff.Bytes()); err != nil { + t.Fatal(err) } - - if reversed.String != stringOut { - t.Error("expected String to be", stringOut, "got", reversed.String) + if !reflect.DeepEqual(*ret1, ret1Exp) { + t.Error("array result", *ret1, "!= Expected", ret1Exp) + } + if *ret2 != ret2Exp { + t.Error("int result", *ret2, "!= Expected", ret2Exp) } } diff --git a/accounts/errors.go b/accounts/errors.go index 64da8821c..40b21ed17 100644 --- a/accounts/errors.go +++ b/accounts/errors.go @@ -62,7 +62,7 @@ func NewAuthNeededError(needed string) error { } } -// Error implements the standard error interfacel. +// Error implements the standard error interface. func (err *AuthNeededError) Error() string { return fmt.Sprintf("authentication needed: %s", err.Needed) } diff --git a/accounts/keystore/presale.go b/accounts/keystore/presale.go index ed900ad08..1554294e1 100644 --- a/accounts/keystore/presale.go +++ b/accounts/keystore/presale.go @@ -58,6 +58,9 @@ func decryptPreSaleKey(fileContent []byte, password string) (key *Key, err error if err != nil { return nil, errors.New("invalid hex in encSeed") } + if len(encSeedBytes) < 16 { + return nil, errors.New("invalid encSeed, too short") + } iv := encSeedBytes[:16] cipherText := encSeedBytes[16:] /* diff --git a/accounts/usbwallet/internal/trezor/messages.proto b/accounts/usbwallet/internal/trezor/messages.proto index 178956457..8cb9c8cc2 100644 --- a/accounts/usbwallet/internal/trezor/messages.proto +++ b/accounts/usbwallet/internal/trezor/messages.proto @@ -2,6 +2,8 @@ // https://github.com/trezor/trezor-common/blob/master/protob/messages.proto // dated 28.07.2017, commit dd8ec3231fb5f7992360aff9bdfe30bb58130f4b. +syntax = "proto2"; + /** * Messages for TREZOR communication */ diff --git a/accounts/usbwallet/internal/trezor/trezor.go b/accounts/usbwallet/internal/trezor/trezor.go index 487aeb5f8..8ae9e726e 100644 --- a/accounts/usbwallet/internal/trezor/trezor.go +++ b/accounts/usbwallet/internal/trezor/trezor.go @@ -18,7 +18,7 @@ // wallets. The wire protocol spec can be found on the SatoshiLabs website: // https://doc.satoshilabs.com/trezor-tech/api-protobuf.html -//go:generate protoc --go_out=Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor,import_path=trezor:. types.proto messages.proto +//go:generate protoc --go_out=import_path=trezor:. types.proto messages.proto // Package trezor contains the wire protocol wrapper in Go. package trezor diff --git a/accounts/usbwallet/internal/trezor/types.proto b/accounts/usbwallet/internal/trezor/types.proto index 3a358a584..acbe79e3f 100644 --- a/accounts/usbwallet/internal/trezor/types.proto +++ b/accounts/usbwallet/internal/trezor/types.proto @@ -2,6 +2,8 @@ // https://github.com/trezor/trezor-common/blob/master/protob/types.proto // dated 28.07.2017, commit dd8ec3231fb5f7992360aff9bdfe30bb58130f4b. +syntax = "proto2"; + /** * Types for TREZOR communication * diff --git a/accounts/usbwallet/trezor.go b/accounts/usbwallet/trezor.go index 159cb2ea9..b84a95599 100644 --- a/accounts/usbwallet/trezor.go +++ b/accounts/usbwallet/trezor.go @@ -180,7 +180,7 @@ func (w *trezorDriver) trezorSign(derivationPath []uint32, tx *types.Transaction AddressN: derivationPath, Nonce: new(big.Int).SetUint64(tx.Nonce()).Bytes(), GasPrice: tx.GasPrice().Bytes(), - GasLimit: tx.Gas().Bytes(), + GasLimit: new(big.Int).SetUint64(tx.Gas()).Bytes(), Value: tx.Value().Bytes(), DataLength: &length, } |