From 78838e451827203860d4eabc91ee90d2354e42b9 Mon Sep 17 00:00:00 2001 From: Alan Shaw Date: Tue, 19 Sep 2023 22:52:23 +0100 Subject: [PATCH] feat: support for non did:key --- did.go | 19 ++++++++++++++++--- did_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/did.go b/did.go index b093ce4..2c49953 100644 --- a/did.go +++ b/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,8 +41,11 @@ func (d DID) DID() DID { } func (d DID) String() string { - key, _ := mbase.Encode(mbase.Base58BTC, []byte(d.str)) - return "did:key:" + key + 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) { @@ -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 } diff --git a/did_test.go b/did_test.go index 720e733..47cfe96 100644 --- a/did_test.go +++ b/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