-
Notifications
You must be signed in to change notification settings - Fork 13
/
bitcoin_cash.go
58 lines (51 loc) · 1.6 KB
/
bitcoin_cash.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
package coincodec
import (
"bytes"
"fmt"
"github.com/pkg/errors"
"github.com/cpacia/bchutil"
"github.com/wealdtech/go-slip44"
)
const (
hrpBCH = "bitcoincash"
)
func init() {
toBytesMap[slip44.BITCOIN_CASH] = BitcoinCashDecodeToBytes
toStringMap[slip44.BITCOIN_CASH] = BitcoinCashEncodeToString
}
// BitcoinCashDecodeToBytes converts the input string to a byte array
func BitcoinCashDecodeToBytes(input string) ([]byte, error) {
if len(input) == 0 {
return nil, errors.New("invalid address")
}
// try cashaddr first
decoded, hrp, addrType, err := bchutil.CheckDecodeCashAddress(input)
if err != nil {
// try base58
return BitcoinDecodeToBytes(input)
}
if hrp != hrpBCH {
return nil, errors.New("invalid hrp")
}
if addrType == bchutil.P2PKH {
return buildP2PKHScript(decoded), nil
} else if addrType == bchutil.P2SH {
return buildP2SHScript(decoded), nil
} else {
return nil, errors.New("unknown address type")
}
}
// BitcoinCashEncodeToString converts the input byte array to a string representation of the Bitcoin address.
func BitcoinCashEncodeToString(input []byte) (string, error) {
if len(input) == 0 {
return "", errors.New("invalid data length")
}
if bytes.HasPrefix(input, P2PKH_SCRIPT_PREFIX) {
address := bchutil.CheckEncodeCashAddress(input[3:len(input)-2], hrpBCH, bchutil.P2PKH)
return fmt.Sprintf("%s:%s", hrpBCH, address), nil
} else if bytes.HasPrefix(input, P2SH_SCRIPT_PREFIX) {
address := bchutil.CheckEncodeCashAddress(input[2:len(input)-1], hrpBCH, bchutil.P2SH)
return fmt.Sprintf("%s:%s", hrpBCH, address), nil
}
return "", errors.New("wrong script data")
}