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