Files
ucan/token/read.go

84 lines
2.3 KiB
Go
Raw Normal View History

2024-10-01 17:02:49 +02:00
package token
2024-10-01 13:23:37 +02:00
import (
"fmt"
"io"
2024-10-01 13:23:37 +02:00
"github.com/ipld/go-ipld-prime"
"github.com/ipld/go-ipld-prime/codec"
2024-10-01 13:23:37 +02:00
"github.com/ipld/go-ipld-prime/codec/dagcbor"
"github.com/ipld/go-ipld-prime/codec/dagjson"
"github.com/ipld/go-ipld-prime/datamodel"
2024-10-01 13:23:37 +02:00
2024-10-01 17:02:49 +02:00
"github.com/ucan-wg/go-ucan/token/delegation"
"github.com/ucan-wg/go-ucan/token/internal/envelope"
2024-10-02 10:53:30 +02:00
"github.com/ucan-wg/go-ucan/token/invocation"
2024-10-01 13:23:37 +02:00
)
// Decode unmarshals the input data using the format specified by the
// provided codec.Decoder into an arbitrary UCAN token.
// An error is returned if the conversion fails, or if the resulting
// Token is invalid.
// Supported and returned types are:
// - delegation.Token
2024-10-01 17:02:49 +02:00
func Decode(b []byte, decFn codec.Decoder) (Token, error) {
node, err := ipld.Decode(b, decFn)
if err != nil {
return nil, err
}
return fromIPLD(node)
}
// DecodeReader is the same as Decode, but accept an io.Reader.
2024-10-01 17:02:49 +02:00
func DecodeReader(r io.Reader, decFn codec.Decoder) (Token, error) {
node, err := ipld.DecodeStreaming(r, decFn)
2024-10-01 13:23:37 +02:00
if err != nil {
return nil, err
}
return fromIPLD(node)
}
// FromDagCbor unmarshals an arbitrary DagCbor encoded UCAN token.
// An error is returned if the conversion fails, or if the resulting
// Token is invalid.
// Supported and returned types are:
// - delegation.Token
2024-10-01 17:02:49 +02:00
func FromDagCbor(b []byte) (Token, error) {
return Decode(b, dagcbor.Decode)
}
// FromDagCborReader is the same as FromDagCbor, but accept an io.Reader.
2024-10-01 17:02:49 +02:00
func FromDagCborReader(r io.Reader) (Token, error) {
return DecodeReader(r, dagcbor.Decode)
}
// FromDagCbor unmarshals an arbitrary DagJson encoded UCAN token.
// An error is returned if the conversion fails, or if the resulting
// Token is invalid.
// Supported and returned types are:
// - delegation.Token
2024-10-01 17:02:49 +02:00
func FromDagJson(b []byte) (Token, error) {
return Decode(b, dagjson.Decode)
}
// FromDagJsonReader is the same as FromDagJson, but accept an io.Reader.
2024-10-01 17:02:49 +02:00
func FromDagJsonReader(r io.Reader) (Token, error) {
return DecodeReader(r, dagjson.Decode)
}
2024-10-01 13:23:37 +02:00
2024-10-01 17:02:49 +02:00
func fromIPLD(node datamodel.Node) (Token, error) {
2024-10-01 13:23:37 +02:00
tag, err := envelope.FindTag(node)
if err != nil {
return nil, err
}
switch tag {
case delegation.Tag:
return delegation.FromIPLD(node)
2024-10-02 10:53:30 +02:00
case invocation.Tag:
return invocation.FromIPLD(node)
2024-10-01 13:23:37 +02:00
default:
return nil, fmt.Errorf(`unknown tag "%s"`, tag)
}
}