/
pub_key.go
92 lines (74 loc) · 2.35 KB
/
pub_key.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package types
import (
"encoding/hex"
"fmt"
"regexp"
sdk "github.com/cosmos/cosmos-sdk/types"
)
// -------------
// --- PubKey
// -------------
// PubKey contains the information of a public key contained inside a Did Document
type PubKey struct {
ID string `json:"id"`
Type string `json:"type"`
Controller sdk.AccAddress `json:"controller"`
PublicKeyHex string `json:"publicKeyHex"`
}
func NewPubKey(pubKeyID string, pubKeyType string, controller sdk.AccAddress, hexValue string) PubKey {
return PubKey{
ID: pubKeyID,
Type: pubKeyType,
Controller: controller,
PublicKeyHex: hexValue,
}
}
// Equals returns true iff pubKey and other contain the same data
func (pubKey PubKey) Equals(other PubKey) bool {
return pubKey.ID == other.ID &&
pubKey.Type == other.Type &&
pubKey.Controller.Equals(other.Controller) &&
pubKey.PublicKeyHex == other.PublicKeyHex
}
// Validate checks the data contained inside pubKey and returns an error if something is wrong
func (pubKey PubKey) Validate() sdk.Error {
regex, _ := regexp.Compile(fmt.Sprintf("^%s#keys-[0-9]+$", pubKey.Controller))
if !regex.MatchString(pubKey.ID) {
return sdk.ErrUnknownRequest(fmt.Sprintf("Invalid key id, must satisfy %s", regex))
}
if pubKey.Type != KeyTypeRsa && pubKey.Type != KeyTypeSecp256k1 && pubKey.Type != KeyTypeEd25519 {
msg := fmt.Sprintf("Invalid key type, must be either %s, %s or %s", KeyTypeRsa, KeyTypeSecp256k1, KeyTypeEd25519)
return sdk.ErrUnknownRequest(msg)
}
if _, err := hex.DecodeString(pubKey.PublicKeyHex); err != nil {
return sdk.ErrUnknownRequest("Invalid publicKeyHex value")
}
return nil
}
// --------------
// --- PubKeys
// --------------
// PubKeys represents a slice of PubKey objects
type PubKeys []PubKey
// Equals returns true iff pubKeys contains the same data as other in the same order
func (pubKeys PubKeys) Equals(other PubKeys) bool {
if len(pubKeys) != len(other) {
return false
}
for index, key := range pubKeys {
if !key.Equals(other[index]) {
return false
}
}
return true
}
// FindByID returns the key having the given id present inside the pubKeys object
// If no key has been found, returns false
func (pubKeys PubKeys) FindByID(id string) (PubKey, bool) {
for _, key := range pubKeys {
if key.ID == id {
return key, true
}
}
return PubKey{}, false
}