PacketToWire converts a Packet to wire format, which is wholly little-endian See notehub-defs.go for binary wire format of PB payload
(payload Packet, secureData bool, downlinksPending bool)
| 2218 | // PacketToWire converts a Packet to wire format, which is wholly little-endian |
| 2219 | // See notehub-defs.go for binary wire format of PB payload |
| 2220 | func (h *PacketHandler) PacketToWire(payload Packet, secureData bool, downlinksPending bool) (msg []byte, err error) { |
| 2221 | |
| 2222 | // Determine whether or not this packet will be encrypted |
| 2223 | encrypted := secureData |
| 2224 | if !h.Notehub.MayEncrypt { |
| 2225 | encrypted = false |
| 2226 | } |
| 2227 | if h.Notehub.MustEncrypt { |
| 2228 | encrypted = true |
| 2229 | } |
| 2230 | |
| 2231 | // Bail if too much data |
| 2232 | if len(payload.Data) > h.PacketMaxDownlinkData(encrypted) { |
| 2233 | err = fmt.Errorf("data length %d is greater than max allowed %d", len(payload.Data), h.PacketMaxDownlinkData(encrypted)) |
| 2234 | return |
| 2235 | } |
| 2236 | |
| 2237 | // Attempt to encode the data using Snappy, and only use the compressed data if it shrinks. |
| 2238 | // This doesn't give us extra room to pack data within the MTU because it's coming too late, |
| 2239 | // but this does save us over-the-air bytes and thus dollars. Note that the data, but not |
| 2240 | // the port, is compressed. There's no reason for this other than code flow. |
| 2241 | compressed := false |
| 2242 | if len(payload.Data) > 0 { |
| 2243 | data := snappy.Encode(nil, payload.Data) |
| 2244 | if len(data) < len(payload.Data) { |
| 2245 | payload.Data = data |
| 2246 | compressed = true |
| 2247 | } |
| 2248 | } |
| 2249 | |
| 2250 | // Construct the flag byte and insert it |
| 2251 | packetHeader := h.Notecard.PacketCidType & PacketTypeMask |
| 2252 | if encrypted { |
| 2253 | packetHeader |= PacketFlagEncrypted |
| 2254 | } |
| 2255 | if compressed { |
| 2256 | packetHeader |= PacketFlagCompressed |
| 2257 | } |
| 2258 | if downlinksPending { |
| 2259 | packetHeader |= PacketFlagDownlinksPending |
| 2260 | } |
| 2261 | msg = append(msg, packetHeader) |
| 2262 | |
| 2263 | // Append the connection ID |
| 2264 | if h.Notecard.PacketCidType != CidNone { |
| 2265 | msg = append(msg, h.Notehub.Cid...) |
| 2266 | } |
| 2267 | |
| 2268 | // If unencrypted, converting to wire is trivial |
| 2269 | if !encrypted { |
| 2270 | msg = append(msg, payload.MessagePort) |
| 2271 | msg = append(msg, payload.Data...) |
| 2272 | return |
| 2273 | } |
| 2274 | |
| 2275 | // Generate the cleartext by appending the data to the port |
| 2276 | cleartext := append([]byte{payload.MessagePort}, payload.Data...) |
| 2277 |
nothing calls this directly
no test coverage detected