forked from echovl/cardano-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
credential.go
114 lines (96 loc) · 2.53 KB
/
credential.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package cardano
import (
"bytes"
"fmt"
"github.com/echovl/cardano-go/crypto"
)
type StakeCredentialType uint64
const (
KeyCredential StakeCredentialType = iota
ScriptCredential
)
type keyStakeCredential struct {
_ struct{} `cbor:",toarray"`
Type StakeCredentialType
KeyHash AddrKeyHash
}
type scriptStakeCredential struct {
_ struct{} `cbor:",toarray"`
Type StakeCredentialType
ScriptHash Hash28
}
// StakeCredential is a Cardano credential.
type StakeCredential struct {
Type StakeCredentialType
KeyHash AddrKeyHash
ScriptHash Hash28
}
func (s *StakeCredential) Hash() Hash28 {
if s.Type == KeyCredential {
return s.KeyHash
} else {
return s.ScriptHash
}
}
// NewKeyCredential creates a Key Credential.
func NewKeyCredential(publicKey crypto.PubKey) (StakeCredential, error) {
keyHash, err := Blake224Hash(publicKey)
if err != nil {
return StakeCredential{}, err
}
return StakeCredential{Type: KeyCredential, KeyHash: keyHash}, nil
}
// NewKeyCredential creates a Script Credential.
func NewScriptCredential(script []byte) (StakeCredential, error) {
scriptHash, err := Blake224Hash(script)
if err != nil {
return StakeCredential{}, err
}
return StakeCredential{Type: ScriptCredential, ScriptHash: scriptHash}, nil
}
// Equal returns true if the credentials are equal.
func (s *StakeCredential) Equal(rhs StakeCredential) bool {
if s.Type != rhs.Type {
return false
}
if s.Type == KeyCredential {
return bytes.Equal(s.KeyHash, rhs.KeyHash)
} else {
return bytes.Equal(s.ScriptHash, rhs.ScriptHash)
}
}
// MarshalCBOR implements cbor.Marshaler.
func (s *StakeCredential) MarshalCBOR() ([]byte, error) {
var cred []interface{}
switch s.Type {
case KeyCredential:
cred = append(cred, s.Type, s.KeyHash)
case ScriptCredential:
cred = append(cred, s.Type, s.ScriptHash)
}
return cborEnc.Marshal(cred)
}
// UnmarshalCBOR implements cbor.Unmarshaler.
func (s *StakeCredential) UnmarshalCBOR(data []byte) error {
credType, err := getTypeFromCBORArray(data)
if err != nil {
return fmt.Errorf("cbor: cannot unmarshal CBOR array into StakeCredential (%v)", err)
}
switch StakeCredentialType(credType) {
case KeyCredential:
cred := &keyStakeCredential{}
if err := cborDec.Unmarshal(data, cred); err != nil {
return err
}
s.Type = KeyCredential
s.KeyHash = cred.KeyHash
case ScriptCredential:
cred := &scriptStakeCredential{}
if err := cborDec.Unmarshal(data, cred); err != nil {
return err
}
s.Type = ScriptCredential
s.ScriptHash = cred.ScriptHash
}
return nil
}