feat: support for non did:key
This commit is contained in:
15
did.go
15
did.go
@@ -11,9 +11,13 @@ import (
|
||||
const Prefix = "did:"
|
||||
const KeyPrefix = "did:key:"
|
||||
|
||||
const DIDCore = 0x0d1d
|
||||
const Ed25519 = 0xed
|
||||
|
||||
var MethodOffset = varint.UvarintSize(uint64(DIDCore))
|
||||
|
||||
type DID struct {
|
||||
key bool
|
||||
str string
|
||||
}
|
||||
|
||||
@@ -37,9 +41,12 @@ func (d DID) DID() DID {
|
||||
}
|
||||
|
||||
func (d DID) String() string {
|
||||
if d.key {
|
||||
key, _ := mbase.Encode(mbase.Base58BTC, []byte(d.str))
|
||||
return "did:key:" + key
|
||||
}
|
||||
return "did:" + d.str[MethodOffset:]
|
||||
}
|
||||
|
||||
func Decode(bytes []byte) (DID, error) {
|
||||
code, _, err := varint.FromUvarint(bytes)
|
||||
@@ -47,6 +54,8 @@ func Decode(bytes []byte) (DID, error) {
|
||||
return Undef, err
|
||||
}
|
||||
if code == Ed25519 {
|
||||
return DID{str: string(bytes), key: true}, nil
|
||||
} else if code == DIDCore {
|
||||
return DID{str: string(bytes)}, nil
|
||||
}
|
||||
return Undef, fmt.Errorf("decoding DID: unsupported DID encoding: 0x%x", code)
|
||||
@@ -68,5 +77,9 @@ func Parse(str string) (DID, error) {
|
||||
return Decode(bytes)
|
||||
}
|
||||
|
||||
return Undef, fmt.Errorf("parsing DID: unsupported method")
|
||||
buf := make([]byte, MethodOffset)
|
||||
varint.PutUvarint(buf, DIDCore)
|
||||
suffix, _ := strings.CutPrefix(str, Prefix)
|
||||
buf = append(buf, suffix...)
|
||||
return DID{str: string(buf)}, nil
|
||||
}
|
||||
|
||||
26
did_test.go
26
did_test.go
@@ -30,6 +30,32 @@ func TestDecodeDIDKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseDIDWeb(t *testing.T) {
|
||||
str := "did:web:up.web3.storage"
|
||||
d, err := Parse(str)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if d.String() != str {
|
||||
t.Fatalf("expected %v to equal %v", d.String(), str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeDIDWeb(t *testing.T) {
|
||||
str := "did:web:up.web3.storage"
|
||||
d0, err := Parse(str)
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
d1, err := Decode(d0.Bytes())
|
||||
if err != nil {
|
||||
t.Fatalf("%v", err)
|
||||
}
|
||||
if d1.String() != str {
|
||||
t.Fatalf("expected %v to equal %v", d1.String(), str)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEquivalence(t *testing.T) {
|
||||
u0 := DID{}
|
||||
u1 := Undef
|
||||
|
||||
Reference in New Issue
Block a user