feat: support for non did:key

This commit is contained in:
Alan Shaw
2023-09-19 22:52:23 +01:00
parent 23c2b1f459
commit 78838e4518
2 changed files with 42 additions and 3 deletions

15
did.go
View File

@@ -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
}

View File

@@ -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