github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/accounts/abi/abi.go (about)

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