github.com/p202io/bor@v0.1.4/accounts/abi/abi.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum 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 go-ethereum 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 go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package abi
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/json"
    22  	"fmt"
    23  	"io"
    24  
    25  	"github.com/maticnetwork/bor/common"
    26  )
    27  
    28  // The ABI holds information about a contract's context and available
    29  // invokable methods. It will allow you to type check function calls and
    30  // packs data accordingly.
    31  type ABI struct {
    32  	Constructor Method
    33  	Methods     map[string]Method
    34  	Events      map[string]Event
    35  }
    36  
    37  // JSON returns a parsed ABI interface and error if it failed.
    38  func JSON(reader io.Reader) (ABI, error) {
    39  	dec := json.NewDecoder(reader)
    40  
    41  	var abi ABI
    42  	if err := dec.Decode(&abi); err != nil {
    43  		return ABI{}, err
    44  	}
    45  
    46  	return abi, nil
    47  }
    48  
    49  // Pack the given method name to conform the ABI. Method call's data
    50  // will consist of method_id, args0, arg1, ... argN. Method id consists
    51  // of 4 bytes and arguments are all 32 bytes.
    52  // Method ids are created from the first 4 bytes of the hash of the
    53  // methods string signature. (signature = baz(uint32,string32))
    54  func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error) {
    55  	// Fetch the ABI of the requested method
    56  	if name == "" {
    57  		// constructor
    58  		arguments, err := abi.Constructor.Inputs.Pack(args...)
    59  		if err != nil {
    60  			return nil, err
    61  		}
    62  		return arguments, nil
    63  	}
    64  	method, exist := abi.Methods[name]
    65  	if !exist {
    66  		return nil, fmt.Errorf("method '%s' not found", name)
    67  	}
    68  	arguments, err := method.Inputs.Pack(args...)
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  	// Pack up the method ID too if not a constructor and return
    73  	return append(method.Id(), arguments...), nil
    74  }
    75  
    76  // Unpack output in v according to the abi specification
    77  func (abi ABI) Unpack(v interface{}, name string, data []byte) (err error) {
    78  	if len(data) == 0 {
    79  		return fmt.Errorf("abi: unmarshalling empty output")
    80  	}
    81  	// since there can't be naming collisions with contracts and events,
    82  	// we need to decide whether we're calling a method or an event
    83  	if method, ok := abi.Methods[name]; ok {
    84  		if len(data)%32 != 0 {
    85  			return fmt.Errorf("abi: improperly formatted output: %s - Bytes: [%+v]", string(data), data)
    86  		}
    87  		return method.Outputs.Unpack(v, data)
    88  	}
    89  	if event, ok := abi.Events[name]; ok {
    90  		return event.Inputs.Unpack(v, data)
    91  	}
    92  	return fmt.Errorf("abi: could not locate named method or event")
    93  }
    94  
    95  // UnpackIntoMap unpacks a log into the provided map[string]interface{}
    96  func (abi ABI) UnpackIntoMap(v map[string]interface{}, name string, data []byte) (err error) {
    97  	if len(data) == 0 {
    98  		return fmt.Errorf("abi: unmarshalling empty output")
    99  	}
   100  	// since there can't be naming collisions with contracts and events,
   101  	// we need to decide whether we're calling a method or an event
   102  	if method, ok := abi.Methods[name]; ok {
   103  		if len(data)%32 != 0 {
   104  			return fmt.Errorf("abi: improperly formatted output")
   105  		}
   106  		return method.Outputs.UnpackIntoMap(v, data)
   107  	}
   108  	if event, ok := abi.Events[name]; ok {
   109  		return event.Inputs.UnpackIntoMap(v, data)
   110  	}
   111  	return fmt.Errorf("abi: could not locate named method or event")
   112  }
   113  
   114  // UnmarshalJSON implements json.Unmarshaler interface
   115  func (abi *ABI) UnmarshalJSON(data []byte) error {
   116  	var fields []struct {
   117  		Type      string
   118  		Name      string
   119  		Constant  bool
   120  		Anonymous bool
   121  		Inputs    []Argument
   122  		Outputs   []Argument
   123  	}
   124  
   125  	if err := json.Unmarshal(data, &fields); err != nil {
   126  		return err
   127  	}
   128  
   129  	abi.Methods = make(map[string]Method)
   130  	abi.Events = make(map[string]Event)
   131  	for _, field := range fields {
   132  		switch field.Type {
   133  		case "constructor":
   134  			abi.Constructor = Method{
   135  				Inputs: field.Inputs,
   136  			}
   137  		// empty defaults to function according to the abi spec
   138  		case "function", "":
   139  			name := field.Name
   140  			_, ok := abi.Methods[name]
   141  			for idx := 0; ok; idx++ {
   142  				name = fmt.Sprintf("%s%d", field.Name, idx)
   143  				_, ok = abi.Methods[name]
   144  			}
   145  			abi.Methods[name] = Method{
   146  				Name:    name,
   147  				Const:   field.Constant,
   148  				Inputs:  field.Inputs,
   149  				Outputs: field.Outputs,
   150  			}
   151  		case "event":
   152  			name := field.Name
   153  			_, ok := abi.Events[name]
   154  			for idx := 0; ok; idx++ {
   155  				name = fmt.Sprintf("%s%d", field.Name, idx)
   156  				_, ok = abi.Events[name]
   157  			}
   158  			abi.Events[name] = Event{
   159  				Name:      name,
   160  				Anonymous: field.Anonymous,
   161  				Inputs:    field.Inputs,
   162  			}
   163  		}
   164  	}
   165  
   166  	return nil
   167  }
   168  
   169  // MethodById looks up a method by the 4-byte id
   170  // returns nil if none found
   171  func (abi *ABI) MethodById(sigdata []byte) (*Method, error) {
   172  	if len(sigdata) < 4 {
   173  		return nil, fmt.Errorf("data too short (%d bytes) for abi method lookup", len(sigdata))
   174  	}
   175  	for _, method := range abi.Methods {
   176  		if bytes.Equal(method.Id(), sigdata[:4]) {
   177  			return &method, nil
   178  		}
   179  	}
   180  	return nil, fmt.Errorf("no method with id: %#x", sigdata[:4])
   181  }
   182  
   183  // EventByID looks an event up by its topic hash in the
   184  // ABI and returns nil if none found.
   185  func (abi *ABI) EventByID(topic common.Hash) (*Event, error) {
   186  	for _, event := range abi.Events {
   187  		if bytes.Equal(event.Id().Bytes(), topic.Bytes()) {
   188  			return &event, nil
   189  		}
   190  	}
   191  	return nil, fmt.Errorf("no event with id: %#x", topic.Hex())
   192  }