initial import, barely working

This commit is contained in:
Michael Muré
2025-03-12 14:13:31 +01:00
commit 581b06738c
13 changed files with 723 additions and 0 deletions

232
LICENSE.md Normal file
View File

@@ -0,0 +1,232 @@
The contents of this repository are Copyright (c) corresponding authors and
contributors, licensed under the `Permissive License Stack` meaning either of:
- Apache-2.0 Software License: https://www.apache.org/licenses/LICENSE-2.0
([...4tr2kfsq](https://dweb.link/ipfs/bafkreiankqxazcae4onkp436wag2lj3ccso4nawxqkkfckd6cg4tr2kfsq))
- MIT Software License: https://opensource.org/licenses/MIT
([...vljevcba](https://dweb.link/ipfs/bafkreiepofszg4gfe2gzuhojmksgemsub2h4uy2gewdnr35kswvljevcba))
You may not use the contents of this repository except in compliance
with one of the listed Licenses. For an extended clarification of the
intent behind the choice of Licensing please refer to
https://protocol.ai/blog/announcing-the-permissive-license-stack/
Unless required by applicable law or agreed to in writing, software
distributed under the terms listed in this notice is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See each License for the specific language
governing permissions and limitations under that License.
<!--- SPDX-License-Identifier: Apache-2.0 OR MIT -->
`SPDX-License-Identifier: Apache-2.0 OR MIT`
Verbatim copies of both licenses are included below:
<details><summary>Apache-2.0 Software License</summary>
```
Apache License
Version 2.0, January 2004
https://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
```
</details>
<details><summary>MIT Software License</summary>
```
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
```
</details>

8
Readme.md Normal file
View File

@@ -0,0 +1,8 @@
DID spec concepts:
![DID spec concepts](resources/did_brief_architecture_overview.svg)
`go-did` concepts:
![`go-did` concepts](resources/go-did%20concepts.png)

58
did-key/document.go Normal file
View File

@@ -0,0 +1,58 @@
package did_key
import (
"net/url"
"github.com/INFURA/go-did"
)
var _ did.Document = &document{}
type document struct {
id did.DID
verification did.VerificationMethod
}
func (d document) MarshalJSON() ([]byte, error) {
// TODO implement me
panic("implement me")
}
func (d document) ID() did.DID {
return d.id
}
func (d document) Controller() did.DID {
// no external controller possible for did:key
return d.id
}
func (d document) AlsoKnownAs() []url.URL {
return nil
}
func (d document) VerificationMethods() map[string]did.VerificationMethod {
return map[string]did.VerificationMethod{
d.verification.ID(): d.verification,
}
}
func (d document) Authentication() []did.VerificationMethod {
return []did.VerificationMethod{d.verification}
}
func (d document) Assertion() []did.VerificationMethod {
return []did.VerificationMethod{d.verification}
}
func (d document) KeyAgreement() []did.VerificationMethod {
return []did.VerificationMethod{d.verification}
}
func (d document) CapabilityInvocation() []did.VerificationMethod {
return []did.VerificationMethod{d.verification}
}
func (d document) CapabilityDelegation() []did.VerificationMethod {
return []did.VerificationMethod{d.verification}
}

84
did-key/key.go Normal file
View File

@@ -0,0 +1,84 @@
package did_key
import (
"fmt"
"net/url"
mbase "github.com/multiformats/go-multibase"
varint "github.com/multiformats/go-varint"
"github.com/INFURA/go-did"
)
type multicodecCode uint64
// Signature algorithms from the [did:key specification]
//
// [did:key specification]: https://w3c-ccg.github.io/did-method-key/#signature-method-creation-algorithm
const (
X25519 multicodecCode = 0xec
Ed25519 multicodecCode = 0xed
P256 multicodecCode = 0x1200
P384 multicodecCode = 0x1201
P521 multicodecCode = 0x1202
Secp256k1 multicodecCode = 0xe7
RSA multicodecCode = 0x1205
)
func Decode(identifier string) (did.DID, error) {
// baseCodec, bytes, err := mbase.Decode(identifier)
_, bytes, err := mbase.Decode(identifier)
if err != nil {
return nil, fmt.Errorf("%w: %w", did.ErrInvalidDid, err)
}
// if baseCodec != mbase.Base58BTC {
// return nil, fmt.Errorf("%w: not Base58BTC encoded", did.ErrInvalidDid)
// }
code, _, err := varint.FromUvarint(bytes)
if err != nil {
return nil, fmt.Errorf("%w: %w", did.ErrInvalidDid, err)
}
switch multicodecCode(code) {
case Ed25519, P256, Secp256k1, RSA:
return DidKey{bytes: string(bytes), code: multicodecCode(code)}, nil
}
return nil, fmt.Errorf("%w: unsupported did:key multicodec: 0x%x", did.ErrInvalidDid, code)
}
func init() {
did.RegisterMethod("key", Decode)
}
var _ did.DID = &DidKey{}
type DidKey struct {
// TODO: store a verification method instead
code multicodecCode
bytes string // as string instead of []byte to allow the == operator
}
func (d DidKey) Method() string {
return "key"
}
func (d DidKey) Path() string {
return ""
}
func (d DidKey) Query() url.Values {
return nil
}
func (d DidKey) Fragment() string {
return ""
}
func (d DidKey) Document() (did.Document, error) {
// TODO implement me
panic("implement me")
}
func (d DidKey) String() string {
key, _ := mbase.Encode(mbase.Base58BTC, []byte(d.bytes))
return "did:key:" + key
}

41
did-key/key_test.go Normal file
View File

@@ -0,0 +1,41 @@
package did_key_test
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/INFURA/go-did"
_ "github.com/INFURA/go-did/did-key"
)
func TestParseDIDKey(t *testing.T) {
str := "did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z"
d, err := did.Parse(str)
require.NoError(t, err)
require.Equal(t, str, d.String())
}
func TestMustParseDIDKey(t *testing.T) {
str := "did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z"
require.NotPanics(t, func() {
d := did.MustParse(str)
require.Equal(t, str, d.String())
})
str = "did:key:z7Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z"
require.Panics(t, func() {
did.MustParse(str)
})
}
func TestEquivalence(t *testing.T) {
did0A, err := did.Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
require.NoError(t, err)
did0B, err := did.Parse("did:key:z6Mkod5Jr3yd5SC7UDueqK4dAAw5xYJYjksy722tA9Boxc4z")
require.NoError(t, err)
did1, err := did.Parse("did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK")
require.NoError(t, err)
require.True(t, did0A == did0B)
require.False(t, did0A == did1)
}

93
did.go Normal file
View File

@@ -0,0 +1,93 @@
package did
import (
"fmt"
"strings"
"sync"
)
// Decoder is a function decoding an identifier ("foo" in "did:example:foo") into a DID.
type Decoder func(identifier string) (DID, error)
var (
decodersMu sync.RWMutex
decoders = map[string]Decoder{}
)
// RegisterMethod registers a DID decoder for a given DID method..
// Method must be the DID method (for example "key" in did:key).
func RegisterMethod(method string, decoder Decoder) {
decodersMu.Lock()
defer decodersMu.Unlock()
if !checkMethod(method) {
panic("invalid method")
}
if decoders[method] != nil {
panic("did decoder already registered")
}
decoders[method] = decoder
}
// Parse returns the DID from the string representation or an error if
// the prefix and method are incorrect, if an unknown encryption algorithm
// is specified or if the method-specific-identifier's bytes don't
// represent a public key for the specified encryption algorithm.
func Parse(str string) (DID, error) {
decodersMu.RLock()
defer decodersMu.RUnlock()
if !strings.HasPrefix(str, "did:") {
return nil, fmt.Errorf("%w: must start with \"did:\"", ErrInvalidDid)
}
method, identifier, ok := strings.Cut(str[len("did:"):], ":")
if !ok {
return nil, fmt.Errorf("%w: must have a method and an identifier", ErrInvalidDid)
}
if !checkIdentifier(identifier) {
return nil, fmt.Errorf("%w: invalid identifier characters", ErrInvalidDid)
}
decoder, ok := decoders[method]
if !ok {
return nil, fmt.Errorf("%w: %s", ErrMethodNotSupported, method)
}
return decoder(identifier)
}
// MustParse is like Parse but panics instead of returning an error.
func MustParse(str string) DID {
did, err := Parse(str)
if err != nil {
panic(err)
}
return did
}
func checkMethod(method string) bool {
if len(method) == 0 {
return false
}
for _, char := range method {
isAlpha := 'a' <= char && char <= 'z'
isDigit := '0' <= char && char <= '9'
if !isAlpha && !isDigit {
return false
}
}
return true
}
func checkIdentifier(identifier string) bool {
if len(identifier) == 0 {
return false
}
// TODO
// for _, char := range identifier {
//
// }
return true
}

19
errors.go Normal file
View File

@@ -0,0 +1,19 @@
package did
import "fmt"
// Decoder errors
var (
// ErrInvalidDid indicates that the DID supplied to the DID resolution function does not conform to valid syntax.
ErrInvalidDid = fmt.Errorf("invalid DID")
// ErrMethodNotSupported indicates that the DID method is not supported, or that the corresponding decoder
// has not been registered properly.
ErrMethodNotSupported = fmt.Errorf("DID method not supported")
)
// Resolver errors
var (
// ErrNotFound indicates that the DID resolver was unable to find the DID document for the given DID.
ErrNotFound = fmt.Errorf("did not found")
)

18
go.mod Normal file
View File

@@ -0,0 +1,18 @@
module github.com/INFURA/go-did
go 1.23
require (
github.com/multiformats/go-multibase v0.2.0
github.com/multiformats/go-varint v0.0.7
github.com/stretchr/testify v1.10.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/mr-tron/base58 v1.1.0 // indirect
github.com/multiformats/go-base32 v0.0.3 // indirect
github.com/multiformats/go-base36 v0.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

20
go.sum Normal file
View File

@@ -0,0 +1,20 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/mr-tron/base58 v1.1.0 h1:Y51FGVJ91WBqCEabAi5OPUz38eAx8DakuAm5svLcsfQ=
github.com/mr-tron/base58 v1.1.0/go.mod h1:xcD2VGqlgYjBdcBLw+TuYLr8afG+Hj8g2eTVqeSzSU8=
github.com/multiformats/go-base32 v0.0.3 h1:tw5+NhuwaOjJCC5Pp82QuXbrmLzWg7uxlMFp8Nq/kkI=
github.com/multiformats/go-base32 v0.0.3/go.mod h1:pLiuGC8y0QR3Ue4Zug5UzK9LjgbkL8NSQj0zQ5Nz/AA=
github.com/multiformats/go-base36 v0.1.0 h1:JR6TyF7JjGd3m6FbLU2cOxhC0Li8z8dLNGQ89tUg4F4=
github.com/multiformats/go-base36 v0.1.0/go.mod h1:kFGE83c6s80PklsHO9sRn2NCoffoRdUUOENyW/Vv6sM=
github.com/multiformats/go-multibase v0.2.0 h1:isdYCVLvksgWlMW9OZRYJEa9pZETFivncJHmHnnd87g=
github.com/multiformats/go-multibase v0.2.0/go.mod h1:bFBZX4lKCA/2lyOFSAoKH5SS6oPyjtnzK/XTFDPkNuk=
github.com/multiformats/go-varint v0.0.7 h1:sWSGR+f/eu5ABZA2ZpYKBILXTTs9JWpdEM/nEGOHFS8=
github.com/multiformats/go-varint v0.0.7/go.mod h1:r8PUYw/fD/SjBCiKOoDlGF6QawOELpZAu9eioSos/OU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

72
interfaces.go Normal file
View File

@@ -0,0 +1,72 @@
package did
import (
"encoding/json"
"net/url"
)
type DID interface { // --> implementation for each DID type: key, pkh ..
Method() string
Path() string
Query() url.Values
Fragment() string
Document() (Document, error)
String() string // return the full DID URL, with path, query, fragment
}
type Document interface { // --> compact implementation, get serialized into json only if necessary
json.Marshaler
// ID is the identifier of the Document, which is the DID itself.
ID() DID
// Controller is the DID that is authorized to make changes to the Document. It's often the same as ID.
Controller() DID
// AlsoKnownAs returns an optional set of URL describing ???TODO
AlsoKnownAs() []url.URL
// VerificationMethods returns all the VerificationMethod known in the document.
VerificationMethods() map[string]VerificationMethod
// Authentication defines how the DID is able to authenticate, for purposes such as logging into a website
// or engaging in any sort of challenge-response protocol.
Authentication() []VerificationMethod
// Assertion specifies how the DID subject is expected to express claims, such as for the purposes of issuing
// a Verifiable Credential.
// See https://www.w3.org/TR/vc-data-model/
Assertion() []VerificationMethod
// KeyAgreement specifies how an entity can generate encryption material in order to transmit confidential
// information intended for the DID subject, such as for the purposes of establishing a secure communication channel
// with the recipient.
KeyAgreement() []VerificationMethod
// CapabilityInvocation specifies a verification method that might be used by the DID subject to invoke a
// cryptographic capability, such as the authorization to update the DID Document.
CapabilityInvocation() []VerificationMethod
// CapabilityDelegation specifies a mechanism that might be used by the DID subject to delegate a cryptographic
// capability to another party, such as delegating the authority to access a specific HTTP API to a subordinate.
CapabilityDelegation() []VerificationMethod
// TODO: Service
// https://www.w3.org/TR/did-extensions-properties/#service-types
}
type VerificationMethod interface { // --> implementation for each method
json.Marshaler
json.Unmarshaler
// ID is a string identifier for the VerificationMethod
ID() string
// Type is a string identifier of a verification method.
// See https://www.w3.org/TR/did-extensions-properties/#verification-method-types
Type() string
// ???? TODO
Controller() DID
// Verify that 'sig' is the signed hash of 'data'
Verify(data []byte, sig []byte) bool
}

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

View File

@@ -0,0 +1,75 @@
package Ed25519
import (
"crypto/ed25519"
"encoding/json"
"errors"
"github.com/INFURA/go-did"
)
var _ did.VerificationMethod = &VerificationKey2020{}
type VerificationKey2020 struct {
id string
pubkey ed25519.PublicKey
controller did.DID
}
func NewVerificationKey2020(id string, pubkey []byte, controller did.DID) (*VerificationKey2020, error) {
if len(pubkey) != ed25519.PublicKeySize {
return nil, errors.New("invalid ed25519 public key size")
}
return &VerificationKey2020{
id: id,
pubkey: pubkey,
controller: controller,
}, nil
}
func (v VerificationKey2020) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
ID string `json:"id"`
Type string `json:"type"`
Controller string `json:"controller"`
PublicKeyMultibase string `json:"publicKeyMultibase"`
}{
ID: v.ID(),
Type: v.Type(),
Controller: v.Controller().String(),
PublicKeyMultibase: v,
})
/*
{
"id": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK#z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
"type": "Ed25519VerificationKey2020",
"controller": "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
"publicKeyMultibase": "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK"
}
*/
}
func (v VerificationKey2020) UnmarshalJSON(bytes []byte) error {
// TODO implement me
panic("implement me")
}
func (v VerificationKey2020) ID() string {
return v.id
}
func (v VerificationKey2020) Type() string {
return "Ed25519VerificationKey2020"
}
func (v VerificationKey2020) Controller() did.DID {
return v.controller
}
func (v VerificationKey2020) Verify(data []byte, sig []byte) bool {
return ed25519.Verify(v.pubkey, data, sig)
}