github.com/klaytn/klaytn@v1.12.1/accounts/abi/abi.go (about)

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