MCPcopy Create free account
hub / github.com/copernet/copernicus / MinimallyEncode

Function MinimallyEncode

model/script/scriptnum.go:192–237  ·  view source on GitHub ↗
(data []byte)

Source from the content-addressed store, hash-verified

190}
191
192func MinimallyEncode(data []byte) []byte {
193 dataLen := len(data)
194 if dataLen == 0 {
195 return data
196 }
197
198 // If the last byte is not 0x00 or 0x80, we are minimally encoded.
199 last := data[dataLen-1]
200 if (last & 0x7f) != 0 {
201 return data
202 }
203
204 // If the script is one byte long, then we have a zero, which encodes as an
205 // empty array.
206 if len(data) == 1 {
207 data = data[:0]
208 return data
209 }
210
211 // If the next byte has it sign bit set, then we are minimaly encoded.
212 if (data[len(data)-2] & 0x80) != 0 {
213 return data
214 }
215
216 // We are not minimally encoded, we need to figure out how much to trim.
217 for i := len(data) - 1; i > 0; i-- {
218 // We found a non zero byte, time to encode.
219 if data[i-1] != 0 {
220 if (data[i-1] & 0x80) != 0 {
221 // We found a byte with it sign bit set so we need one more
222 // byte.
223 data[i] = last
224 i++
225 } else {
226 // the sign bit is clear, we can use it.
227 data[i-1] |= last
228 }
229 data = data[:i]
230 return data
231 }
232 }
233
234 // If we the whole thing is zeros, then we have a zero.
235 data = data[:0]
236 return data
237}
238
239func IsMinimallyEncoded(data []byte, nMaxNumSize int64) bool {
240 dataLen := len(data)

Callers 1

TestMinimallyEncodeFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestMinimallyEncodeFunction · 0.68