forked from hashgraph/hedera-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
id.go
55 lines (45 loc) · 1.23 KB
/
id.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
package hedera
import (
"encoding/binary"
"encoding/hex"
"fmt"
"strconv"
"strings"
)
func idFromString(s string) (shard int, realm int, num int, err error) {
values := strings.SplitN(s, ".", 3)
if len(values) != 3 {
// Was not three values separated by periods
return 0, 0, 0, fmt.Errorf("expected {shard}.{realm}.{num}")
}
shard, err = strconv.Atoi(values[0])
if err != nil {
return 0, 0, 0, err
}
realm, err = strconv.Atoi(values[1])
if err != nil {
return 0, 0, 0, err
}
num, err = strconv.Atoi(values[2])
if err != nil {
return 0, 0, 0, err
}
return
}
func idFromSolidityAddress(s string) (uint64, uint64, uint64, error) {
bytes, err := hex.DecodeString(s)
if err != nil {
return 0, 0, 0, err
}
if len(bytes) != 20 {
return 0, 0, 0, fmt.Errorf("Solidity address must be 20 bytes")
}
return uint64(binary.BigEndian.Uint32(bytes[0:4])), binary.BigEndian.Uint64(bytes[4:12]), binary.BigEndian.Uint64(bytes[12:20]), nil
}
func idToSolidityAddress(shard uint64, realm uint64, num uint64) string {
bytes := make([]byte, 20)
binary.BigEndian.PutUint32(bytes[0:4], uint32(shard))
binary.BigEndian.PutUint64(bytes[4:12], realm)
binary.BigEndian.PutUint64(bytes[12:20], num)
return hex.EncodeToString(bytes)
}