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