-
Notifications
You must be signed in to change notification settings - Fork 14
/
agent.go
517 lines (481 loc) · 14.7 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
package agent
import (
"context"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net/url"
"reflect"
"time"
"github.com/aviate-labs/agent-go/candid/idl"
"github.com/aviate-labs/agent-go/certification"
"github.com/aviate-labs/agent-go/certification/hashtree"
"github.com/aviate-labs/agent-go/identity"
"github.com/aviate-labs/agent-go/principal"
"github.com/fxamacker/cbor/v2"
"google.golang.org/protobuf/proto"
)
// DefaultConfig is the default configuration for an Agent.
var DefaultConfig = Config{}
// 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 effectiveCanisterID(canisterID principal.Principal, args []any) principal.Principal {
// If the canisterID is not aaaaa-aa (encoded as empty byte array), return it.
if 0 < len(canisterID.Raw) || len(args) < 1 {
return canisterID
}
v := reflect.ValueOf(args[0])
switch v.Kind() {
case reflect.Map:
if ecid, ok := args[0].(map[string]any)["canister_id"]; ok {
switch ecidp := ecid.(type) {
case principal.Principal:
return ecidp
default:
// If the field is not a principal, return the original canisterId.
return canisterID
}
}
return canisterID
case reflect.Struct:
t := v.Type()
// Get the field with the ic tag "canister_id".
for idx := range t.NumField() {
if tag := t.Field(idx).Tag.Get("ic"); tag == "canister_id" {
ecid := v.Field(idx).Interface()
switch ecidp := ecid.(type) {
case principal.Principal:
return ecidp
default:
// If the field is not a principal, return the original canisterId.
return canisterID
}
}
}
return canisterID
default:
return canisterID
}
}
func newNonce() ([]byte, error) {
/* Read 10 bytes of random data, which is smaller than the max allowed by the IC (32 bytes)
* and should still be enough from a practical point of view. */
nonce := make([]byte, 10)
_, err := rand.Read(nonce)
return nonce, err
}
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)
}
}
type APIRequest[In, Out any] struct {
a *Agent
unmarshal func([]byte, Out) error
typ RequestType
methodName string
effectiveCanisterID principal.Principal
requestID RequestID
data []byte
}
func createAPIRequest[In, Out any](
a *Agent,
marshal func(In) ([]byte, error),
unmarshal func([]byte, Out) error,
typ RequestType,
canisterID principal.Principal,
effectiveCanisterID principal.Principal,
methodName string,
in In,
) (*APIRequest[In, Out], error) {
rawArgs, err := marshal(in)
if err != nil {
return nil, err
}
nonce, err := newNonce()
if err != nil {
return nil, err
}
requestID, data, err := a.sign(Request{
Type: typ,
Sender: a.Sender(),
CanisterID: canisterID,
MethodName: methodName,
Arguments: rawArgs,
IngressExpiry: a.expiryDate(),
Nonce: nonce,
})
if err != nil {
return nil, err
}
return &APIRequest[In, Out]{
a: a,
unmarshal: unmarshal,
typ: typ,
methodName: methodName,
effectiveCanisterID: effectiveCanisterID,
requestID: *requestID,
data: data,
}, nil
}
// WithEffectiveCanisterID sets the effective canister ID for the Call.
func (c *APIRequest[In, Out]) WithEffectiveCanisterID(canisterID principal.Principal) *APIRequest[In, Out] {
c.effectiveCanisterID = canisterID
return c
}
// Agent is a client for the Internet Computer.
type Agent struct {
client Client
ctx context.Context
identity identity.Identity
ingressExpiry time.Duration
rootKey []byte
logger Logger
delay, timeout time.Duration
verifySignatures bool
}
// New returns a new Agent based on the given configuration.
func New(cfg Config) (*Agent, error) {
if cfg.IngressExpiry == 0 {
cfg.IngressExpiry = 5 * time.Minute
}
// By default, use the anonymous identity.
var id identity.Identity = new(identity.AnonymousIdentity)
if cfg.Identity != nil {
id = cfg.Identity
}
var logger Logger = new(NoopLogger)
if cfg.Logger != nil {
logger = cfg.Logger
}
ccfg := ClientConfig{
Host: icp0,
}
if cfg.ClientConfig != nil {
ccfg = *cfg.ClientConfig
}
client := NewClientWithLogger(ccfg, logger)
rootKey, _ := hex.DecodeString(certification.RootKey)
if cfg.FetchRootKey {
status, err := client.Status()
if err != nil {
return nil, err
}
rootKey = status.RootKey
}
delay := time.Second
if cfg.PollDelay != 0 {
delay = cfg.PollDelay
}
timeout := 10 * time.Second
if cfg.PollTimeout != 0 {
timeout = cfg.PollTimeout
}
return &Agent{
client: client,
ctx: context.Background(),
identity: id,
ingressExpiry: cfg.IngressExpiry,
rootKey: rootKey,
logger: logger,
delay: delay,
timeout: timeout,
verifySignatures: !cfg.DisableSignedQueryVerification,
}, nil
}
// Client returns the underlying Client of the Agent.
func (a Agent) Client() *Client {
return &a.client
}
// CreateCandidAPIRequest creates a new api request to the given canister and method.
func (a *Agent) CreateCandidAPIRequest(typ RequestType, canisterID principal.Principal, methodName string, args ...any) (*CandidAPIRequest, error) {
return createAPIRequest[[]any, []any](
a,
idl.Marshal,
idl.Unmarshal,
typ,
canisterID,
effectiveCanisterID(canisterID, args),
methodName,
args,
)
}
// CreateProtoAPIRequest creates a new api request to the given canister and method.
func (a *Agent) CreateProtoAPIRequest(typ RequestType, canisterID principal.Principal, methodName string, message proto.Message) (*ProtoAPIRequest, error) {
return createAPIRequest[proto.Message, proto.Message](
a,
func(m proto.Message) ([]byte, error) {
raw, err := proto.Marshal(m)
if err != nil {
return nil, err
}
if len(raw) == 0 {
// Protobuf arg are not allowed to be empty.
return []byte{}, nil
}
return raw, nil
},
proto.Unmarshal,
typ,
canisterID,
canisterID,
methodName,
message,
)
}
// 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 := []hashtree.Label{hashtree.Label("canister"), canisterID.Raw, hashtree.Label(subPath)}
node, err := a.ReadStateCertificate(canisterID, [][]hashtree.Label{path})
if err != nil {
return nil, err
}
canisterInfo, err := hashtree.Lookup(node, path...)
if err != nil {
return nil, err
}
return canisterInfo, nil
}
func (a Agent) GetCanisterMetadata(canisterID principal.Principal, subPath string) ([]byte, error) {
path := []hashtree.Label{hashtree.Label("canister"), canisterID.Raw, hashtree.Label("metadata"), hashtree.Label(subPath)}
c, err := a.readStateCertificate(canisterID, [][]hashtree.Label{path})
if err != nil {
return nil, err
}
metadata, err := c.Tree.Lookup(path...)
if err != nil {
return nil, err
}
return metadata, nil
}
// GetCanisterModuleHash returns the module hash for the given canister.
func (a Agent) GetCanisterModuleHash(canisterID principal.Principal) ([]byte, error) {
h, err := a.GetCanisterInfo(canisterID, "module_hash")
var lookupError hashtree.LookupError
if errors.As(err, &lookupError) && lookupError.Type == hashtree.LookupResultAbsent {
// If the canister is empty, it is expected that the module hash is not available.
return nil, nil
}
return h, err
}
// GetRootKey returns the root key of the host.
func (a Agent) GetRootKey() []byte {
return a.rootKey
}
// ReadStateCertificate reads the certificate state of the given canister at the given path.
func (a Agent) ReadStateCertificate(canisterID principal.Principal, path [][]hashtree.Label) (hashtree.Node, error) {
c, err := a.readStateCertificate(canisterID, path)
if err != nil {
return nil, err
}
return c.Tree.Root, nil
}
// RequestStatus returns the status of the request with the given ID.
func (a Agent) RequestStatus(ecID principal.Principal, requestID RequestID) ([]byte, hashtree.Node, error) {
a.logger.Printf("[AGENT] REQUEST STATUS %s %x", ecID, requestID)
path := []hashtree.Label{hashtree.Label("request_status"), requestID[:]}
certificate, err := a.readStateCertificate(ecID, [][]hashtree.Label{path})
if err != nil {
return nil, nil, err
}
if err := certification.VerifyCertificate(*certificate, ecID, a.rootKey); err != nil {
return nil, nil, err
}
status, err := certificate.Tree.Lookup(append(path, hashtree.Label("status"))...)
var lookupError hashtree.LookupError
if errors.As(err, &lookupError) && lookupError.Type == hashtree.LookupResultAbsent {
// The status might not be available immediately, since the request is still being processed.
return nil, nil, nil
}
if err != nil {
return nil, nil, err
}
return status, certificate.Tree.Root, nil
}
// Sender returns the principal that is sending the requests.
func (a Agent) Sender() principal.Principal {
return a.identity.Sender()
}
func (a Agent) call(ecID principal.Principal, data []byte) ([]byte, error) {
ctx, cancel := context.WithTimeout(a.ctx, a.ingressExpiry)
defer cancel()
return a.client.Call(ctx, ecID, data)
}
func (a Agent) expiryDate() uint64 {
return uint64(time.Now().Add(a.ingressExpiry).UnixNano())
}
func (a Agent) poll(ecID principal.Principal, requestID RequestID) ([]byte, error) {
ticker := time.NewTicker(a.delay)
timer := time.NewTimer(a.timeout)
for {
select {
case <-ticker.C:
a.logger.Printf("[AGENT] POLL %s %x", ecID, requestID)
data, node, err := a.RequestStatus(ecID, requestID)
if err != nil {
return nil, err
}
if len(data) != 0 {
path := []hashtree.Label{hashtree.Label("request_status"), requestID[:]}
switch string(data) {
case "rejected":
tree := hashtree.NewHashTree(node)
code, err := tree.Lookup(append(path, hashtree.Label("reject_code"))...)
if err != nil {
return nil, err
}
message, err := tree.Lookup(append(path, hashtree.Label("reject_message"))...)
if err != nil {
return nil, err
}
return nil, fmt.Errorf("(%d) %s", uint64FromBytes(code), string(message))
case "replied":
replied, err := hashtree.Lookup(node, append(path, hashtree.Label("reply"))...)
if err != nil {
return nil, fmt.Errorf("no reply found")
}
return replied, nil
}
}
case <-timer.C:
return nil, fmt.Errorf("out of time... waited %d seconds", a.timeout/time.Second)
}
}
}
func (a Agent) readState(ecID principal.Principal, data []byte) (map[string][]byte, error) {
ctx, cancel := context.WithTimeout(a.ctx, a.ingressExpiry)
defer cancel()
resp, err := a.client.ReadState(ctx, ecID, data)
if err != nil {
return nil, err
}
var m map[string][]byte
return m, cbor.Unmarshal(resp, &m)
}
func (a Agent) readStateCertificate(ecID principal.Principal, paths [][]hashtree.Label) (*certification.Certificate, error) {
_, data, err := a.sign(Request{
Type: RequestTypeReadState,
Sender: a.Sender(),
Paths: paths,
IngressExpiry: a.expiryDate(),
})
if err != nil {
return nil, err
}
a.logger.Printf("[AGENT] READ STATE %s (ecID)", ecID)
resp, err := a.readState(ecID, data)
if err != nil {
return nil, err
}
var certificate certification.Certificate
if err := cbor.Unmarshal(resp["certificate"], &certificate); err != nil {
return nil, err
}
if err := certificate.VerifyTime(a.ingressExpiry); err != nil {
return nil, err
}
if err := certification.VerifyCertificate(certificate, ecID, a.rootKey); err != nil {
return nil, err
}
return &certificate, nil
}
func (a Agent) readSubnetState(subnetID principal.Principal, data []byte) (map[string][]byte, error) {
ctx, cancel := context.WithTimeout(a.ctx, a.ingressExpiry)
defer cancel()
resp, err := a.client.ReadSubnetState(ctx, subnetID, data)
if err != nil {
return nil, err
}
var m map[string][]byte
return m, cbor.Unmarshal(resp, &m)
}
func (a Agent) readSubnetStateCertificate(subnetID principal.Principal, paths [][]hashtree.Label) (*certification.Certificate, error) {
_, data, err := a.sign(Request{
Type: RequestTypeReadState,
Sender: a.Sender(),
Paths: paths,
IngressExpiry: a.expiryDate(),
})
if err != nil {
return nil, err
}
a.logger.Printf("[AGENT] READ SUBNET STATE %s (subnetID)", subnetID)
resp, err := a.readSubnetState(subnetID, data)
if err != nil {
return nil, err
}
var certificate certification.Certificate
if err := cbor.Unmarshal(resp["certificate"], &certificate); err != nil {
return nil, err
}
if err := certificate.VerifyTime(a.ingressExpiry); err != nil {
return nil, err
}
if err := certification.VerifySubnetCertificate(certificate, subnetID, a.rootKey); err != nil {
return nil, err
}
return &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
}
type CandidAPIRequest = APIRequest[[]any, []any]
// Config is the configuration for an Agent.
type Config struct {
// Identity is the identity used by the Agent.
Identity identity.Identity
// IngressExpiry is the duration for which an ingress message is valid.
// The default is set to 5 minutes.
IngressExpiry time.Duration
// ClientConfig is the configuration for the underlying Client.
ClientConfig *ClientConfig
// FetchRootKey determines whether the root key should be fetched from the IC.
FetchRootKey bool
// Logger is the logger used by the Agent.
Logger Logger
// PollDelay is the delay between polling for a response.
PollDelay time.Duration
// PollTimeout is the timeout for polling for a response.
PollTimeout time.Duration
// DisableSignedQueryVerification disables the verification of signed queries.
DisableSignedQueryVerification bool
}
type ProtoAPIRequest = APIRequest[proto.Message, proto.Message]