-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathbip276.go
96 lines (78 loc) · 2.47 KB
/
bip276.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
package bscript
import (
"encoding/hex"
"fmt"
"regexp"
"strconv"
"github.com/libsv/go-bk/crypto"
)
// BIP276 proposes a scheme for encoding typed bitcoin related data in a user-friendly way
// see https://github.com/moneybutton/bips/blob/master/bip-0276.mediawiki
type BIP276 struct {
Prefix string
Version int
Network int
Data []byte
}
// PrefixScript is the prefix in the BIP276 standard which
// specifies if it is a script or template.
const PrefixScript = "bitcoin-script"
// PrefixTemplate is the prefix in the BIP276 standard which
// specifies if it is a script or template.
const PrefixTemplate = "bitcoin-template"
// CurrentVersion provides the ability to
// update the structure of the data that
// follows it.
const CurrentVersion = 1
// NetworkMainnet specifies that the data is only
// valid for use on the main network.
const NetworkMainnet = 1
// NetworkTestnet specifies that the data is only
// valid for use on the test network.
const NetworkTestnet = 2
var validBIP276 = regexp.MustCompile(`^(.+?):(\d{2})(\d{2})([0-9A-Fa-f]+)([0-9A-Fa-f]{8})$`)
// EncodeBIP276 is used to encode specific (non-standard) scripts in BIP276 format.
// See https://github.com/moneybutton/bips/blob/master/bip-0276.mediawiki
func EncodeBIP276(script BIP276) string {
if script.Version == 0 || script.Version > 255 || script.Network == 0 || script.Network > 255 {
return "ERROR"
}
p, c := createBIP276(script)
return p + c
}
func createBIP276(script BIP276) (string, string) {
payload := fmt.Sprintf("%s:%.2x%.2x%x", script.Prefix, script.Network, script.Version, script.Data)
return payload, hex.EncodeToString(crypto.Sha256d([]byte(payload))[:4])
}
// DecodeBIP276 is used to decode BIP276 formatted data into specific (non-standard) scripts.
// See https://github.com/moneybutton/bips/blob/master/bip-0276.mediawiki
func DecodeBIP276(text string) (*BIP276, error) {
// Determine if regex match
res := validBIP276.FindStringSubmatch(text)
// Check if we got a result from the regex match first
if len(res) == 0 {
return nil, ErrTextNoBIP76
}
s := BIP276{
Prefix: res[1],
}
version, err := strconv.Atoi(res[2])
if err != nil {
return nil, err
}
s.Version = version
network, err := strconv.Atoi(res[3])
if err != nil {
return nil, err
}
s.Network = network
data, err := hex.DecodeString(res[4])
if err != nil {
return nil, err
}
s.Data = data
if _, checkSum := createBIP276(s); res[5] != checkSum {
return nil, ErrEncodingInvalidChecksum
}
return &s, nil
}