Debian Codegraph @

crypto/canonicaljson/json.go

raw
1 /* Copyright 2016-2017 Vector Creations Ltd
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 package canonicaljson
17
18 import (
19 "encoding/binary"
20 "fmt"
21 "sort"
22 "unicode/utf8"
23
24 "github.com/tidwall/gjson"
25 )
26
27 // CanonicalJSON re-encodes the JSON in a canonical encoding. The encoding is
28 // the shortest possible encoding using integer values with sorted object keys.
29 // https://matrix.org/docs/spec/appendices#canonical-json
30 func CanonicalJSON(input []byte) ([]byte, error) {
31 if !gjson.Valid(string(input)) {
32 return nil, fmt.Errorf("invalid json")
33 }
34
35 return CanonicalJSONAssumeValid(input), nil
36 }
37
38 // CanonicalJSONAssumeValid is the same as CanonicalJSON, but assumes the
39 // input is valid JSON
40 func CanonicalJSONAssumeValid(input []byte) []byte {
41 input = CompactJSON(input, make([]byte, 0, len(input)))
42 return SortJSON(input, make([]byte, 0, len(input)))
43 }
44
45 // SortJSON reencodes the JSON with the object keys sorted by lexicographically
46 // by codepoint. The input must be valid JSON.
47 func SortJSON(input, output []byte) []byte {
48 result := gjson.ParseBytes(input)
49
50 return sortJSONValue(result, input, output)
51 }
52
53 // sortJSONValue takes a gjson.Result and sorts it. inputJSON must be the
54 // raw JSON bytes that gjson.Result points to.
55 func sortJSONValue(input gjson.Result, inputJSON, output []byte) []byte {
56 if input.IsArray() {
57 return sortJSONArray(input, inputJSON, output)
58 }
59
60 if input.IsObject() {
61 return sortJSONObject(input, inputJSON, output)
62 }
63
64 // If its neither an object nor an array then there is no sub structure
65 // to sort, so just append the raw bytes.
66 return append(output, input.Raw...)
67 }
68
69 // sortJSONArray takes a gjson.Result and sorts it, assuming its an array.
70 // inputJSON must be the raw JSON bytes that gjson.Result points to.
71 func sortJSONArray(input gjson.Result, inputJSON, output []byte) []byte {
72 sep := byte('[')
73
74 // Iterate over each value in the array and sort it.
75 input.ForEach(func(_, value gjson.Result) bool {
76 output = append(output, sep)
77 sep = ','
78 output = sortJSONValue(value, inputJSON, output)
79 return true // keep iterating
80 })
81
82 if sep == '[' {
83 // If sep is still '[' then the array was empty and we never wrote the
84 // initial '[', so we write it now along with the closing ']'.
85 output = append(output, '[', ']')
86 } else {
87 // Otherwise we end the array by writing a single ']'
88 output = append(output, ']')
89 }
90 return output
91 }
92
93 // sortJSONObject takes a gjson.Result and sorts it, assuming its an object.
94 // inputJSON must be the raw JSON bytes that gjson.Result points to.
95 func sortJSONObject(input gjson.Result, inputJSON, output []byte) []byte {
96 type entry struct {
97 key string // The parsed key string
98 rawKey string // The raw, unparsed key JSON string
99 value gjson.Result
100 }
101
102 var entries []entry
103
104 // Iterate over each key/value pair and add it to a slice
105 // that we can sort
106 input.ForEach(func(key, value gjson.Result) bool {
107 entries = append(entries, entry{
108 key: key.String(),
109 rawKey: key.Raw,
110 value: value,
111 })
112 return true // keep iterating
113 })
114
115 // Sort the slice based on the *parsed* key
116 sort.Slice(entries, func(a, b int) bool {
117 return entries[a].key < entries[b].key
118 })
119
120 sep := byte('{')
121
122 for _, entry := range entries {
123 output = append(output, sep)
124 sep = ','
125
126 // Append the raw unparsed JSON key, *not* the parsed key
127 output = append(output, entry.rawKey...)
128 output = append(output, ':')
129 output = sortJSONValue(entry.value, inputJSON, output)
130 }
131 if sep == '{' {
132 // If sep is still '{' then the object was empty and we never wrote the
133 // initial '{', so we write it now along with the closing '}'.
134 output = append(output, '{', '}')
135 } else {
136 // Otherwise we end the object by writing a single '}'
137 output = append(output, '}')
138 }
139 return output
140 }
141
142 // CompactJSON makes the encoded JSON as small as possible by removing
143 // whitespace and unneeded unicode escapes
144 func CompactJSON(input, output []byte) []byte {
145 var i int
146 for i < len(input) {
147 c := input[i]
148 i++
149 // The valid whitespace characters are all less than or equal to SPACE 0x20.
150 // The valid non-white characters are all greater than SPACE 0x20.
151 // So we can check for whitespace by comparing against SPACE 0x20.
152 if c <= ' ' {
153 // Skip over whitespace.
154 continue
155 }
156 // Add the non-whitespace character to the output.
157 output = append(output, c)
158 if c == '"' {
159 // We are inside a string.
160 for i < len(input) {
161 c = input[i]
162 i++
163 // Check if this is an escape sequence.
164 if c == '\\' {
165 escape := input[i]
166 i++
167 if escape == 'u' {
168 // If this is a unicode escape then we need to handle it specially
169 output, i = compactUnicodeEscape(input, output, i)
170 } else if escape == '/' {
171 // JSON does not require escaping '/', but allows encoders to escape it as a special case.
172 // Since the escape isn't required we remove it.
173 output = append(output, escape)
174 } else {
175 // All other permitted escapes are single charater escapes that are already in their shortest form.
176 output = append(output, '\\', escape)
177 }
178 } else {
179 output = append(output, c)
180 }
181 if c == '"' {
182 break
183 }
184 }
185 }
186 }
187 return output
188 }
189
190 // compactUnicodeEscape unpacks a 4 byte unicode escape starting at index.
191 // If the escape is a surrogate pair then decode the 6 byte \uXXXX escape
192 // that follows. Returns the output slice and a new input index.
193 func compactUnicodeEscape(input, output []byte, index int) ([]byte, int) {
194 const (
195 ESCAPES = "uuuuuuuubtnufruuuuuuuuuuuuuuuuuu"
196 HEX = "0123456789ABCDEF"
197 )
198 // If there aren't enough bytes to decode the hex escape then return.
199 if len(input)-index < 4 {
200 return output, len(input)
201 }
202 // Decode the 4 hex digits.
203 c := readHexDigits(input[index:])
204 index += 4
205 if c < ' ' {
206 // If the character is less than SPACE 0x20 then it will need escaping.
207 escape := ESCAPES[c]
208 output = append(output, '\\', escape)
209 if escape == 'u' {
210 output = append(output, '0', '0', byte('0'+(c>>4)), HEX[c&0xF])
211 }
212 } else if c == '\\' || c == '"' {
213 // Otherwise the character only needs escaping if it is a QUOTE '"' or BACKSLASH '\\'.
214 output = append(output, '\\', byte(c))
215 } else if c < 0xD800 || c >= 0xE000 {
216 // If the character isn't a surrogate pair then encoded it directly as UTF-8.
217 var buffer [4]byte
218 n := utf8.EncodeRune(buffer[:], rune(c))
219 output = append(output, buffer[:n]...)
220 } else {
221 // Otherwise the escaped character was the first part of a UTF-16 style surrogate pair.
222 // The next 6 bytes MUST be a '\uXXXX'.
223 // If there aren't enough bytes to decode the hex escape then return.
224 if len(input)-index < 6 {
225 return output, len(input)
226 }
227 // Decode the 4 hex digits from the '\uXXXX'.
228 surrogate := readHexDigits(input[index+2:])
229 index += 6
230 // Reconstruct the UCS4 codepoint from the surrogates.
231 codepoint := 0x10000 + (((c & 0x3FF) << 10) | (surrogate & 0x3FF))
232 // Encode the charater as UTF-8.
233 var buffer [4]byte
234 n := utf8.EncodeRune(buffer[:], rune(codepoint))
235 output = append(output, buffer[:n]...)
236 }
237 return output, index
238 }
239
240 // Read 4 hex digits from the input slice.
241 // Taken from https://github.com/NegativeMjark/indolentjson-rust/blob/8b959791fe2656a88f189c5d60d153be05fe3deb/src/readhex.rs#L21
242 func readHexDigits(input []byte) uint32 {
243 hex := binary.BigEndian.Uint32(input)
244 // subtract '0'
245 hex -= 0x30303030
246 // strip the higher bits, maps 'a' => 'A'
247 hex &= 0x1F1F1F1F
248 mask := hex & 0x10101010
249 // subtract 'A' - 10 - '9' - 9 = 7 from the letters.
250 hex -= mask >> 1
251 hex += mask >> 4
252 // collect the nibbles
253 hex |= hex >> 4
254 hex &= 0xFF00FF
255 hex |= hex >> 8
256 return hex & 0xFFFF
257 }