Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CCIP Read implementation #41

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
168 changes: 168 additions & 0 deletions ccip.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
package ens

import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"time"

"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rpc"
"github.com/wealdtech/go-ens/v3/contracts/offchainresolver"
"github.com/wealdtech/go-ens/v3/contracts/universalresolver"
)

func getCcipReadError(err error) (bool, string) {
var jsonErr, ok = err.(rpc.DataError)
if !ok {
return false, ""
}
errData, ok := jsonErr.ErrorData().(string)
if !ok {
return false, ""
}
return (len(errData) >= 10 && errData[:10] == offchainLookupSignature), errData
}

func ccipRead(backend bind.ContractBackend, resolverAddr common.Address, revertData string) ([]byte, error) {
hexBytes, err := hex.DecodeString(strings.TrimPrefix(revertData, "0x"))
if err != nil {
return nil, err
}
uAbi, err := universalresolver.ContractMetaData.GetAbi()
if err != nil {
return nil, err
}

if len(revertData) < 5 {
return nil, errors.New("invalid revert data")
}

// Extracting error details from the revert data
var sig [4]byte
copy(sig[:], hexBytes[:4])
pikonha marked this conversation as resolved.
Show resolved Hide resolved
abiErr, err := uAbi.ErrorByID(sig)
if err != nil {
return nil, err
}
errArgs, err := abiErr.Inputs.Unpack(hexBytes[4:])
pikonha marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}

sender := errArgs[0].(common.Address)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a lot of casting and array access here without checks, please add checks to avoid potential panics.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for the returned error to have the OffchainLookup signature (0x556f1830), it must have the following arguments:

  • sender
  • urls
  • calldata
  • callback
  • extraData

so I assume those variables will be on the errArgs variable and so they can be accessed directly by the index. otherwise, it would have failed on the (len(errData) >= 10 && errData[:10] == offchainLookupSignature) condition

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is easy for an error to be returned with the same four bytes but representing a different function (see 4byte.info for an example of clashes), and if done maliciously then it would cause a panic.

Copy link
Author

@pikonha pikonha Jul 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand the selector conflict and I did some testing to ensure it would break before an unexpected panic. in every scenario I've tested these conditions would return an error in case of an unexpected error since it wouldn't be present on the Universal Resolver's ABI

var sig [4]byte
copy(sig[:], hexBytes[:4])
abiErr, err := uAbi.ErrorByID(sig)
if err != nil {
  return nil, err
}
var errorData []byte
copy(errorData[:], hexBytes[4:])
errArgs, err := abiErr.Inputs.Unpack(errorData)
if err != nil {
  return nil, err
}

urls := errArgs[1].([]string)
calldata := common.Bytes2Hex(errArgs[2].([]byte))
calldataHex := fmt.Sprintf("0x%s", calldata)
callback := errArgs[3].([4]byte)
extraData := common.Bytes2Hex(errArgs[4].([]byte))
extraDataHex := fmt.Sprintf("0x%s", extraData)

// Fetching data from external source using CCIP
resp, err := ccipFetch(sender, calldataHex, urls)
if err != nil || len(resp) == 0 {
return nil, errors.New("unregistered name")
}

oAbi, err := offchainresolver.ContractMetaData.GetAbi()
if err != nil {
return nil, errors.New("no address")
}
m, err := oAbi.MethodById(callback[:])
if err != nil {
return nil, errors.New("no address")
}
args, err := m.Inputs.Pack(common.FromHex(resp), common.FromHex(extraDataHex))
if err != nil {
return nil, errors.New("no address")
}

encodedResp, err := backend.CallContract(context.Background(), ethereum.CallMsg{
To: &resolverAddr,
Data: append(callback[:], args...),
}, nil)

if err != nil {
return nil, err
}

outputs, err := m.Outputs.Unpack(encodedResp)
if err != nil || len(outputs) == 0 {
return nil, err
}
return outputs[0].([]byte), nil
}

func ccipFetch(sender common.Address, data string, urls []string) (result string, err error) {
for _, url := range urls {
method := "POST"
if strings.Contains(url, "{data}") {
method = "GET"
}

body := []byte{}
if method == "POST" {
body, err = json.Marshal(map[string]interface{}{
"data": data,
"sender": sender,
})
if err != nil {
return "", err
}
}

url = strings.ReplaceAll(url, "{sender}", sender.String())
url = strings.ReplaceAll(url, "{data}", data)
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")

client := &http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return "", err
}

defer resp.Body.Close()

var responseData map[string]interface{}
var result string
if strings.HasPrefix(resp.Header.Get("Content-Type"), "application/json") {
err = json.NewDecoder(resp.Body).Decode(&responseData)
if err != nil {
continue
}
var ok bool
result, ok = responseData["data"].(string)
if !ok {
continue
}
} else {
responseBytes, err := io.ReadAll(resp.Body)
if err != nil {
continue
}
result = string(responseBytes)
}

if resp.StatusCode != http.StatusOK {
continue
}

return result, nil
}

return "", err
}
50 changes: 50 additions & 0 deletions contracts/offchainresolver/contract.abi
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
[
{
"type": "function",
"name": "resolve",
"inputs": [
{
"name": "name",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "data",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "view"
},
{
"type": "function",
"name": "resolveWithProof",
"inputs": [
{
"name": "response",
"type": "bytes",
"internalType": "bytes"
},
{
"name": "extraData",
"type": "bytes",
"internalType": "bytes"
}
],
"outputs": [
{
"name": "",
"type": "bytes",
"internalType": "bytes"
}
],
"stateMutability": "view"
}
]
Loading