(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*) open Crowbar (* Generate random EIDs *) let eid_gen = choose [ const Bundle.Dtn_none; map [ bytes ] (fun s -> Bundle.Dtn s); map [ int64; int64 ] (fun n s -> Bundle.Ipn (Int64.abs n, Int64.abs s)); ] (* Generate random timestamps *) let timestamp_gen = map [ int64; int64 ] (fun time seq -> Bundle.{ time = Int64.abs time; seq = Int64.abs seq }) (* Test EID roundtrip through CBOR *) let test_eid_roundtrip eid = let cbor = Bundle.eid_to_cbor eid in match Bundle.eid_of_cbor cbor with | Ok decoded -> check_eq ~pp:Bundle.pp_eid eid decoded | Error _ -> bad_test () (* Test bundle flags roundtrip *) let test_bundle_flags_roundtrip n = let n = n land 0x07FFFF in (* Mask to valid flag bits *) let flags = Bundle.flags_of_int n in let encoded = Bundle.int_of_flags flags in let decoded = Bundle.flags_of_int encoded in check_eq ~pp:(fun fmt f -> Fmt.pf fmt "%a" Bundle.pp_flags f) flags decoded (* Test block flags roundtrip *) let test_block_flags_roundtrip n = let n = n land 0x17 in (* Mask to valid flag bits *) let flags = Bundle.block_flags_of_int n in let encoded = Bundle.int_of_block_flags flags in let decoded = Bundle.block_flags_of_int encoded in check_eq ~pp:(fun fmt f -> Fmt.pf fmt "%a" Bundle.pp_block_flags f) flags decoded (* Test bundle encode/decode roundtrip *) let test_bundle_roundtrip source dest timestamp payload = (* Skip empty payloads and very large ones *) if String.length payload = 0 || String.length payload > 65536 then bad_test () else let bundle = Bundle.v ~source ~destination:dest ~creation_timestamp:timestamp ~payload () in let encoded = Bundle.encode bundle in match Bundle.decode encoded with | Ok decoded -> check_eq ~pp:(fun fmt s -> Format.pp_print_string fmt s) (Option.value ~default:"" (Bundle.payload bundle)) (Option.value ~default:"" (Bundle.payload decoded)) | Error _ -> (* Decoding our own encoding should never fail *) fail "bundle roundtrip failed" (* Test that decoding arbitrary bytes doesn't crash *) let test_decode_no_crash data = let _ = Bundle.decode data in check true let suite = ( "bundle", [ test_case "EID roundtrip" [ eid_gen ] test_eid_roundtrip; test_case "bundle flags roundtrip" [ int ] test_bundle_flags_roundtrip; test_case "block flags roundtrip" [ int ] test_block_flags_roundtrip; test_case "encode/decode roundtrip" [ eid_gen; eid_gen; timestamp_gen; bytes ] test_bundle_roundtrip; test_case "decode no crash" [ bytes ] test_decode_no_crash; ] )