residual.go 864 B

1234567891011121314151617181920212223242526272829303132333435
  1. package protocol
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. // ResidualUntrusted classifies pre-transaction UART leftovers.
  7. // Any complete late frame, parser leftover, half-frame, or unexplained
  8. // residual byte is untrusted. Empty input is clean.
  9. func ResidualUntrusted(chunks [][]byte, now time.Time) error {
  10. drain := NewStreamParser(DefaultMaxPayload, 0)
  11. total := 0
  12. for _, c := range chunks {
  13. if len(c) == 0 {
  14. continue
  15. }
  16. total += len(c)
  17. for _, fr := range drain.Push(c, now) {
  18. if fr.Err != nil {
  19. return fmt.Errorf("untrusted residual parse: %w", fr.Err)
  20. }
  21. if len(fr.Raw) > 0 {
  22. return fmt.Errorf("late frame (%d bytes)", total)
  23. }
  24. }
  25. }
  26. if drain.Buffered() > 0 {
  27. return fmt.Errorf("half-frame leftover %d bytes after %d drained", drain.Buffered(), total)
  28. }
  29. if total > 0 {
  30. return fmt.Errorf("%d residual bytes", total)
  31. }
  32. return nil
  33. }