mirror of
https://github.com/meshtastic/Meshtastic-Apple.git
synced 2026-04-20 22:13:56 +00:00
* Bump version * Stop and resume DD Session Replay on app backgrounding and activation to prevent crashes * TAK server -> TestFlight (#1567) * Bump version * Message list performance fixes into 2.7.6 (#1475) * Remove extra want config call when adding a contact * App badge and unnecessary notification fixes (#1455) * - Fix for app badge not going to zero if a message arrives while you have that chat open - Fix for push notifications popping up when a message is received while that chat is open * Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message * Fix: Channels help grammer fix (#1452) * remove outdated TCP not available on Apple devices (#1450) * Update initial onboarding view * remove toggle gating for mac * Update crash reporting opt out in real time * Update onboarding text * Use mDNS text records for node name * TCP IP and port on the connection screen * Hide app icon chooser on mac * Infinite loop hang bugfixes and performance improvements for both `UserMessageList` and `ChannelMessageList` (#1465) * 2.7.5 Working Changes (#1460) * Remove extra want config call when adding a contact * App badge and unnecessary notification fixes (#1455) * - Fix for app badge not going to zero if a message arrives while you have that chat open - Fix for push notifications popping up when a message is received while that chat is open * Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message * Fix: Channels help grammer fix (#1452) * remove outdated TCP not available on Apple devices (#1450) * Update initial onboarding view * remove toggle gating for mac * Update crash reporting opt out in real time * Update onboarding text --------- Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> * UserEntity: add mostRecentMessage and unreadMessages with early exit when lastMessage is nil, and fetch 1 row (not N) otherwise * UserList: replace 5 slow calls to user.messageList with new fast calls * NodeList: always put the connected node at the top of list (if it matches the node filters) * ChannelEntity: add faster mostRecentPrivateMessage and unreadMessages which fetch 1 row (not N) * ChannelList: replace 5 calls to channel.allPrivateMessage with new fast calls * Fix incorrect appState.unreadDirectMessages calculations * MyInfoEntity: also fix unreadMessages count here to be fast, and use it for appState.unreadChannelMessages * UserMessageList: use @FetchRequest to prevent the N^2 behavior that was happening in calls to allPrivateMessages * Refactor ChannelEntityExtension and MyInfoEntityExtension to be more similar to UserEntityExtension * Remove SwiftUI-infinite-loop-causing `.id(redrawTapbacksTrigger)` in ChannelMessageList and UserMessageList (duplicate row ids) * MyInfoEntityExtension: exclude emoji tapbacks (which never get marked as read anyway) from unread message count * Add SaveChannelLinkData so MessageText and MeshtasticApp can use .sheet(item: ...) and avoid infinite loop hang due to Binding rebuild * ChannelMessageList and UserMessageList: switch to stable messageId for ForEach SwiftUI row identity * ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification * ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear * ChannelMessageList and UserMessageList: block spurious markMessagesAsRead when this View is not active --------- Co-authored-by: Garth Vander Houwen <garth@meshtastic.com> Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> * message-list-performance: revert scrolling changes (#1472) * Reverte0f0b4a0f7(ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear) * Revert "ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification" This reverts commitee1a7c4415. --------- Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> * Explicitly set unmessagable, seems unnessary * Add back missing mesh map features * Fix: "Retrieving nodes" significantly slower after reconnect extracted from #1424 (#1477) * Fix: "Retrieving nodes" significantly slower after reconnect (#1424) The node database retrieval was calling context.save() for every single NodeInfo packet received (250 saves for 250 nodes). This caused severe performance degradation on reconnect when CoreData had accumulated state. Root Cause: - nodeInfoPacket() called context.save() immediately for each node - With 250 nodes, this meant 250 individual CoreData save operations - On first connection, CoreData is fresh and fast - On reconnect, CoreData has accumulated change tracking, undo management, and memory pressure, making each save progressively slower - This resulted in 10+ second retrieval times vs 1-2 seconds initially Solution: - Added deferSave parameter to nodeInfoPacket() function - During database retrieval (.retrievingDatabase state), defer all saves - Perform a single batch save when database retrieval completes (when NONCE_ONLY_DB configCompleteID is received) - This reduces 250 saves to 1 save Performance Impact: - Eliminates N individual saves during node database sync - Reduces database retrieval time back to 1-2 seconds on reconnect - Matches first-connection performance consistently Fixes #1424 * Revert *MessageListUnified files --------- Co-authored-by: Martin Bogomolni <martinbogo@gmail.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> * Hide route lines filter from mesh map * Mesh Map: fuzz imprecise locations so they're distinguishable and clickable at the highest zoom levels (#1478) Co-authored-by: Garth Vander Houwen <garth@meshtastic.com> * Fix bad merge * Update Meshtastic/Extensions/CoreData/UserEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Views/Nodes/Helpers/Map/MapContent/MeshMapContent.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Extensions/CoreData/ChannelEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Extensions/CoreData/MyInfoEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Extensions/CoreData/ChannelEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Keep list of previous manual connections (#1484) * Keep list of previous manual connections * More descriptive manual connection rows * Merge fixes and new way to show IP on Connect view --------- Co-authored-by: Jake-B <jake-b@users.noreply.github.com> * Show who relayed messages (#1486) * Add identification for node that relayed text messages and add count for ammount of relayers of your message * Ack Relays * upsertPositionPacket: don't use future timestamps to set node's lastHeard (#1488) * R1 NEO * Neo * Update Meshtastic/Views/Settings/AppSettings.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Remove bad if * Git rid of extra environment variable * Update Meshtastic/Accessory/Transports/TCP/TCPTransport.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * MeshMap performance: quick wins (#1490) * MeshMap: change onMapCameraChange frequency to .onEnd so that zooming doesn't cause continuous SwiftUI reevaluation on every frame * MeshMapContent: factor out reducedPrecisionMapCircles into a separate function * MeshMapContent: when multiple reducedPrecisionCircles have the same (lat,lon,radius), just draw one (big perf boost in dense areas) * NodeMap performance improvements for high # positions history (#1480) * NodeMapContent: move Route Lines out of ForEach * NodeMapContent: move Convex Hull out of ForEach * NodeMapContent: Replace `position.nodePosition?` with `node` * NodeMapContent: drop unnecessary LazyVStack in showNodeHistory * NodeMapContent: hoist out nodeColorSwift * Move lineCoords, loraCoords calculations within showRouteLines, showConvexHull respectively * Hoist out repeated node.metadata?.positionFlags lookups / PositionFlags creation * NodeMapContent: remove unused @State * NodeMapSwiftUI: add NodeMapContentEquatableWrapper and NodeMapContentSignature to prevent frequent NodeMapContent recomputation and infinite render loops * NodeMapSwiftUI: disable animation during SwiftUI transactions * NodeMapContent: hoist nodeBorderColor and set allowsHitTesting(false) on history point views * NodeMapContent: prerenderHistoryPointCircle and prerenderHistoryPointArrow to avoid thousands of vector draw operations * NodeMapContent: Shared coordinate list for Route Lines and Convex Hull * NodeMapContent.prerenderHistoryPointArrow: add .frame(width: 16, height: 16) * Fix wantRangeTestPackets to correctly follow rangeTestConfig.enabled (#1489) * Fix interval drop down formatter * Clean up channel qr code functionality. * perferredPeripheralId fix * Set opt in * Retry once 5 second timer. dont throw the error * Queue for peripherals * Fix: hoplimit of dms would always fallback to hops away of the node even when configured hops was higher (#1495) * fix hops setting in dms * Fix hops for exchange position * Final fix * Don't favorite client base * Update device hardware * Prevent nil environment metrics * Bump datadog sdk * fix setting device telemetry enabled (#1515) * Update Muzi R1 Neo to actively supported * fix setting device telemetry enabled --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Don't subscribe to mqtt topic if downlink is not on (#1501) * Dont sub if no downlink * moved reload mqtt connect config * Preview enabled in connected devices (#1509) * Update Muzi R1 Neo to actively supported * Preview enabled in connected devices * Fixing indentation * Fixing indentation --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * UpdateCoreData.updateAnyPacketFrom: mirror firmware's lastHeard/snr/rssi/hopsAway update logic from NodeDB::updateFrom (#1492) * `CLIENT_BASE` add-favorite/role-change confirmation dialog (#1493) * FavoriteNodeButton: refactor task out * AccessoryManager.connectedDeviceRole helper * FavoriteNodeButton: show confirmation dialog when a CLIENT_BASE is trying to add a favorite * addContactFromURL: add comment referencing upcoming change in https://github.com/meshtastic/firmware/pull/8495 * DeviceConfig: role picker: show a warning when selecting CLIENT_BASE, similar to warning shown for ROUTER * Adjust device configuration Client Base warning text * Compass view (#1521) * Added compass view * Added Compass View * Node colors in compass * Update Muzi R1 Neo to actively supported * Update PositionPopover.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Views/Helpers/CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Views/Helpers/CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com> Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Remove discovery queue * revert problematic retry functionalliy * format file * Update & improve zh-Hans translation (#1523) * Update Muzi R1 Neo to actively supported * update & improve zh-Hans translation rt --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Update protobufs to 2.7.1 * Add long-turbo preset * Disable Range Test module when primary channel is public/unsecured (#1512) * Update Muzi R1 Neo to actively supported * Disable Range Test module when primary channel is public/unsecured Updated RangeTestConfig.swift to determine whether the primary channel (index 0) is operating without encryption or with a 1-byte minimal PSK. Disabled Range Test UI controls when on a public/default channel to prevent user interaction. Added safety enforcement in the save operation: Range Test enabled flag is automatically forced to false before sending updates to the device. Introduced a computed property isPrimaryChannelPublic following existing code patterns and security indicators (e.g., hexDescription PSK length). Matches the behavior implemented in the Android client for consistent policy across platforms. --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Add new device images * Remove print statement, get rid of cut and paste error * Bump version * update the translations (#1540) update the translations * Don't alert (with sound: .default) when updating Live Activity (#1536) * Fix adding channels (#1532) * Full translation into Spanish (#1529) * tapback with any emoji (#1538) * Call clearStaleNodes at start of sendWantConfig (#1535) * NFC Tag contact (#1537) * Accessorymanager background discovery (#1542) * Don't add new BLE devices to the device list in the backgournd * Bump version * Update Meshtastic/MeshtasticApp.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/MeshtasticApp.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Revert "Full translation into Spanish (#1529)" (#1543) This reverts commitf25fdfb89f. * Revert "update the translations (#1540)" (#1544) This reverts commitcb2fd8cc15. * Revert "NFC Tag contact (#1537)" (#1545) This reverts commit5c22b8b6e0. * Update Muzi R1 Neo to actively supported * Revert "Update Muzi R1 Neo to actively supported" * 2.7.6 Working Changes (#1479) * Bump version * Message list performance fixes into 2.7.6 (#1475) * Remove extra want config call when adding a contact * App badge and unnecessary notification fixes (#1455) * - Fix for app badge not going to zero if a message arrives while you have that chat open - Fix for push notifications popping up when a message is received while that chat is open * Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message * Fix: Channels help grammer fix (#1452) * remove outdated TCP not available on Apple devices (#1450) * Update initial onboarding view * remove toggle gating for mac * Update crash reporting opt out in real time * Update onboarding text * Use mDNS text records for node name * TCP IP and port on the connection screen * Hide app icon chooser on mac * Infinite loop hang bugfixes and performance improvements for both `UserMessageList` and `ChannelMessageList` (#1465) * 2.7.5 Working Changes (#1460) * Remove extra want config call when adding a contact * App badge and unnecessary notification fixes (#1455) * - Fix for app badge not going to zero if a message arrives while you have that chat open - Fix for push notifications popping up when a message is received while that chat is open * Fix for cancelling notifications, works now. And scroll to bottom of conversation upon new message * Fix: Channels help grammer fix (#1452) * remove outdated TCP not available on Apple devices (#1450) * Update initial onboarding view * remove toggle gating for mac * Update crash reporting opt out in real time * Update onboarding text --------- Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> * UserEntity: add mostRecentMessage and unreadMessages with early exit when lastMessage is nil, and fetch 1 row (not N) otherwise * UserList: replace 5 slow calls to user.messageList with new fast calls * NodeList: always put the connected node at the top of list (if it matches the node filters) * ChannelEntity: add faster mostRecentPrivateMessage and unreadMessages which fetch 1 row (not N) * ChannelList: replace 5 calls to channel.allPrivateMessage with new fast calls * Fix incorrect appState.unreadDirectMessages calculations * MyInfoEntity: also fix unreadMessages count here to be fast, and use it for appState.unreadChannelMessages * UserMessageList: use @FetchRequest to prevent the N^2 behavior that was happening in calls to allPrivateMessages * Refactor ChannelEntityExtension and MyInfoEntityExtension to be more similar to UserEntityExtension * Remove SwiftUI-infinite-loop-causing `.id(redrawTapbacksTrigger)` in ChannelMessageList and UserMessageList (duplicate row ids) * MyInfoEntityExtension: exclude emoji tapbacks (which never get marked as read anyway) from unread message count * Add SaveChannelLinkData so MessageText and MeshtasticApp can use .sheet(item: ...) and avoid infinite loop hang due to Binding rebuild * ChannelMessageList and UserMessageList: switch to stable messageId for ForEach SwiftUI row identity * ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification * ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear * ChannelMessageList and UserMessageList: block spurious markMessagesAsRead when this View is not active --------- Co-authored-by: Garth Vander Houwen <garth@meshtastic.com> Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> * message-list-performance: revert scrolling changes (#1472) * Reverte0f0b4a0f7(ChannelMessageList and UserMessageList: scroll to bottom onFirstAppear) * Revert "ChannelMessageList and UserMessageList: debouncedScrollToBottom; keyboardWillShowNotification/keyboardDidShowNotification" This reverts commitee1a7c4415. --------- Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> * Explicitly set unmessagable, seems unnessary * Add back missing mesh map features * Fix: "Retrieving nodes" significantly slower after reconnect extracted from #1424 (#1477) * Fix: "Retrieving nodes" significantly slower after reconnect (#1424) The node database retrieval was calling context.save() for every single NodeInfo packet received (250 saves for 250 nodes). This caused severe performance degradation on reconnect when CoreData had accumulated state. Root Cause: - nodeInfoPacket() called context.save() immediately for each node - With 250 nodes, this meant 250 individual CoreData save operations - On first connection, CoreData is fresh and fast - On reconnect, CoreData has accumulated change tracking, undo management, and memory pressure, making each save progressively slower - This resulted in 10+ second retrieval times vs 1-2 seconds initially Solution: - Added deferSave parameter to nodeInfoPacket() function - During database retrieval (.retrievingDatabase state), defer all saves - Perform a single batch save when database retrieval completes (when NONCE_ONLY_DB configCompleteID is received) - This reduces 250 saves to 1 save Performance Impact: - Eliminates N individual saves during node database sync - Reduces database retrieval time back to 1-2 seconds on reconnect - Matches first-connection performance consistently Fixes #1424 * Revert *MessageListUnified files --------- Co-authored-by: Martin Bogomolni <martinbogo@gmail.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> * Hide route lines filter from mesh map * Mesh Map: fuzz imprecise locations so they're distinguishable and clickable at the highest zoom levels (#1478) Co-authored-by: Garth Vander Houwen <garth@meshtastic.com> * Fix bad merge * Update Meshtastic/Extensions/CoreData/UserEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Views/Nodes/Helpers/Map/MapContent/MeshMapContent.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Extensions/CoreData/ChannelEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Extensions/CoreData/MyInfoEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Extensions/CoreData/ChannelEntityExtension.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Keep list of previous manual connections (#1484) * Keep list of previous manual connections * More descriptive manual connection rows * Merge fixes and new way to show IP on Connect view --------- Co-authored-by: Jake-B <jake-b@users.noreply.github.com> * Show who relayed messages (#1486) * Add identification for node that relayed text messages and add count for ammount of relayers of your message * Ack Relays * upsertPositionPacket: don't use future timestamps to set node's lastHeard (#1488) * R1 NEO * Neo * Update Meshtastic/Views/Settings/AppSettings.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Remove bad if * Git rid of extra environment variable * Update Meshtastic/Accessory/Transports/TCP/TCPTransport.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * MeshMap performance: quick wins (#1490) * MeshMap: change onMapCameraChange frequency to .onEnd so that zooming doesn't cause continuous SwiftUI reevaluation on every frame * MeshMapContent: factor out reducedPrecisionMapCircles into a separate function * MeshMapContent: when multiple reducedPrecisionCircles have the same (lat,lon,radius), just draw one (big perf boost in dense areas) * NodeMap performance improvements for high # positions history (#1480) * NodeMapContent: move Route Lines out of ForEach * NodeMapContent: move Convex Hull out of ForEach * NodeMapContent: Replace `position.nodePosition?` with `node` * NodeMapContent: drop unnecessary LazyVStack in showNodeHistory * NodeMapContent: hoist out nodeColorSwift * Move lineCoords, loraCoords calculations within showRouteLines, showConvexHull respectively * Hoist out repeated node.metadata?.positionFlags lookups / PositionFlags creation * NodeMapContent: remove unused @State * NodeMapSwiftUI: add NodeMapContentEquatableWrapper and NodeMapContentSignature to prevent frequent NodeMapContent recomputation and infinite render loops * NodeMapSwiftUI: disable animation during SwiftUI transactions * NodeMapContent: hoist nodeBorderColor and set allowsHitTesting(false) on history point views * NodeMapContent: prerenderHistoryPointCircle and prerenderHistoryPointArrow to avoid thousands of vector draw operations * NodeMapContent: Shared coordinate list for Route Lines and Convex Hull * NodeMapContent.prerenderHistoryPointArrow: add .frame(width: 16, height: 16) * Fix wantRangeTestPackets to correctly follow rangeTestConfig.enabled (#1489) * Fix interval drop down formatter * Clean up channel qr code functionality. * perferredPeripheralId fix * Set opt in * Retry once 5 second timer. dont throw the error * Queue for peripherals * Fix: hoplimit of dms would always fallback to hops away of the node even when configured hops was higher (#1495) * fix hops setting in dms * Fix hops for exchange position * Final fix * Don't favorite client base * Update device hardware * Prevent nil environment metrics * Bump datadog sdk * fix setting device telemetry enabled (#1515) * Update Muzi R1 Neo to actively supported * fix setting device telemetry enabled --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Don't subscribe to mqtt topic if downlink is not on (#1501) * Dont sub if no downlink * moved reload mqtt connect config * Preview enabled in connected devices (#1509) * Update Muzi R1 Neo to actively supported * Preview enabled in connected devices * Fixing indentation * Fixing indentation --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * UpdateCoreData.updateAnyPacketFrom: mirror firmware's lastHeard/snr/rssi/hopsAway update logic from NodeDB::updateFrom (#1492) * `CLIENT_BASE` add-favorite/role-change confirmation dialog (#1493) * FavoriteNodeButton: refactor task out * AccessoryManager.connectedDeviceRole helper * FavoriteNodeButton: show confirmation dialog when a CLIENT_BASE is trying to add a favorite * addContactFromURL: add comment referencing upcoming change in https://github.com/meshtastic/firmware/pull/8495 * DeviceConfig: role picker: show a warning when selecting CLIENT_BASE, similar to warning shown for ROUTER * Adjust device configuration Client Base warning text * Compass view (#1521) * Added compass view * Added Compass View * Node colors in compass * Update Muzi R1 Neo to actively supported * Update PositionPopover.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Views/Helpers/CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Views/Helpers/CompassView.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com> Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Remove discovery queue * revert problematic retry functionalliy * format file * Update & improve zh-Hans translation (#1523) * Update Muzi R1 Neo to actively supported * update & improve zh-Hans translation rt --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Update protobufs to 2.7.1 * Add long-turbo preset * Disable Range Test module when primary channel is public/unsecured (#1512) * Update Muzi R1 Neo to actively supported * Disable Range Test module when primary channel is public/unsecured Updated RangeTestConfig.swift to determine whether the primary channel (index 0) is operating without encryption or with a 1-byte minimal PSK. Disabled Range Test UI controls when on a public/default channel to prevent user interaction. Added safety enforcement in the save operation: Range Test enabled flag is automatically forced to false before sending updates to the device. Introduced a computed property isPrimaryChannelPublic following existing code patterns and security indicators (e.g., hexDescription PSK length). Matches the behavior implemented in the Android client for consistent policy across platforms. --------- Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> * Add new device images * Remove print statement, get rid of cut and paste error --------- Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> Co-authored-by: Martin Bogomolni <martinbogo@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: jake-b <1012393+jake-b@users.noreply.github.com> Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com> Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Charles Pinesky <25388414+Vaidios@users.noreply.github.com> Co-authored-by: Radio <35003866+radiolee@users.noreply.github.com> Co-authored-by: Jason Houk <dubsectordevelopment@gmail.com> * Initial TAK Server implementation for IOS based TAK clients This is my initial implementation for a TAK Server running inside Meshtastic-Apple. * Update marketing version to 2.7.7 * Update MessageText.swift * Update Meshtastic/Helpers/TAK/CoTMessage.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Helpers/TAK/TAKCertificateManager.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Refactor TAKServerConfig file importer to conditionally allow p12 or pem types; update CoTMessage parsing method name for clarity; enhance mTLS logging in TAKServerManager. --------- Co-authored-by: Garth Vander Houwen <garthvh@yahoo.com> Co-authored-by: Garth Vander Houwen <garth@meshtastic.com> Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> Co-authored-by: Martin Bogomolni <martinbogo@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: jake-b <1012393+jake-b@users.noreply.github.com> Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com> Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Charles Pinesky <25388414+Vaidios@users.noreply.github.com> Co-authored-by: Radio <35003866+radiolee@users.noreply.github.com> Co-authored-by: Jason Houk <dubsectordevelopment@gmail.com> Co-authored-by: MGJ <62177301+MGJ520@users.noreply.github.com> Co-authored-by: Alvaro Samudio <alvarosamudio@protonmail.com> Co-authored-by: Mathew Kamkar <578302+matkam@users.noreply.github.com> Co-authored-by: niccellular <79813408+niccellular@users.noreply.github.com> * Fix * Add localization strings * CoreData Writes wrapped in an Actor (#1569) * MeshPackets.swift into an actor and make async * Move upserts in UpdateCoreData to the MeshPackets actor * Update Meshtastic/Views/Settings/AppSettings.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update Meshtastic/Persistence/UpdateCoreData.swift Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Jake-B <jake-b@users.noreply.github.com> Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Refactor channel packet sending to use async/await pattern * Fix call * `// swiftlint:disable` overrides for TAK * Revert "Fix call" This reverts commit097ddbd43f. * Move CoreData operations onto background actor * Fix for discovery reconnect issues (#1574) Co-authored-by: Jake-B <jake-b@users.noreply.github.com> * Remove specific TAK client references Be TAK client neutral. * Update TAKDataPackageGenerator.swift Add client cert to datapackage generation for TAK clients who require it. (TAK Aware afaik) * Ble improvements (#1583) * Fix for discovery reconnect issues * Allow disconnect earlier in the connection process --------- Co-authored-by: Jake-B <jake-b@users.noreply.github.com> * Update linker flag for ios 17 crash * Update protobufs * Ru/translation (#1571) * Russian localization is 50% * Russian localization is 100% * fix Taiwan language Co-authored-by: Sergei K <svk@svk.su> Co-authored-by: Dmitriy Petrov <kenzot.fpv@gmail.com> * Fix connectToPreferredDevice parameter type to resolve compilation error (#1590) * Initial plan * Fix connectToPreferredDevice signature to accept optional device parameter Co-authored-by: garthvh <1795163+garthvh@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: garthvh <1795163+garthvh@users.noreply.github.com> * Fix TAK certificate security and storage consistency Address multiple certificate management issues identified in code review: - Fix server P12 storage/retrieval inconsistency: getActiveServerP12Data() now reads from Keychain instead of UserDefaults, matching where importServerIdentity() stores the data - Improve client P12 security: migrate storage from UserDefaults to Keychain to protect certificate data from unauthorized access and backups - Fix Keychain cleanup: clearCustomCertificateData() now properly deletes both server and client P12 data from Keychain during reset - Add force-unwrap safety: replace sec_identity_create() force-unwrap with guard statement to prevent crashes, throwing TAKServerError.tlsConfigurationFailed instead - Remove unused backup certificates: delete Resources/Certificates/backup/ folder to reduce app bundle size and avoid confusion about which certificates are active All certificate data (both server and client P12 files and passwords) now consistently use Keychain storage for improved security and proper cleanup during resets. * Update TAKDataPackageGenerator.swift Fix TAKAware's data package ingestion error. This was due to us generating a DP with certs in a cert subdirectory. However TAKAware's parser did not check subdirectories. 3 areas changed in TAKDataPackageGenerator.swift: 1. Removed certs/ subdirectory creation (old lines 50-52) — the pref file and certificates are now written directly to tempDir instead of certsDir 2. Files written to tempDir instead of certsDir — the pref file (line 72), truststore (line 80), and client cert (line 89) all go to the package root 3. Manifest zipEntry values flattened (lines 216-218) — changed from certs\filename to just filename Pref file cert/ paths left unchanged (lines 170, 172) — these are ATAK convention for the client's internal cert store path, not zip-relative paths. SwiftTAK strips them to just the filename anyway, and ATAK/iTAK interpret them the same way. The resulting zip structure will now be: Meshtastic_TAK_Server/ ├── manifest.xml ├── meshtastic-server.pref ├── truststore.p12 └── DeviceName.p12 This matches the flat structure used by all passing SwiftTAK test packages (tak-all-top.zip, tak-subfolder-all-top.zip, etc.). * Fix copilot identified issues #10 — manifest.xml: Removed certs\ prefix from zip entry paths so they match the actual flat file structure. #11 — taky-server.pref: Fixed cert/ path prefixes to match the flat structure, and replaced hardcoded atakatak passwords with YOURPASSWORD placeholders. #12 — TAKServerConfig.swift:41: Replaced force-unwraps (UTType(filenameExtension: "p12")!) with nil-coalescing fallbacks (?? .pkcs12 and ?? .plainText). #13 — TAKConnection.swift:26: Removed the unused bufferTrimSize constant. --------- Co-authored-by: Ben Meadors <benmmeadors@gmail.com> Co-authored-by: Gnome Adrift <646322+gnomeadrift@users.noreply.github.com> Co-authored-by: Zain Kergaye <62440012+ZainKergaye@users.noreply.github.com> Co-authored-by: NillRudd <102033730+NillRudd@users.noreply.github.com> Co-authored-by: Jake-B <jake-b@users.noreply.github.com> Co-authored-by: Mike Robbins <mrobbins@alum.mit.edu> Co-authored-by: Martin Bogomolni <martinbogo@gmail.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: jake-b <1012393+jake-b@users.noreply.github.com> Co-authored-by: Benjamin Faershtein <119711889+RCGV1@users.noreply.github.com> Co-authored-by: Jonathan Bennett <jbennett@incomsystems.biz> Co-authored-by: Charles Pinesky <25388414+Vaidios@users.noreply.github.com> Co-authored-by: Radio <35003866+radiolee@users.noreply.github.com> Co-authored-by: Jason Houk <dubsectordevelopment@gmail.com> Co-authored-by: MGJ <62177301+MGJ520@users.noreply.github.com> Co-authored-by: Alvaro Samudio <alvarosamudio@protonmail.com> Co-authored-by: Mathew Kamkar <578302+matkam@users.noreply.github.com> Co-authored-by: niccellular <79813408+niccellular@users.noreply.github.com> Co-authored-by: Dmitriy Q <40627944+krotesk@users.noreply.github.com> Co-authored-by: Sergei K <svk@svk.su> Co-authored-by: Dmitriy Petrov <kenzot.fpv@gmail.com> Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: garthvh <1795163+garthvh@users.noreply.github.com>
630 lines
19 KiB
Swift
630 lines
19 KiB
Swift
//
|
|
// FountainCodec.swift
|
|
// Meshtastic
|
|
//
|
|
// Fountain code (LT codes) implementation for reliable transfer over lossy mesh networks
|
|
// Based on the ATAK Meshtastic plugin protocol
|
|
//
|
|
|
|
import Foundation
|
|
import CryptoKit
|
|
import OSLog
|
|
|
|
// MARK: - Constants
|
|
|
|
enum FountainConstants {
|
|
/// Magic bytes identifying fountain packets: "FTN"
|
|
static let magic: [UInt8] = [0x46, 0x54, 0x4E]
|
|
|
|
/// Maximum payload size per block
|
|
static let blockSize = 220
|
|
|
|
/// Header size for data blocks
|
|
static let dataHeaderSize = 11
|
|
|
|
/// Size threshold for fountain coding (below this, send directly)
|
|
static let fountainThreshold = 233
|
|
|
|
/// Transfer type: CoT event
|
|
static let transferTypeCot: UInt8 = 0x00
|
|
|
|
/// Transfer type: File transfer
|
|
static let transferTypeFile: UInt8 = 0x01
|
|
|
|
/// ACK type: Transfer complete
|
|
static let ackTypeComplete: UInt8 = 0x02
|
|
|
|
/// ACK type: Need more blocks
|
|
static let ackTypeNeedMore: UInt8 = 0x03
|
|
|
|
/// ACK packet size
|
|
static let ackPacketSize = 19
|
|
}
|
|
|
|
// MARK: - Fountain Packet Types
|
|
|
|
/// A received fountain block with its metadata
|
|
struct FountainBlock {
|
|
let seed: UInt16
|
|
var indices: Set<Int>
|
|
var payload: Data
|
|
|
|
func copy() -> FountainBlock {
|
|
return FountainBlock(seed: seed, indices: indices, payload: payload)
|
|
}
|
|
}
|
|
|
|
/// State for receiving a fountain-coded transfer
|
|
class FountainReceiveState {
|
|
let transferId: UInt32
|
|
// swiftlint:disable:next identifier_name
|
|
let K: Int
|
|
let totalLength: Int
|
|
var blocks: [FountainBlock] = []
|
|
let createdAt: Date
|
|
|
|
// swiftlint:disable:next identifier_name
|
|
init(transferId: UInt32, K: Int, totalLength: Int) {
|
|
self.transferId = transferId
|
|
self.K = K
|
|
self.totalLength = totalLength
|
|
self.createdAt = Date()
|
|
}
|
|
|
|
func addBlock(_ block: FountainBlock) {
|
|
// Don't add duplicate seeds
|
|
if !blocks.contains(where: { $0.seed == block.seed }) {
|
|
blocks.append(block)
|
|
}
|
|
}
|
|
|
|
var isExpired: Bool {
|
|
// Expire after 60 seconds
|
|
return Date().timeIntervalSince(createdAt) > 60
|
|
}
|
|
}
|
|
|
|
/// Parsed fountain data block header
|
|
struct FountainDataHeader {
|
|
let transferId: UInt32 // 24-bit, stored in lower 24 bits
|
|
let seed: UInt16
|
|
// swiftlint:disable:next identifier_name
|
|
let K: UInt8
|
|
let totalLength: UInt16
|
|
}
|
|
|
|
/// Parsed fountain ACK packet
|
|
struct FountainAck {
|
|
let transferId: UInt32
|
|
let type: UInt8
|
|
let received: UInt16
|
|
let needed: UInt16
|
|
let dataHash: Data
|
|
}
|
|
|
|
// MARK: - Java-Compatible Random Number Generator
|
|
|
|
/// Java's java.util.Random implementation (Linear Congruential Generator)
|
|
/// CRITICAL: Must match Java exactly for Android interoperability
|
|
struct JavaRandom {
|
|
private var seed: Int64
|
|
|
|
init(seed: Int64) {
|
|
// Java's Random constructor: (seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)
|
|
self.seed = (seed ^ 0x5DEECE66D) & ((Int64(1) << 48) - 1)
|
|
}
|
|
|
|
/// Generate next random bits (Java's protected next(int bits) method)
|
|
mutating func next(bits: Int) -> Int32 {
|
|
// seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
|
|
seed = (seed &* 0x5DEECE66D &+ 0xB) & ((Int64(1) << 48) - 1)
|
|
return Int32(truncatingIfNeeded: seed >> (48 - bits))
|
|
}
|
|
|
|
/// Generate random int in [0, bound) - matches Java's nextInt(int bound)
|
|
mutating func nextInt(bound: Int) -> Int {
|
|
guard bound > 0 else { return 0 }
|
|
|
|
// Power of 2 optimization
|
|
if (bound & -bound) == bound {
|
|
return Int((Int64(bound) &* Int64(next(bits: 31))) >> 31)
|
|
}
|
|
|
|
// Rejection sampling to avoid modulo bias
|
|
var bits: Int32
|
|
var val: Int
|
|
repeat {
|
|
bits = next(bits: 31)
|
|
val = Int(bits) % bound
|
|
} while bits - Int32(val) + Int32(bound - 1) < 0
|
|
|
|
return val
|
|
}
|
|
|
|
/// Generate random double in [0.0, 1.0) - matches Java's nextDouble()
|
|
mutating func nextDouble() -> Double {
|
|
let high = Int64(next(bits: 26))
|
|
let low = Int64(next(bits: 27))
|
|
return Double((high << 27) + low) / Double(Int64(1) << 53)
|
|
}
|
|
}
|
|
|
|
// MARK: - Fountain Codec
|
|
|
|
/// Encoder and decoder for fountain-coded transfers
|
|
final class FountainCodec {
|
|
|
|
static let shared = FountainCodec()
|
|
|
|
private var receiveStates: [UInt32: FountainReceiveState] = [:]
|
|
|
|
private init() {}
|
|
|
|
// MARK: - Transfer ID Generation
|
|
|
|
/// Generate a unique random 24-bit transfer ID
|
|
/// CRITICAL: Must be random to avoid collisions with recent transfers
|
|
func generateTransferId() -> UInt32 {
|
|
let random = UInt32.random(in: 0...0xFFFFFF)
|
|
let time = UInt32(Date().timeIntervalSince1970) & 0xFFFF
|
|
return (random ^ time) & 0xFFFFFF
|
|
}
|
|
|
|
// MARK: - Encoding
|
|
|
|
/// Encode data into fountain-coded blocks
|
|
/// - Parameters:
|
|
/// - data: The data to encode (should include transfer type prefix)
|
|
/// - transferId: Unique transfer ID for this transmission
|
|
/// - Returns: Array of encoded block packets ready for transmission
|
|
func encode(data: Data, transferId: UInt32) -> [Data] {
|
|
// Guard against empty data
|
|
guard !data.isEmpty else {
|
|
Logger.tak.warning("Fountain encode: empty data")
|
|
return []
|
|
}
|
|
// swiftlint:disable:next identifier_name
|
|
let K = max(1, Int(ceil(Double(data.count) / Double(FountainConstants.blockSize))))
|
|
let overhead = getAdaptiveOverhead(K)
|
|
let blocksToSend = max(1, Int(ceil(Double(K) * (1.0 + overhead))))
|
|
|
|
// Split into source blocks (pad last block with zeros)
|
|
let sourceBlocks = splitIntoBlocks(data: data, K: K)
|
|
|
|
// Debug: Log source block hashes to verify they're different
|
|
for (i, block) in sourceBlocks.enumerated() {
|
|
let hash = block.prefix(8).map { String(format: "%02X", $0) }.joined()
|
|
Logger.tak.debug("Fountain sourceBlock[\(i)]: first 8 bytes = \(hash)")
|
|
}
|
|
|
|
var packets: [Data] = []
|
|
|
|
for i in 0..<blocksToSend {
|
|
let seed = generateSeed(transferId: transferId, blockIndex: i)
|
|
|
|
// Generate indices - must match Android's algorithm exactly
|
|
let indices = generateBlockIndices(seed: seed, K: K, blockIndex: i)
|
|
|
|
Logger.tak.debug("Fountain block \(i): seed=\(seed), degree=\(indices.count), indices=\(indices.sorted())")
|
|
|
|
// XOR selected source blocks together
|
|
var blockPayload = Data(repeating: 0, count: FountainConstants.blockSize)
|
|
for idx in indices {
|
|
let before = blockPayload.prefix(4).map { String(format: "%02X", $0) }.joined()
|
|
blockPayload = xor(blockPayload, sourceBlocks[idx])
|
|
let after = blockPayload.prefix(4).map { String(format: "%02X", $0) }.joined()
|
|
Logger.tak.debug(" XOR with sourceBlock[\(idx)]: \(before) → \(after)")
|
|
}
|
|
|
|
// Log final payload hash
|
|
let payloadHash = blockPayload.prefix(8).map { String(format: "%02X", $0) }.joined()
|
|
Logger.tak.debug(" Final payload first 8 bytes: \(payloadHash)")
|
|
|
|
// Build data block packet
|
|
let packet = buildDataBlock(
|
|
transferId: transferId,
|
|
seed: seed,
|
|
K: UInt8(K),
|
|
totalLength: UInt16(data.count),
|
|
payload: blockPayload
|
|
)
|
|
packets.append(packet)
|
|
}
|
|
|
|
Logger.tak.info("Fountain encode: \(data.count) bytes → \(K) source blocks → \(blocksToSend) packets")
|
|
return packets
|
|
}
|
|
|
|
/// Split data into K blocks, padding the last block with zeros
|
|
// swiftlint:disable:next identifier_name
|
|
private func splitIntoBlocks(data: Data, K: Int) -> [Data] {
|
|
var blocks: [Data] = []
|
|
for i in 0..<K {
|
|
let start = i * FountainConstants.blockSize
|
|
let end = min(start + FountainConstants.blockSize, data.count)
|
|
|
|
var block: Data
|
|
if start < data.count {
|
|
// IMPORTANT: Use Data() to rebase indices to 0
|
|
// Data slices keep original indices which causes crashes
|
|
block = Data(data[start..<end])
|
|
// Pad if necessary
|
|
if block.count < FountainConstants.blockSize {
|
|
block.append(Data(repeating: 0, count: FountainConstants.blockSize - block.count))
|
|
}
|
|
} else {
|
|
block = Data(repeating: 0, count: FountainConstants.blockSize)
|
|
}
|
|
blocks.append(block)
|
|
}
|
|
return blocks
|
|
}
|
|
|
|
/// Build a fountain data block packet
|
|
// swiftlint:disable:next identifier_name
|
|
private func buildDataBlock(transferId: UInt32, seed: UInt16, K: UInt8, totalLength: UInt16, payload: Data) -> Data {
|
|
var packet = Data()
|
|
|
|
// Magic bytes
|
|
packet.append(contentsOf: FountainConstants.magic)
|
|
|
|
// Transfer ID (24-bit, big-endian)
|
|
packet.append(UInt8((transferId >> 16) & 0xFF))
|
|
packet.append(UInt8((transferId >> 8) & 0xFF))
|
|
packet.append(UInt8(transferId & 0xFF))
|
|
|
|
// Seed (16-bit, big-endian)
|
|
packet.append(UInt8((seed >> 8) & 0xFF))
|
|
packet.append(UInt8(seed & 0xFF))
|
|
|
|
// K (number of source blocks)
|
|
packet.append(K)
|
|
|
|
// Total length (16-bit, big-endian)
|
|
packet.append(UInt8((totalLength >> 8) & 0xFF))
|
|
packet.append(UInt8(totalLength & 0xFF))
|
|
|
|
// Payload
|
|
packet.append(payload)
|
|
|
|
return packet
|
|
}
|
|
|
|
// MARK: - Decoding
|
|
|
|
/// Check if data is a fountain packet
|
|
static func isFountainPacket(_ data: Data) -> Bool {
|
|
guard data.count >= 3 else { return false }
|
|
return data[0] == FountainConstants.magic[0]
|
|
&& data[1] == FountainConstants.magic[1]
|
|
&& data[2] == FountainConstants.magic[2]
|
|
}
|
|
|
|
/// Parse a fountain data block header
|
|
func parseDataHeader(_ data: Data) -> FountainDataHeader? {
|
|
guard data.count >= FountainConstants.dataHeaderSize else { return nil }
|
|
guard Self.isFountainPacket(data) else { return nil }
|
|
|
|
let transferId = (UInt32(data[3]) << 16) | (UInt32(data[4]) << 8) | UInt32(data[5])
|
|
let seed = (UInt16(data[6]) << 8) | UInt16(data[7])
|
|
// swiftlint:disable:next identifier_name
|
|
let K = data[8]
|
|
let totalLength = (UInt16(data[9]) << 8) | UInt16(data[10])
|
|
|
|
return FountainDataHeader(transferId: transferId, seed: seed, K: K, totalLength: totalLength)
|
|
}
|
|
|
|
/// Handle an incoming fountain packet
|
|
/// - Parameters:
|
|
/// - data: The raw packet data
|
|
/// - senderNodeId: ID of the sending node
|
|
/// - Returns: Decoded data if transfer is complete, nil otherwise
|
|
func handleIncomingPacket(_ data: Data, senderNodeId: UInt32) -> (data: Data, transferId: UInt32)? {
|
|
// Clean up expired states
|
|
cleanupExpiredStates()
|
|
|
|
guard let header = parseDataHeader(data) else {
|
|
Logger.tak.warning("Invalid fountain packet header")
|
|
return nil
|
|
}
|
|
|
|
let payload = data.dropFirst(FountainConstants.dataHeaderSize)
|
|
guard payload.count == FountainConstants.blockSize else {
|
|
Logger.tak.warning("Invalid fountain payload size: \(payload.count)")
|
|
return nil
|
|
}
|
|
|
|
// Get or create receive state
|
|
let state: FountainReceiveState
|
|
if let existing = receiveStates[header.transferId] {
|
|
state = existing
|
|
} else {
|
|
state = FountainReceiveState(
|
|
transferId: header.transferId,
|
|
K: Int(header.K),
|
|
totalLength: Int(header.totalLength)
|
|
)
|
|
receiveStates[header.transferId] = state
|
|
Logger.tak.debug("New fountain transfer: id=\(header.transferId), K=\(header.K), len=\(header.totalLength)")
|
|
}
|
|
|
|
// Regenerate source indices from seed
|
|
let indices = regenerateIndices(seed: header.seed, K: state.K, transferId: header.transferId)
|
|
|
|
// Add block
|
|
let block = FountainBlock(seed: header.seed, indices: indices, payload: Data(payload))
|
|
state.addBlock(block)
|
|
|
|
Logger.tak.debug("Fountain block received: xferId=\(header.transferId), seed=\(header.seed), blocks=\(state.blocks.count)/\(state.K)")
|
|
|
|
// Try to decode if we have enough blocks
|
|
if state.blocks.count >= state.K {
|
|
if let decoded = peelingDecode(state) {
|
|
// Remove completed state
|
|
receiveStates.removeValue(forKey: header.transferId)
|
|
Logger.tak.info("Fountain decode complete: \(decoded.count) bytes from \(state.blocks.count) blocks")
|
|
return (decoded, header.transferId)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
/// Build an ACK packet
|
|
func buildAck(transferId: UInt32, type: UInt8, received: UInt16, needed: UInt16, dataHash: Data) -> Data {
|
|
var packet = Data()
|
|
|
|
// Magic bytes
|
|
packet.append(contentsOf: FountainConstants.magic)
|
|
|
|
// Transfer ID (24-bit, big-endian)
|
|
packet.append(UInt8((transferId >> 16) & 0xFF))
|
|
packet.append(UInt8((transferId >> 8) & 0xFF))
|
|
packet.append(UInt8(transferId & 0xFF))
|
|
|
|
// Type
|
|
packet.append(type)
|
|
|
|
// Received (16-bit, big-endian)
|
|
packet.append(UInt8((received >> 8) & 0xFF))
|
|
packet.append(UInt8(received & 0xFF))
|
|
|
|
// Needed (16-bit, big-endian)
|
|
packet.append(UInt8((needed >> 8) & 0xFF))
|
|
packet.append(UInt8(needed & 0xFF))
|
|
|
|
// Data hash (8 bytes)
|
|
packet.append(dataHash.prefix(8))
|
|
|
|
return packet
|
|
}
|
|
|
|
/// Parse an ACK packet
|
|
func parseAck(_ data: Data) -> FountainAck? {
|
|
guard data.count >= FountainConstants.ackPacketSize else { return nil }
|
|
guard Self.isFountainPacket(data) else { return nil }
|
|
|
|
let transferId = (UInt32(data[3]) << 16) | (UInt32(data[4]) << 8) | UInt32(data[5])
|
|
let type = data[6]
|
|
let received = (UInt16(data[7]) << 8) | UInt16(data[8])
|
|
let needed = (UInt16(data[9]) << 8) | UInt16(data[10])
|
|
let dataHash = Data(data[11..<19])
|
|
|
|
return FountainAck(transferId: transferId, type: type, received: received, needed: needed, dataHash: dataHash)
|
|
}
|
|
|
|
// MARK: - Peeling Decoder
|
|
|
|
/// Decode using the peeling algorithm
|
|
private func peelingDecode(_ state: FountainReceiveState) -> Data? {
|
|
var decoded: [Int: Data] = [:]
|
|
var workingBlocks = state.blocks.map { $0.copy() }
|
|
|
|
var progress = true
|
|
while progress && decoded.count < state.K {
|
|
progress = false
|
|
|
|
for i in 0..<workingBlocks.count {
|
|
var block = workingBlocks[i]
|
|
|
|
// Remove already-decoded indices by XORing out their data
|
|
for idx in block.indices {
|
|
if let decodedBlock = decoded[idx] {
|
|
block.payload = xor(block.payload, decodedBlock)
|
|
block.indices.remove(idx)
|
|
}
|
|
}
|
|
workingBlocks[i] = block
|
|
|
|
// If only one unknown remains, we can decode it
|
|
if block.indices.count == 1 {
|
|
let idx = block.indices.first!
|
|
decoded[idx] = block.payload
|
|
progress = true
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check if complete
|
|
guard decoded.count >= state.K else {
|
|
Logger.tak.debug("Peeling decode incomplete: \(decoded.count)/\(state.K) blocks decoded")
|
|
return nil
|
|
}
|
|
|
|
// Reassemble original data
|
|
var result = Data()
|
|
for i in 0..<state.K {
|
|
if let block = decoded[i] {
|
|
result.append(block)
|
|
} else {
|
|
Logger.tak.warning("Missing block \(i) in decoded data")
|
|
return nil
|
|
}
|
|
}
|
|
|
|
// Trim to original length
|
|
return Data(result.prefix(state.totalLength))
|
|
}
|
|
|
|
// MARK: - Helper Functions
|
|
|
|
/// Get adaptive overhead based on K
|
|
// swiftlint:disable:next identifier_name
|
|
private func getAdaptiveOverhead(_ K: Int) -> Double {
|
|
if K <= 10 { return 0.50 } // 50% for very small
|
|
else if K <= 50 { return 0.25 } // 25% for small
|
|
else { return 0.15 } // 15% for larger
|
|
}
|
|
|
|
/// Generate deterministic seed from transfer ID and block index
|
|
private func generateSeed(transferId: UInt32, blockIndex: Int) -> UInt16 {
|
|
let combined = Int(transferId) * 31337 + blockIndex * 7919
|
|
return UInt16(combined & 0xFFFF)
|
|
}
|
|
|
|
/// Generate indices for encoding a block
|
|
/// CRITICAL: Must match Android's exact algorithm for interoperability
|
|
/// Android uses Java's java.util.Random (LCG) with specific block 0 handling
|
|
// swiftlint:disable:next identifier_name
|
|
private func generateBlockIndices(seed: UInt16, K: Int, blockIndex: Int) -> Set<Int> {
|
|
var rng = JavaRandom(seed: Int64(seed))
|
|
|
|
// ALWAYS sample degree first (advances RNG state) - matches Android
|
|
let sampledDegree = sampleRobustSolitonDegree(&rng, K: K)
|
|
|
|
// For block 0: ignore sampled degree, use degree=1 instead
|
|
// For other blocks: use the sampled degree
|
|
// This matches Android's isFirstBlock logic
|
|
let degree = (blockIndex == 0) ? 1 : sampledDegree
|
|
|
|
// Select indices with RNG now advanced past degree sampling
|
|
return selectIndices(&rng, K: K, degree: degree)
|
|
}
|
|
|
|
/// Regenerate source indices from seed (must match sender's algorithm)
|
|
/// CRITICAL: Must use same RNG flow as generateBlockIndices for Android interop
|
|
// swiftlint:disable:next identifier_name
|
|
private func regenerateIndices(seed: UInt16, K: Int, transferId: UInt32) -> Set<Int> {
|
|
var rng = JavaRandom(seed: Int64(seed))
|
|
|
|
// ALWAYS sample degree first (advances RNG state) - matches Android
|
|
let sampledDegree = sampleRobustSolitonDegree(&rng, K: K)
|
|
|
|
// Check if this is block 0 (forced degree=1)
|
|
let expectedSeed0 = generateSeed(transferId: transferId, blockIndex: 0)
|
|
let degree = (seed == expectedSeed0) ? 1 : sampledDegree
|
|
|
|
// Select indices with RNG now advanced past degree sampling
|
|
return selectIndices(&rng, K: K, degree: degree)
|
|
}
|
|
|
|
/// Select source block indices using provided RNG
|
|
/// Matches Android's selectIndices algorithm exactly
|
|
// swiftlint:disable:next identifier_name
|
|
private func selectIndices(_ rng: inout JavaRandom, K: Int, degree: Int) -> Set<Int> {
|
|
var indices = Set<Int>()
|
|
|
|
// Select 'degree' unique indices
|
|
while indices.count < degree && indices.count < K {
|
|
let idx = rng.nextInt(bound: K)
|
|
indices.insert(idx)
|
|
}
|
|
|
|
return indices
|
|
}
|
|
|
|
/// Sample degree from Robust Soliton distribution using provided RNG
|
|
/// Matches Android's sampleDegree algorithm exactly
|
|
// swiftlint:disable:next identifier_name
|
|
// swiftlint:disable:next identifier_name
|
|
private func sampleRobustSolitonDegree(_ rng: inout JavaRandom, K: Int) -> Int {
|
|
let cdf = buildRobustSolitonCDF(K: K)
|
|
let u = rng.nextDouble()
|
|
|
|
for d in 1...K {
|
|
if u <= cdf[d] {
|
|
return d
|
|
}
|
|
}
|
|
return K
|
|
}
|
|
|
|
/// Build CDF for Robust Soliton distribution
|
|
// swiftlint:disable:next identifier_name
|
|
private func buildRobustSolitonCDF(K: Int, c: Double = 0.1, delta: Double = 0.5) -> [Double] {
|
|
// Guard against K <= 0
|
|
guard K > 0 else {
|
|
return [1.0] // Single element CDF
|
|
}
|
|
|
|
// Ideal Soliton distribution
|
|
var rho = [Double](repeating: 0, count: K + 1)
|
|
rho[1] = 1.0 / Double(K)
|
|
for d in 2...K {
|
|
rho[d] = 1.0 / (Double(d) * Double(d - 1))
|
|
}
|
|
|
|
// Robust Soliton addition (tau)
|
|
// swiftlint:disable:next identifier_name
|
|
let R = c * log(Double(K) / delta) * sqrt(Double(K))
|
|
var tau = [Double](repeating: 0, count: K + 1)
|
|
let threshold = Int(Double(K) / R)
|
|
|
|
for d in 1...K {
|
|
if d < threshold {
|
|
tau[d] = R / (Double(d) * Double(K))
|
|
} else if d == threshold {
|
|
tau[d] = R * log(R / delta) / Double(K)
|
|
}
|
|
}
|
|
|
|
// Combine and normalize
|
|
var mu = [Double](repeating: 0, count: K + 1)
|
|
var sum = 0.0
|
|
for d in 1...K {
|
|
mu[d] = rho[d] + tau[d]
|
|
sum += mu[d]
|
|
}
|
|
|
|
// Build CDF
|
|
var cdf = [Double](repeating: 0, count: K + 1)
|
|
var cumulative = 0.0
|
|
for d in 1...K {
|
|
cumulative += mu[d] / sum
|
|
cdf[d] = cumulative
|
|
}
|
|
|
|
return cdf
|
|
}
|
|
|
|
/// XOR two data blocks
|
|
private func xor(_ a: Data, _ b: Data) -> Data {
|
|
// IMPORTANT: Rebase inputs to ensure 0-based indices
|
|
// Data slices keep original indices which causes crashes when accessing [i]
|
|
let aData = a.startIndex == 0 ? a : Data(a)
|
|
let bData = b.startIndex == 0 ? b : Data(b)
|
|
|
|
var result = Data(count: max(aData.count, bData.count))
|
|
for i in 0..<result.count {
|
|
let byteA = i < aData.count ? aData[i] : 0
|
|
let byteB = i < bData.count ? bData[i] : 0
|
|
result[i] = byteA ^ byteB
|
|
}
|
|
return result
|
|
}
|
|
|
|
/// Compute SHA-256 hash (first 8 bytes for ACK)
|
|
static func computeHash(_ data: Data) -> Data {
|
|
let digest = SHA256.hash(data: data)
|
|
return Data(digest.prefix(8))
|
|
}
|
|
|
|
/// Clean up expired receive states
|
|
private func cleanupExpiredStates() {
|
|
let expiredIds = receiveStates.filter { $0.value.isExpired }.map { $0.key }
|
|
for id in expiredIds {
|
|
receiveStates.removeValue(forKey: id)
|
|
Logger.tak.debug("Cleaned up expired fountain state: \(id)")
|
|
}
|
|
}
|
|
}
|