/
from_address.go
94 lines (79 loc) · 2.23 KB
/
from_address.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
package account
import (
libp2pc "github.com/libp2p/go-libp2p-core/crypto"
pb "github.com/libp2p/go-libp2p-core/crypto/pb"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/textileio/go-textile-wallet/key"
"github.com/textileio/go-textile/crypto"
"golang.org/x/crypto/ed25519"
)
// FromAddress represents a account to which only the address is known. This Account
// can verify signatures, but cannot sign them.
//
// NOTE: ensure the address provided is a valid key encoded textile address.
// Some operations will panic otherwise. It's recommended that you create these
// structs through the Parse() method.
type FromAddress struct {
address string
}
func (kp *FromAddress) Address() string {
return kp.address
}
func (kp *FromAddress) Hint() (r [4]byte) {
copy(r[:], kp.publicKey()[28:])
return
}
func (kp *FromAddress) Id() (peer.ID, error) {
pub, err := kp.LibP2PPubKey()
if err != nil {
return "", nil
}
return peer.IDFromPublicKey(pub)
}
func (kp *FromAddress) LibP2PPrivKey() (*libp2pc.Ed25519PrivateKey, error) {
return nil, ErrCannotSign
}
func (kp *FromAddress) LibP2PPubKey() (*libp2pc.Ed25519PublicKey, error) {
pmes := new(pb.PublicKey)
pmes.Data = kp.publicKey()[:]
pk, err := libp2pc.UnmarshalEd25519PublicKey(pmes.GetData())
if err != nil {
return nil, err
}
epk, ok := pk.(*libp2pc.Ed25519PublicKey)
if !ok {
return nil, nil
}
return epk, nil
}
func (kp *FromAddress) Verify(input []byte, sig []byte) error {
if len(sig) != ed25519.PrivateKeySize {
return ErrInvalidSignature
}
var asig [ed25519.PrivateKeySize]byte
copy(asig[:], sig[:])
if !ed25519.Verify(kp.publicKey(), input, asig[:]) {
return ErrInvalidSignature
}
return nil
}
func (kp *FromAddress) Sign(input []byte) ([]byte, error) {
return nil, ErrCannotSign
}
func (kp *FromAddress) Encrypt(input []byte) ([]byte, error) {
pub, err := kp.LibP2PPubKey()
if err != nil {
return nil, err
}
return crypto.Encrypt(pub, input)
}
func (kp *FromAddress) Decrypt(input []byte) ([]byte, error) {
return nil, ErrCannotDecrypt
}
func (kp *FromAddress) publicKey() ed25519.PublicKey {
bytes := key.MustDecode(key.VersionByteAccountID, kp.address)
var result [ed25519.PublicKeySize]byte
copy(result[:], bytes)
slice := result[:]
return slice
}