/
account.go
executable file
·104 lines (93 loc) · 2.66 KB
/
account.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
/*
Copyright (C) CESS. All rights reserved.
Copyright (C) Cumulus Encrypted Storage System. All rights reserved.
SPDX-License-Identifier: Apache-2.0
*/
package utils
import (
"errors"
"github.com/btcsuite/btcutil/base58"
"golang.org/x/crypto/blake2b"
)
var (
SSPrefix = []byte{0x53, 0x53, 0x35, 0x38, 0x50, 0x52, 0x45}
SubstratePrefix = []byte{0x2a}
CessPrefix = []byte{0x50, 0xac}
)
func ParsingPublickey(address string) ([]byte, error) {
err := VerityAddress(address, CessPrefix)
if err != nil {
err := VerityAddress(address, SubstratePrefix)
if err != nil {
return nil, errors.New("Invalid account")
}
data := base58.Decode(address)
if len(data) != (34 + len(SubstratePrefix)) {
return nil, errors.New("Public key decoding failed")
}
return data[len(SubstratePrefix) : len(data)-2], nil
} else {
data := base58.Decode(address)
if len(data) != (34 + len(CessPrefix)) {
return nil, errors.New("Public key decoding failed")
}
return data[len(CessPrefix) : len(data)-2], nil
}
}
func EncodePublicKeyAsSubstrateAccount(publicKey []byte) (string, error) {
if len(publicKey) != 32 {
return "", errors.New("Invalid public key")
}
payload := appendBytes(SubstratePrefix, publicKey)
input := appendBytes(SSPrefix, payload)
ck := blake2b.Sum512(input)
checkum := ck[:2]
address := base58.Encode(appendBytes(payload, checkum))
if address == "" {
return address, errors.New("Public key encoding failed")
}
return address, nil
}
func EncodePublicKeyAsCessAccount(publicKey []byte) (string, error) {
if len(publicKey) != 32 {
return "", errors.New("Invalid public key")
}
payload := appendBytes(CessPrefix, publicKey)
input := appendBytes(SSPrefix, payload)
ck := blake2b.Sum512(input)
checkum := ck[:2]
address := base58.Encode(appendBytes(payload, checkum))
if address == "" {
return address, errors.New("Public key encoding failed")
}
return address, nil
}
func appendBytes(data1, data2 []byte) []byte {
if data2 == nil {
return data1
}
return append(data1, data2...)
}
func VerityAddress(address string, prefix []byte) error {
decodeBytes := base58.Decode(address)
if len(decodeBytes) != (34 + len(prefix)) {
return errors.New("Public key decoding failed")
}
if decodeBytes[0] != prefix[0] {
return errors.New("Invalid account prefix")
}
pub := decodeBytes[len(prefix) : len(decodeBytes)-2]
data := append(prefix, pub...)
input := append(SSPrefix, data...)
ck := blake2b.Sum512(input)
checkSum := ck[:2]
for i := 0; i < 2; i++ {
if checkSum[i] != decodeBytes[32+len(prefix)+i] {
return errors.New("Invalid account")
}
}
if len(pub) != 32 {
return errors.New("Invalid account public key")
}
return nil
}