|
1 | 1 | package multiaddr |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bytes" |
4 | 5 | "encoding/binary" |
5 | 6 | "encoding/json" |
6 | 7 | "fmt" |
@@ -217,6 +218,43 @@ func newComponent(protocol Protocol, bvalue []byte) (Component, error) { |
217 | 218 | // It ensures that we will be able to call all methods on Component without |
218 | 219 | // error. |
219 | 220 | func validateComponent(c Component) (Component, error) { |
| 221 | + if c.valueStartIdx > len(c.bytes) { |
| 222 | + return Component{}, fmt.Errorf("component valueStartIdx is greater than the length of the component's bytes") |
| 223 | + } |
| 224 | + |
| 225 | + if len(c.protocol.VCode) == 0 { |
| 226 | + return Component{}, fmt.Errorf("Component is missing its protocol's VCode field") |
| 227 | + } |
| 228 | + if len(c.bytes) < len(c.protocol.VCode) { |
| 229 | + return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.bytes), len(c.protocol.VCode)) |
| 230 | + } |
| 231 | + if !bytes.Equal([]byte(c.bytes[:len(c.protocol.VCode)]), c.protocol.VCode) { |
| 232 | + return Component{}, fmt.Errorf("component's VCode field is invalid: %v != %v", []byte(c.bytes[:len(c.protocol.VCode)]), c.protocol.VCode) |
| 233 | + } |
| 234 | + if c.protocol.Size < 0 { |
| 235 | + size, n, err := ReadVarintCode([]byte(c.bytes[len(c.protocol.VCode):])) |
| 236 | + if err != nil { |
| 237 | + return Component{}, err |
| 238 | + } |
| 239 | + if size != len(c.bytes[c.valueStartIdx:]) { |
| 240 | + return Component{}, fmt.Errorf("component value size mismatch: %d != %d", size, len(c.bytes[c.valueStartIdx:])) |
| 241 | + } |
| 242 | + |
| 243 | + if len(c.protocol.VCode)+n+size != len(c.bytes) { |
| 244 | + return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.protocol.VCode)+n+size, len(c.bytes)) |
| 245 | + } |
| 246 | + } else { |
| 247 | + // Fixed size value |
| 248 | + size := c.protocol.Size / 8 |
| 249 | + if size != len(c.bytes[c.valueStartIdx:]) { |
| 250 | + return Component{}, fmt.Errorf("component value size mismatch: %d != %d", size, len(c.bytes[c.valueStartIdx:])) |
| 251 | + } |
| 252 | + |
| 253 | + if len(c.protocol.VCode)+size != len(c.bytes) { |
| 254 | + return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.protocol.VCode)+size, len(c.bytes)) |
| 255 | + } |
| 256 | + } |
| 257 | + |
220 | 258 | _, err := c.valueAndErr() |
221 | 259 | if err != nil { |
222 | 260 | return Component{}, err |
|
0 commit comments