forked from aviate-labs/agent-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
354 lines (325 loc) · 10.1 KB
/
agent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package agent
import (
"encoding/binary"
"encoding/hex"
"fmt"
"net/url"
"time"
"github.com/fxamacker/cbor/v2"
"github.com/mohaijiang/agent-go/candid"
"github.com/mohaijiang/agent-go/candid/idl"
"github.com/mohaijiang/agent-go/certificate"
"github.com/mohaijiang/agent-go/identity"
"github.com/mohaijiang/agent-go/principal"
)
// ic0 is the old (default) host for the Internet Computer.
// var ic0, _ = url.Parse("https://ic0.app/")
// icp0 is the default host for the Internet Computer.
var icp0, _ = url.Parse("https://icp0.io/")
func uint64FromBytes(raw []byte) uint64 {
switch len(raw) {
case 1:
return uint64(raw[0])
case 2:
return uint64(binary.BigEndian.Uint16(raw))
case 4:
return uint64(binary.BigEndian.Uint32(raw))
case 8:
return binary.BigEndian.Uint64(raw)
default:
panic(raw)
}
}
// Agent is a client for the Internet Computer.
type Agent struct {
client Client
identity identity.Identity
ingressExpiry time.Duration
rootKey []byte
}
// New returns a new Agent based on the given configuration.
func New(cfg Config) (*Agent, error) {
if cfg.IngressExpiry == 0 {
cfg.IngressExpiry = 10 * time.Second
}
// By default, use the anonymous identity.
var id identity.Identity = new(identity.AnonymousIdentity)
if cfg.Identity != nil {
id = cfg.Identity
}
ccfg := ClientConfig{
Host: icp0,
}
if cfg.ClientConfig != nil {
ccfg = *cfg.ClientConfig
}
client := NewClient(ccfg)
rootKey, _ := hex.DecodeString(certificate.RootKey)
if cfg.FetchRootKey {
status, err := client.Status()
if err != nil {
return nil, err
}
rootKey = status.RootKey
}
return &Agent{
client: client,
identity: id,
ingressExpiry: cfg.IngressExpiry,
rootKey: rootKey,
}, nil
}
// Call calls a method on a canister and unmarshals the result into the given values.
func (a Agent) Call(canisterID principal.Principal, methodName string, args []byte, values []any) error {
if len(args) == 0 {
// Default to the empty Candid argument list.
args = []byte{'D', 'I', 'D', 'L', 0, 0}
}
raw, err := a.CallRaw(canisterID, methodName, args)
if err != nil {
return err
}
return idl.Unmarshal(raw, values)
}
// CallCandid calls a method on a canister and returns the raw Candid result as a list of types and values.
func (a Agent) CallCandid(canisterID principal.Principal, methodName string, args []byte) ([]idl.Type, []interface{}, error) {
raw, err := a.CallRaw(canisterID, methodName, args)
if err != nil {
return nil, nil, err
}
return idl.Decode(raw)
}
// CallRaw calls a method on a canister and returns the raw Candid result.
func (a Agent) CallRaw(canisterID principal.Principal, methodName string, args []byte) ([]byte, error) {
requestID, data, err := a.sign(Request{
Type: RequestTypeCall,
Sender: a.Sender(),
CanisterID: canisterID,
MethodName: methodName,
Arguments: args,
IngressExpiry: a.expiryDate(),
})
if err != nil {
return nil, err
}
if _, err := a.call(canisterID, data); err != nil {
return nil, err
}
return a.poll(canisterID, *requestID, time.Second, time.Second*10)
}
// CallString calls a method on a canister and returns the result as a string.
func (a Agent) CallString(canisterID principal.Principal, methodName string, args []byte) (string, error) {
if len(args) == 0 {
args = []byte{'D', 'I', 'D', 'L', 0, 0}
}
types, values, err := a.CallCandid(canisterID, methodName, args)
if err != nil {
return "", err
}
return candid.DecodeValuesString(types, values)
}
// GetCanisterControllers returns the list of principals that can control the given canister.
func (a Agent) GetCanisterControllers(canisterID principal.Principal) ([]principal.Principal, error) {
resp, err := a.GetCanisterInfo(canisterID, "controllers")
if err != nil {
return nil, err
}
var m [][]byte
if err := cbor.Unmarshal(resp, &m); err != nil {
return nil, err
}
var p []principal.Principal
for _, b := range m {
p = append(p, principal.Principal{Raw: b})
}
return p, nil
}
// GetCanisterInfo returns the raw certificate for the given canister based on the given sub-path.
func (a Agent) GetCanisterInfo(canisterID principal.Principal, subPath string) ([]byte, error) {
path := [][]byte{[]byte("canister"), canisterID.Raw, []byte(subPath)}
c, err := a.readStateCertificate(canisterID, [][][]byte{path})
if err != nil {
return nil, err
}
var state map[string]any
if err := cbor.Unmarshal(c, &state); err != nil {
return nil, err
}
node, err := certificate.DeserializeNode(state["tree"].([]any))
if err != nil {
return nil, err
}
return certificate.Lookup(path, node), nil
}
// GetCanisterModuleHash returns the module hash for the given canister.
func (a Agent) GetCanisterModuleHash(canisterID principal.Principal) ([]byte, error) {
return a.GetCanisterInfo(canisterID, "module_hash")
}
// Query queries a method on a canister and unmarshals the result into the given values.
func (a Agent) Query(canisterID principal.Principal, methodName string, args []byte, values []any) error {
if len(args) == 0 {
args = []byte{'D', 'I', 'D', 'L', 0, 0}
}
raw, err := a.QueryRaw(canisterID, methodName, args)
if err != nil {
return err
}
return idl.Unmarshal(raw, values)
}
// QueryCandid queries a method on a canister and returns the raw Candid result as a list of types and values.
func (a Agent) QueryCandid(canisterID principal.Principal, methodName string, args []byte) ([]idl.Type, []interface{}, error) {
raw, err := a.QueryRaw(canisterID, methodName, args)
if err != nil {
return nil, nil, err
}
return idl.Decode(raw)
}
// QueryRaw queries a method on a canister and returns the raw Candid result.
func (a Agent) QueryRaw(canisterID principal.Principal, methodName string, args []byte) ([]byte, error) {
_, data, err := a.sign(Request{
Type: RequestTypeQuery,
Sender: a.Sender(),
CanisterID: canisterID,
MethodName: methodName,
Arguments: args,
IngressExpiry: a.expiryDate(),
})
if err != nil {
return nil, err
}
resp, err := a.query(canisterID, data)
if err != nil {
return nil, err
}
switch resp.Status {
case "replied":
return resp.Reply["arg"], nil
case "rejected":
return nil, fmt.Errorf("(%d) %s", resp.RejectCode, resp.RejectMsg)
default:
panic("unreachable")
}
}
// QueryString queries a method on a canister and returns the result as a string.
func (a Agent) QueryString(canisterID principal.Principal, methodName string, args []byte) (string, error) {
if len(args) == 0 {
args = []byte{'D', 'I', 'D', 'L', 0, 0}
}
types, values, err := a.QueryCandid(canisterID, methodName, args)
if err != nil {
return "", err
}
return candid.DecodeValuesString(types, values)
}
// RequestStatus returns the status of the request with the given ID.
func (a Agent) RequestStatus(canisterID principal.Principal, requestID RequestID) ([]byte, certificate.Node, error) {
path := [][]byte{[]byte("request_status"), requestID[:]}
c, err := a.readStateCertificate(canisterID, [][][]byte{path})
if err != nil {
return nil, nil, err
}
var state map[string]interface{}
if err := cbor.Unmarshal(c, &state); err != nil {
return nil, nil, err
}
cert, err := certificate.New(canisterID, a.rootKey[len(a.rootKey)-96:], c)
if err != nil {
return nil, nil, err
}
if err := cert.Verify(); err != nil {
return nil, nil, err
}
node, err := certificate.DeserializeNode(state["tree"].([]any))
if err != nil {
return nil, nil, err
}
return certificate.Lookup(append(path, []byte("status")), node), node, nil
}
// Sender returns the principal that is sending the requests.
func (a Agent) Sender() principal.Principal {
return a.identity.Sender()
}
func (a Agent) call(canisterID principal.Principal, data []byte) ([]byte, error) {
return a.client.call(canisterID, data)
}
func (a Agent) expiryDate() uint64 {
return uint64(time.Now().Add(a.ingressExpiry).UnixNano())
}
func (a Agent) poll(canisterID principal.Principal, requestID RequestID, delay, timeout time.Duration) ([]byte, error) {
ticker := time.NewTicker(delay)
timer := time.NewTimer(timeout)
for {
select {
case <-ticker.C:
data, node, err := a.RequestStatus(canisterID, requestID)
if err != nil {
return nil, err
}
if len(data) != 0 {
path := [][]byte{[]byte("request_status"), requestID[:]}
switch string(data) {
case "rejected":
code := certificate.Lookup(append(path, []byte("reject_code")), node)
rejectMessage := certificate.Lookup(append(path, []byte("reject_message")), node)
return nil, fmt.Errorf("(%d) %s", uint64FromBytes(code), string(rejectMessage))
case "replied":
path := [][]byte{[]byte("request_status"), requestID[:]}
return certificate.Lookup(append(path, []byte("reply")), node), nil
}
}
case <-timer.C:
return nil, fmt.Errorf("out of time... waited %d seconds", timeout/time.Second)
}
}
}
func (a Agent) query(canisterID principal.Principal, data []byte) (*Response, error) {
resp, err := a.client.query(canisterID, data)
if err != nil {
return nil, err
}
queryResponse := new(Response)
return queryResponse, cbor.Unmarshal(resp, queryResponse)
}
func (a Agent) readState(canisterID principal.Principal, data []byte) (map[string][]byte, error) {
resp, err := a.client.readState(canisterID, data)
if err != nil {
return nil, err
}
var m map[string][]byte
return m, cbor.Unmarshal(resp, &m)
}
func (a Agent) readStateCertificate(canisterID principal.Principal, paths [][][]byte) ([]byte, error) {
_, data, err := a.sign(Request{
Type: RequestTypeReadState,
Sender: a.Sender(),
Paths: paths,
IngressExpiry: a.expiryDate(),
})
if err != nil {
return nil, err
}
resp, err := a.readState(canisterID, data)
if err != nil {
return nil, err
}
return resp["certificate"], nil
}
func (a Agent) sign(request Request) (*RequestID, []byte, error) {
requestID := NewRequestID(request)
data, err := cbor.Marshal(Envelope{
Content: request,
SenderPubKey: a.identity.PublicKey(),
SenderSig: requestID.Sign(a.identity),
})
if err != nil {
return nil, nil, err
}
return &requestID, data, nil
}
// Config is the configuration for an Agent.
type Config struct {
Identity identity.Identity
IngressExpiry time.Duration
ClientConfig *ClientConfig
FetchRootKey bool
}