Didexchange с использованием InboundTransport для запуска 2 агентов на локальном хосте с использованием aries-framework-go

Я новичок в aries, и я запускаю пример кода, но мне не удалось установить соединение с использованием протокола didexchange.

Я создаю две службы с помощью go: одна работает на порте 5000, а другая - на 5005.

Вот мой код:

      func main() {
    client, _ := services.NewDidClient(port)

    http.Handle("/invitation", &handlers.InvitationHandler{DidClient: *client})
    http.Handle("/connection", &handlers.ConnectionHandler{DidClient: *client})
    http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}

type DidClient struct {
    didexchange.Client
}
func NewDidClient(port int32) (*DidClient, error) {
    framework, _ := aries.New(
        // aries.WithInboundTransport(newInboundTransport(port)),
        aries.WithStoreProvider(mem.NewProvider()),
        aries.WithProtocolStateStoreProvider(mem.NewProvider()),
    )
    ctx, _ := framework.Context()
    didExchangeClient, _ := didexchange.New(ctx)
    actions := make(chan service.DIDCommAction, 1)
    didExchangeClient.RegisterActionEvent(actions)
    go func() {
        service.AutoExecuteActionEvent(actions)
    }()
    return &DidClient{Client: *didExchangeClient}, nil
}

type InvitationHandler struct {
    DidClient services.DidClient
}
func (handler *InvitationHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
    switch request.Method {
    case http.MethodGet:
        invitation, _ := handler.DidClient.CreateInvitation("5000 invitation")  
        response, _ := json.Marshal(invitation)     
        writer.Header().Set("Content-Type", "application/json")
        writer.Write(response)
    }
}

type ConnectionHandler struct {
    DidClient services.DidClient
}
func (handler *ConnectionHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
    switch request.Method {
    case http.MethodGet:
        connections, _ := handler.DidClient.QueryConnections(&didexchange.QueryConnectionsParams{})
        response, _ := json.Marshal(connections)
        writer.Header().Set("Content-Type", "application/json")
        writer.Write(response)

    case http.MethodPost:
        var invitation didexchange.Invitation
        bodyBytes, _ := ioutil.ReadAll(request.Body)
        json.Unmarshal(bodyBytes, &invitation)  
        connectionID, _ := handler.DidClient.HandleInvitation(&invitation)
        connection, _ := handler.DidClient.GetConnection(connectionID)
        response, _ := json.Marshal(connection)
        writer.Header().Set("Content-Type", "application/json")
        writer.Write(response)
    }
}

type inboundTransport struct {
    port int32
}

func newInboundTransport(port int32) *inboundTransport {
    return &inboundTransport{port: port + 1}
}

func (transport *inboundTransport) Start(prov transport.Provider) error {
    return nil
}

func (transport *inboundTransport) Stop() error {
    return nil
}

func (transport *inboundTransport) Endpoint() string {
    return fmt.Sprintf("http://localhost:%d", transport.port) 
}

Я опускаю здесь обработку ошибок, но она есть в моем коде.

Итак, при работе без входящего транспорта они оба говорят, что конечная точка службы - это: didcomm: transport / queue

Я создаю приглашение с помощью обработчика приглашения на порту 5000, например:

      curl --request GET --url http://localhost:5000/invitation
response: 
{
  "serviceEndpoint": "didcomm:transport/queue",
  "recipientKeys": [
    "did:key:z6MkojtSLJ4EtwAUJZsy7BDhhDDnNtfvwu3AH7di6o5XzaFz"
  ],
  "@id": "ac56543b-526b-47e6-887a-0ee4a8fd888e",
  "label": "5000 invitation",
  "@type": "https://didcomm.org/didexchange/1.0/invitation"
}

передайте его агенту в порт 5005, используя post в обработчике соединения следующим образом:

      curl --request POST \
  --url http://localhost:5005/connection \
  --header 'Content-Type: application/json' \
  --data '{
  "serviceEndpoint": "didcomm:transport/queue",
  "recipientKeys": [
    "did:key:z6MkojtSLJ4EtwAUJZsy7BDhhDDnNtfvwu3AH7di6o5XzaFz"
  ],
  "@id": "ac56543b-526b-47e6-887a-0ee4a8fd888e",
  "label": "5000 invitation",
  "@type": "https://didcomm.org/didexchange/1.0/invitation"
}'
response:
{
  "ConnectionID": "808939bc-0e88-41cb-971b-e00e3aa2a631",
  "State": "null",
  "ThreadID": "3db73089-025d-4e6f-9703-d86881745494",
  "ParentThreadID": "",
  "TheirLabel": "5000 invitation",
  "TheirDID": "",
  "MyDID": "",
  "ServiceEndPoint": "didcomm:transport/queue",
  "RecipientKeys": [
    "did:key:z6Mknaw7ANj5yqDrsFhkWgfdYM8XbGNKLLexhBmD1XoUKAAo"
  ],
  "RoutingKeys": null,
  "InvitationID": "3db73089-025d-4e6f-9703-d86881745494",
  "InvitationDID": "",
  "Implicit": false,
  "Namespace": "my"
}

И я ожидал получить соединение в обоих агентах, запускающих соединение get, но соединение есть только у агента 5005, например:

      curl --request GET --url http://localhost:5000/connection
response: nil

curl --request GET --url http://localhost:5005/connection
response:
[{
  "ConnectionID": "808939bc-0e88-41cb-971b-e00e3aa2a631",
  "State": "abandoned",
  "ThreadID": "3db73089-025d-4e6f-9703-d86881745494",
  "ParentThreadID": "",
  "TheirLabel": "5000 invitation",
  "TheirDID": "",
  "MyDID": "did:peer:1zQmPBE2GKCCWTXoSA2EzUVbLGs3njJtqDmnN5LLP9UQpWLJ",
  "ServiceEndPoint": "didcomm:transport/queue",
  "RecipientKeys": [
    "did:key:z6Mknaw7ANj5yqDrsFhkWgfdYM8XbGNKLLexhBmD1XoUKAAo"
  ],
  "RoutingKeys": null,
  "InvitationID": "3db73089-025d-4e6f-9703-d86881745494",
  "InvitationDID": "",
  "Implicit": false,
  "Namespace": "my"
}]

Но я получаю эти ошибки на консоли:

      [aries-framework/out-of-band/service] 2021/08/26 02:11:15 UTC - n/a -> ERROR command=[out-of-band] action=handleDIDEvent] [] errMsg=[ignored]

Соединение в агенте 5005 говорит, что оно заброшено, и я думаю, что проблема в том, что обе платформы должны иметь возможность подключаться друг к другу без моего вмешательства, но они не могут видеть друг друга, поэтому я добавил InboundTransport к каждому, используя http: // localhost с порты 5001 и 5006, но потом я получил следующие ошибки:

      [aries-framework/out-of-band/service] 2021/08/26 02:20:41 UTC - n/a -> ERROR command=[out-of-band] action[handleDIDEvent] [] errMsg=[ignored]
[aries-framework/http] 2021/08/26 02:20:44 UTC - http.(*OutboundHTTPClient).Send -> ERROR posting DID envelope to agent failed [http://localhost:5001, Post "http://localhost:5001": dial tcp [::1]:5001: connectex: No connection could be made because the target machine actively refused it.]
[aries-framework/out-of-band/service] 2021/08/26 02:20:44 UTC - n/a -> ERROR command=[out-of-band] action [handleDIDEvent] [] errMsg=[ignored]

Итак, я немного растерялся, я прочитал, что агенты должны работать только с new () (с батареями), но я не уверен, что запуск обоих агентов на моем локальном хосте приводит к их конфликту, и как "didcomm" : transport / queue "работает?" Я понимаю, что фреймворк не использует rest и его внедряют с go, но тогда как он раскрывает свои конечные точки? что мне не хватает?

Спасибо

1 ответ

Я разместил вопрос как с проблемуgithub, и с помощью ссылок, которые они опубликовали, я изменил свой код и получил входящую работу.

Вот изменения:

      func NewDidClient(port int32) (*DidClient, error) {

    address := fmt.Sprintf("localhost:%d", port + 1)
    inbound, err := ws.NewInbound(address, "ws://" + address, "", "")

    framework, _ := aries.New(
        aries.WithInboundTransport(inbound),
        aries.WithOutboundTransports(ws.NewOutbound()),
        aries.WithStoreProvider(mem.NewProvider()),
        aries.WithProtocolStateStoreProvider(mem.NewProvider()),
    )
    ctx, _ := framework.Context()
    didExchangeClient, _ := didexchange.New(ctx)
    actions := make(chan service.DIDCommAction, 1)
    didExchangeClient.RegisterActionEvent(actions)
    go func() {
        service.AutoExecuteActionEvent(actions)
    }()
    return &DidClient{Client: *didExchangeClient}, nil
}

Он использует веб-сокеты, и теперь оба агента могут подключаться друг к другу.

Другие вопросы по тегам