github.com/dim4egster/coreth@v0.10.2/accounts/abi/abi.go (about) 1 // (c) 2019-2020, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2015 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package abi 28 29 import ( 30 "bytes" 31 "encoding/json" 32 "errors" 33 "fmt" 34 "io" 35 36 "github.com/ethereum/go-ethereum/common" 37 "github.com/ethereum/go-ethereum/crypto" 38 ) 39 40 // The ABI holds information about a contract's context and available 41 // invokable methods. It will allow you to type check function calls and 42 // packs data accordingly. 43 type ABI struct { 44 Constructor Method 45 Methods map[string]Method 46 Events map[string]Event 47 Errors map[string]Error 48 49 // Additional "special" functions introduced in solidity v0.6.0. 50 // It's separated from the original default fallback. Each contract 51 // can only define one fallback and receive function. 52 Fallback Method // Note it's also used to represent legacy fallback before v0.6.0 53 Receive Method 54 } 55 56 // JSON returns a parsed ABI interface and error if it failed. 57 func JSON(reader io.Reader) (ABI, error) { 58 dec := json.NewDecoder(reader) 59 60 var abi ABI 61 if err := dec.Decode(&abi); err != nil { 62 return ABI{}, err 63 } 64 return abi, nil 65 } 66 67 // Pack the given method name to conform the ABI. Method call's data 68 // will consist of method_id, args0, arg1, ... argN. Method id consists 69 // of 4 bytes and arguments are all 32 bytes. 70 // Method ids are created from the first 4 bytes of the hash of the 71 // methods string signature. (signature = baz(uint32,string32)) 72 func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) { 73 // Fetch the ABI of the requested method 74 if name == "" { 75 // constructor 76 arguments, err := abi.Constructor.Inputs.Pack(args...) 77 if err != nil { 78 return nil, err 79 } 80 return arguments, nil 81 } 82 method, exist := abi.Methods[name] 83 if !exist { 84 return nil, fmt.Errorf("method '%s' not found", name) 85 } 86 arguments, err := method.Inputs.Pack(args...) 87 if err != nil { 88 return nil, err 89 } 90 // Pack up the method ID too if not a constructor and return 91 return append(method.ID, arguments...), nil 92 } 93 94 func (abi ABI) getArguments(name string, data []byte) (Arguments, error) { 95 // since there can't be naming collisions with contracts and events, 96 // we need to decide whether we're calling a method or an event 97 var args Arguments 98 if method, ok := abi.Methods[name]; ok { 99 if len(data)%32 != 0 { 100 return nil, fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data) 101 } 102 args = method.Outputs 103 } 104 if event, ok := abi.Events[name]; ok { 105 args = event.Inputs 106 } 107 if args == nil { 108 return nil, fmt.Errorf("abi: could not locate named method or event: %s", name) 109 } 110 return args, nil 111 } 112 113 // Unpack unpacks the output according to the abi specification. 114 func (abi ABI) Unpack(name string, data []byte) ([]interface{}, error) { 115 args, err := abi.getArguments(name, data) 116 if err != nil { 117 return nil, err 118 } 119 return args.Unpack(data) 120 } 121 122 // UnpackIntoInterface unpacks the output in v according to the abi specification. 123 // It performs an additional copy. Please only use, if you want to unpack into a 124 // structure that does not strictly conform to the abi structure (e.g. has additional arguments) 125 func (abi ABI) UnpackIntoInterface(v interface{}, name string, data []byte) error { 126 args, err := abi.getArguments(name, data) 127 if err != nil { 128 return err 129 } 130 unpacked, err := args.Unpack(data) 131 if err != nil { 132 return err 133 } 134 return args.Copy(v, unpacked) 135 } 136 137 // UnpackIntoMap unpacks a log into the provided map[string]interface{}. 138 func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) { 139 args, err := abi.getArguments(name, data) 140 if err != nil { 141 return err 142 } 143 return args.UnpackIntoMap(v, data) 144 } 145 146 // UnmarshalJSON implements json.Unmarshaler interface. 147 func (abi *ABI) UnmarshalJSON(data []byte) error { 148 var fields []struct { 149 Type string 150 Name string 151 Inputs []Argument 152 Outputs []Argument 153 154 // Status indicator which can be: "pure", "view", 155 // "nonpayable" or "payable". 156 StateMutability string 157 158 // Deprecated Status indicators, but removed in v0.6.0. 159 Constant bool // True if function is either pure or view 160 Payable bool // True if function is payable 161 162 // Event relevant indicator represents the event is 163 // declared as anonymous. 164 Anonymous bool 165 } 166 if err := json.Unmarshal(data, &fields); err != nil { 167 return err 168 } 169 abi.Methods = make(map[string]Method) 170 abi.Events = make(map[string]Event) 171 abi.Errors = make(map[string]Error) 172 for _, field := range fields { 173 switch field.Type { 174 case "constructor": 175 abi.Constructor = NewMethod("", "", Constructor, field.StateMutability, field.Constant, field.Payable, field.Inputs, nil) 176 case "function": 177 name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Methods[s]; return ok }) 178 abi.Methods[name] = NewMethod(name, field.Name, Function, field.StateMutability, field.Constant, field.Payable, field.Inputs, field.Outputs) 179 case "fallback": 180 // New introduced function type in v0.6.0, check more detail 181 // here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function 182 if abi.HasFallback() { 183 return errors.New("only single fallback is allowed") 184 } 185 abi.Fallback = NewMethod("", "", Fallback, field.StateMutability, field.Constant, field.Payable, nil, nil) 186 case "receive": 187 // New introduced function type in v0.6.0, check more detail 188 // here https://solidity.readthedocs.io/en/v0.6.0/contracts.html#fallback-function 189 if abi.HasReceive() { 190 return errors.New("only single receive is allowed") 191 } 192 if field.StateMutability != "payable" { 193 return errors.New("the statemutability of receive can only be payable") 194 } 195 abi.Receive = NewMethod("", "", Receive, field.StateMutability, field.Constant, field.Payable, nil, nil) 196 case "event": 197 name := ResolveNameConflict(field.Name, func(s string) bool { _, ok := abi.Events[s]; return ok }) 198 abi.Events[name] = NewEvent(name, field.Name, field.Anonymous, field.Inputs) 199 case "error": 200 // Errors cannot be overloaded or overridden but are inherited, 201 // no need to resolve the name conflict here. 202 abi.Errors[field.Name] = NewError(field.Name, field.Inputs) 203 default: 204 return fmt.Errorf("abi: could not recognize type %v of field %v", field.Type, field.Name) 205 } 206 } 207 return nil 208 } 209 210 // MethodById looks up a method by the 4-byte id, 211 // returns nil if none found. 212 func (abi *ABI) MethodById(sigdata []byte) (*Method, error) { 213 if len(sigdata) < 4 { 214 return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata)) 215 } 216 for _, method := range abi.Methods { 217 if bytes.Equal(method.ID, sigdata[:4]) { 218 return &method, nil 219 } 220 } 221 return nil, fmt.Errorf("no method with id: %#x", sigdata[:4]) 222 } 223 224 // EventByID looks an event up by its topic hash in the 225 // ABI and returns nil if none found. 226 func (abi *ABI) EventByID(topic common.Hash) (*Event, error) { 227 for _, event := range abi.Events { 228 if bytes.Equal(event.ID.Bytes(), topic.Bytes()) { 229 return &event, nil 230 } 231 } 232 return nil, fmt.Errorf("no event with id: %#x", topic.Hex()) 233 } 234 235 // HasFallback returns an indicator whether a fallback function is included. 236 func (abi *ABI) HasFallback() bool { 237 return abi.Fallback.Type == Fallback 238 } 239 240 // HasReceive returns an indicator whether a receive function is included. 241 func (abi *ABI) HasReceive() bool { 242 return abi.Receive.Type == Receive 243 } 244 245 // revertSelector is a special function selector for revert reason unpacking. 246 var revertSelector = crypto.Keccak256([]byte("Error(string)"))[:4] 247 248 // UnpackRevert resolves the abi-encoded revert reason. According to the solidity 249 // spec https://solidity.readthedocs.io/en/latest/control-structures.html#revert, 250 // the provided revert reason is abi-encoded as if it were a call to a function 251 // `Error(string)`. So it's a special tool for it. 252 func UnpackRevert(data []byte) (string, error) { 253 if len(data) < 4 { 254 return "", errors.New("invalid data for unpacking") 255 } 256 if !bytes.Equal(data[:4], revertSelector) { 257 return "", errors.New("invalid data for unpacking") 258 } 259 typ, _ := NewType("string", "", nil) 260 unpacked, err := (Arguments{{Type: typ}}).Unpack(data[4:]) 261 if err != nil { 262 return "", err 263 } 264 return unpacked[0].(string), nil 265 }