aviate-labs / agent-go

Golang Agent for the Internet Computer
Apache License 2.0
44 stars 14 forks source link

Segfault occurs when replica cannot be reached #12

Closed nmattia closed 8 months ago

nmattia commented 8 months ago

Expected Behavior

If the replica cannot be reached, I would expect a network error or a custom error, not a segfault

Actual Behavior

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10d105d59]

Steps to Reproduce the Problem

Adapt the README example to use a local replica, and make sure the replica is not running on that port:

package main

import (
    "github.com/aviate-labs/agent-go"
    "github.com/aviate-labs/agent-go/ic"
    "log"
    "net/url"
)

type (
    account struct {
        account string `ic:"account"`
    }

    balance struct {
        e8s uint64 `ic:"e8s"`
    }
)

func main() {
    u, _ := url.parse("http://localhost:4943")
    config := agent.config{
        clientconfig: &agent.clientconfig{host: u},
        fetchrootkey: true,
    }

    a, _ := agent.new(config)

    var balance balance
    if err := a.query(
        ic.ledger_principal, "account_balance_dfx",
        []any{account{"9523dc824aa062dcd9c91b98f4594ff9c6af661ac96747daef2090b7fe87037d"}},
        []any{&balance},
    ); err != nil {
        log.fatal(err)
    }

    // print(balance.e8s)
    _ = balance // balance{e8s: 0}
}

Specifications

q-uint commented 8 months ago

Hi @nmattia.

The main reason you are getting this is because you do not handle the following error:

a, err := agent.New(config)
if err != nil {
    log.Fatal(err)
}

This will return the following if it can not reach the replica:

Get "http://localhost:4943/api/v2/status": dial tcp [::1]:4943: connect: connection refused

The invalid memory address or nil pointer dereference is because the variable a (Agent) will be nil, since it returned an error.

nmattia commented 8 months ago

Completely missed this, thank you! Sorry for the noise.